diff --git a/.gitignore b/.gitignore index 1a517801..6f11653e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ node_modules -examples/**/dist +dist .DS_Store yarn.lock diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 0ccc0781..00000000 --- a/LICENSE +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. \ No newline at end of file diff --git a/README.md b/README.md index f9f6f4c3..7a453fb7 100644 --- a/README.md +++ b/README.md @@ -1,88 +1,110 @@ + # graphscript [![Npm package version](https://img.shields.io/npm/v/graphscript)](https://npmjs.com/package/graphscript) [![Npm package monthly downloads](https://badgen.net/npm/dm/graphscript)](https://npmjs.ccom/package/graphscript) -[![License: LGPL v3](https://img.shields.io/badge/license-LGPL_v3-blue.svg)](https://www.gnu.org/licenses/LGPL-3.0) +[![License: AGPL v3](https://img.shields.io/badge/license-AGPL_v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) +[![Discord](https://img.shields.io/badge/community-discord-7289da.svg?sanitize=true)](https://discord.gg/CDxskSh9ZB)

-
+
For happy code!

-## This API is still under construction -There's plenty of working tools available already. However, we are randomly breaking/finding old broken code and improving things constantly as we push out a model we feel can be competitive. 100% FOSS! - -Also, we are going to turn this spec into something that supports a visual editor for games and applications built right into VSCode: [Notes](https://docs.google.com/document/d/18EZ1UgztDTi5w7B8xdgAWzMF2TDoZubMnkuVbW-y4cU/edit?usp=sharing ) -
-**GraphScript** is a highly customizable, high performance library for creating complex full stack software and library architectures. It's based around graphs hierarchies, event systems, and microservices, with an intuitive composition and node/function indexing tree system for rapid development. -

- -Check out the code in [examples](./examples) for very clear, compelling implementatons that flex our rapidly evolving feature sets. Get in touch at brewster.joshua1@gmail.com if you'd like to contribute and see this evolve. - -## Core Concepts -**graphscript** is organized by the basic principles of graph theory: - -1. **Graph:** These are contained in a shared scope. -2. **Nodes:** There is a hierarchy of objects. -3. **Connections:** Within each shared scope, properties can be linked in order to react to each other. - -Beyond these basic concepts, nodes can be direct proxies for generic javascript functions, objects or class instances from any libraries, enabling an intuitive frontend/backend hierarchical organization scheme that can plug right in as an event system for existing object-oriented programs. - -### Graphs and Graph Nodes -See [Graphs and GraphNodes](./docs/Graph.md) for more information. - -The basic connectivity framework. You can design entire apps or modules as nested object (or scope) associations with the graph node properties and event system. We've demonstrated dozens of modules in the examples and throughout the source code. Just dump them in a Graph and you can quickly build event systems with a clear readable hierarchy. This isn't a rigid system as you'll see in the [examples](./examples/). Add more GraphScript properties (which we distinguish with a *__*) using **loaders** to customize node instantiation behaviors e.g. for spawning a multithreaded app from a fairly simple hierarchical definition for the desired i/o scheme. - -### Services -See [Services](./docs/Service.md) for more information. - -This forms a microservices layer on top of the graph system. It makes it easier to communicate between separate graphs that track their own properties. We've implemented all kinds of protocols (HTTP, WebRTC, WSS, Event Sources, End-to-End encryption, etc) on top of this to demonstrate the convenience of a graph-based event system for software pipelining. - -[Included Services](./docs/Service.md#included-services) contains a reference of the services included in the main graphscript packages. - -## Packages - -### `graphscript`: A GraphScript distribution for browsers (~211kb) -#### Package Features -- Graphs, Services -- Web Workers, including convenient canvas renderer multithreading and MessageChannel pipelining -- WebRTC -- WebSockets -- Event Sources -- Session system for syncing data across connections (e.g. for game servers) -- Router for creating user systems and connection routing by user assocation. -- End 2 End encryption (via `sjcl`) - -### `graphscript-node`: A GraphScript build for Node.js (~238Kb) -#### Package Features -- Graphs, Services -- Experimental pure nodejs HTTP/HTTPS server for rapid prototyping. Tie requests to graph node properties or use a simple page templating system. -- Websocket server and Websockets (via `ws`) -- Server-Sent Events (via `better-sse`) -- Child-Processes (still need to add a polyfill for web workers) -- Session system for syncing data across connections (e.g. for game servers) -- Router for creating user systems and connection routing by user assocation. -- End 2 End encryption (via `sjcl`) - - -### `graphscript-core` : (~26kb) -#### Package Features -- A minimal GraphScript distribution featuring only Graphs, the EventHandler, and the base loaders. Should work in browser and node.js - -### `graphscript-services`: A collection of additional GraphScript services and general bloat. -#### Package Features -- User database system made for use with Mongoose/MongoDB. Includes dozens of boilerplate data structures for a simple query system with optional user permissions and access token verification. -- Entity Component System - a semi out-of-date but functional ECS format. -- WebGL plotter, can handle millions of points. -- Node templates (e.g. for use with the remoteGraphRoutes) for receiving data from sensors and stuff. - -#### Extras - - `graphscript-services.gpu`: Experimental `gpu.js` plugin. ~500kb, use it with workers for best results. - - `graphscript-services.storage`: Some BrowserFS, CSV, and Google Drive utilities. Not very complete. - -### Contributing - -Want to see this API improve faster? Please contribute or create issues and offer perspective. This repo is mostly a labor of love by Josh, with Garrett swooping in to reality check the actual utility of it from time to time. We want this to API to give you open web super powers, so we can all move on to building much more interesting end products as a community, as well as get more students, engineers, and researchers working in a collaborative development environment. This is the future! Down with knowledge and tool hoarding! - -### See also: -- [`device-decoder`](https://github.com/joshbrew/device-decoder) - Complex Browser USB and Browser or Native Mobile Bluetooth driver set that is by-default multithreaded using our web worker system. You can use the worker system to create fully-threaded pipelines from the device codec without touching the main thread. +For Browser: +`npm i graphscript` ~190kb dist + +For NodeJS +`npm i graphscript-node` ~220Kb dist + +Core (Graph and Loaders only) ~20Kb dist +`npm i graphscript-core` + +For additional services (currently gpu.js service and the compiled worker dataurl as `gsworker` (or use `graphscript/dist/Worker`)) +`npm i graphscript-services` + +# READMEs: + +Before reading and getting immediately confused by this alien API and the currently-lacking documentation, scroll through the code in [Examples](https://github.com/brainsatplay/graphscript/blob/master/examples) for very clear, compelling implementatons that flex our feature sets. + +## * [Graphs and GraphNodes](https://github.com/brainsatplay/graphscript/blob/master/docs/Graph.md) +## * [Services](https://github.com/brainsatplay/graphscript/blob/master/docs/Service.md) + * * [Included Services](https://github.com/brainsatplay/graphscript/blob/master/docs/Service.md#included-services) + +(WIP) + + +> **Note:** **graphscript** is a core library of the [Brains@Play Framework](https://github.com/brainsatplay/brainsatplay) + + +## Acknowledgments +This library is maintained by [Garrett Flynn](https://github.com/garrettmflynn) and [Joshua Brewster](https://github.com/joshbrew), who use contract work and community contributions through [Open Collective](https://opencollective.com/brainsatplay) to support themselves. + +### Backers +[Support us with a monthly donation](https://opencollective.com/brainsatplay#backer) and help us continue our activities! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Sponsors + +[Become a sponsor](https://opencollective.com/brainsatplay#sponsor) and get your logo here with a link to your site! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/_old/_oldGraph.ts b/_old/_oldGraph.ts index 7066c290..7d052ff0 100644 --- a/_old/_oldGraph.ts +++ b/_old/_oldGraph.ts @@ -43,7 +43,7 @@ export function parseFunctionFromText(method='') { // go-here-do-that utilities. Create an object node tree and make it do... things // same setup as sequencer but object/array/tag only (no functions), and can add arbitrary properties to mutate on objects // or propagate to children/parents with utility calls that get added to the objects -//Joshua Brewster and Garrett Flynn LGPLv3.0 +//Joshua Brewster and Garrett Flynn AGPLv3.0 export type OperatorType = ( //can be async ...args:any //input arguments, e.g. output from another node diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 00000000..3caac945 --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,11 @@ +# benchmarks +This is a standard benchmarking suite for graphscript implementations. + +## Snapshots +### December 28th Snapshot — Separate Special Property Definitions into Loaders +Time to Instantiation: 0.2012ms +Time to Listen: 0.0012ms + +### December 27th Snapshot — Original Benchmark +Time to Instantiate: 0.1167ms +Time to Listen: 0.0012ms \ No newline at end of file diff --git a/benchmarks/comparison/core.benchmark.ts b/benchmarks/comparison/core.benchmark.ts new file mode 100644 index 00000000..9a3756b0 --- /dev/null +++ b/benchmarks/comparison/core.benchmark.ts @@ -0,0 +1,29 @@ +import { checkPerformance } from '../utils/index' +import { clone } from '../../../js/packages/core/index' +import { Graph } from "../../../../graphscript/Graph"; +import tree from '../../../../graphscript/examples/graph/tree' +import { nTimes } from '../global'; + +const trees = Array.from({length: nTimes}).map(() => clone(tree)) // Pre-generate trees to avoid performance hit of generating them + +export const instantiate = async () => { + return checkPerformance((i) => { + let graph = new Graph({ + roots: trees[i], + }); + return graph + }, nTimes) +} + + +const listenerTree = clone(tree) +export const listen = async () => { + let graph = new Graph({ + roots: listenerTree, + }); + + return checkPerformance(async () => { + const res = graph.get('nodeA').jump(); + // console.warn('Got', res) + }, nTimes) +} \ No newline at end of file diff --git a/benchmarks/core.benchmark.ts b/benchmarks/core.benchmark.ts new file mode 100644 index 00000000..338538e3 --- /dev/null +++ b/benchmarks/core.benchmark.ts @@ -0,0 +1,31 @@ +import { checkPerformance } from './utils/index' +import { Graph } from "../src/core/Graph"; +import tree from '../examples/graph/tree' +import { nTimes } from './global'; +import { deep } from './utils/clone/index'; + +const trees = Array.from({length: nTimes}).map(() => deep(tree)) // Pre-generate trees to avoid performance hit of generating them + +export const instantiate = async () => { + return checkPerformance((i) => { + let graph = new Graph({ + roots: trees[i], + }); + return graph + }, nTimes, (graph) => { + graph.clearListeners() + }) +} + + +const listenerTree = deep(tree) +export const listen = async () => { + let graph = new Graph({ + roots: listenerTree, + }); + + return checkPerformance(async () => { + const res = graph.get('nodeA').jump(); + // console.warn('Got', res) + }, nTimes) +} \ No newline at end of file diff --git a/benchmarks/global.ts b/benchmarks/global.ts new file mode 100644 index 00000000..1b24abed --- /dev/null +++ b/benchmarks/global.ts @@ -0,0 +1 @@ +export const nTimes = 1000 \ No newline at end of file diff --git a/benchmarks/index.ts b/benchmarks/index.ts new file mode 100644 index 00000000..3c726344 --- /dev/null +++ b/benchmarks/index.ts @@ -0,0 +1,39 @@ +import * as core from './core.benchmark' + +globalThis.graphscriptDemoLog = false + +let results = { + other: {}, + graphscript: {} +} as any + +const decimals = 4 + +const message = (res, msg) => { + console.log(`Time to ${msg}: ${res.toFixed(decimals)}ms`) + return res +} + +const run = async (config) => { + return { + instantiate: await config.instantiate(), //.then((res) => message(res, 'Instantiate')), + listen: await config.listen()//.then((res) => message(res, 'Listen')), + } +} + +const runGraphScript = async () => { + // console.log(`\n--------------- GraphScript ---------------`) + const res = await run(core) + results.graphscript = res +} + +const showResults = () => { + // console.log('Ratio:', (results.graphscript.instantiate / results.graphscript.listen).toFixed(decimals)) + console.log('Time to Instantiation:', `${(results.graphscript.instantiate).toFixed(decimals)}ms`) + console.log('Time to Listen:', `${(results.graphscript.listen).toFixed(decimals)}ms`) +} + +// Run the demos +// runESCode().then(runGraphScript).then(showResults) +runGraphScript() +.then(showResults) \ No newline at end of file diff --git a/benchmarks/package.json b/benchmarks/package.json new file mode 100644 index 00000000..cc64de58 --- /dev/null +++ b/benchmarks/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-benchmark", + "type": "module" +} \ No newline at end of file diff --git a/benchmarks/tsconfig.json b/benchmarks/tsconfig.json new file mode 100644 index 00000000..8929a631 --- /dev/null +++ b/benchmarks/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "lib": ["ES2022"], // ES2020 in earlier versions + "module": "ES2022", //ESNext + "moduleResolution": "Node", + "target": "ES2022", // ES2020 in earlier versions + "esModuleInterop": true, + }, + "ts-node": { + "esm": true, + "experimentalSpecifierResolution": "node" + } +} diff --git a/benchmarks/utils/clone/check.js b/benchmarks/utils/clone/check.js new file mode 100644 index 00000000..f00c7f2f --- /dev/null +++ b/benchmarks/utils/clone/check.js @@ -0,0 +1,11 @@ +const moduleStringTag = '[object Module]' + +export const esm = (object) => { + const res = object && (!!Object.keys(object).reduce((a,b) => { + const desc = Object.getOwnPropertyDescriptor(object, b) + const isModule = (desc && desc.get && !desc.set) ? 1 : 0 + return a + isModule + }, 0) || Object.prototype.toString.call(object) === moduleStringTag) + + return !!res +} \ No newline at end of file diff --git a/benchmarks/utils/clone/drill.js b/benchmarks/utils/clone/drill.js new file mode 100644 index 00000000..2c6c34f1 --- /dev/null +++ b/benchmarks/utils/clone/drill.js @@ -0,0 +1,92 @@ +import { esm } from './check.js' + +export const abortSymbol = Symbol('abort') + + +const getObjectInfo = (obj, path = []) => { + return { + typeof: typeof obj, + name: obj?.constructor?.name, + simple: true, + object: obj && typeof obj === 'object', + path + } +} + +export const drillSimple = (obj, callback, options = {}) => { + + let accumulator = options.accumulator + if (!accumulator) accumulator = options.accumulator = {} + + const ignore = options.ignore || [] + const path = options.path || [] + const condition = options.condition || true + + const seen = [] + const fromSeen = [] + + let drill = (obj, acc={}, globalInfo) => { + + + const path = globalInfo.path + if (path.length === 0) { + const toPass = condition instanceof Function ? condition(undefined, obj, { ...getObjectInfo(obj, path) }) : condition + if (!toPass) return obj // Allow skipping top-level objects too + } + + for (let key in obj) { + if (options.abort) return + if (ignore.includes(key)) continue + + const val = obj[key] + const newPath = [...path, key] + + const info = getObjectInfo(val, newPath) + + if (info.object) { + const name = info.name + + const isESM = esm(val) // make sure to catch ESM + + if (isESM || name === 'Object' || name === 'Array') { + info.simple = true + const idx = seen.indexOf(val) + if (idx !== -1) acc[key] =fromSeen[idx] + else { + seen.push(val) + + const pass = condition instanceof Function ? condition(key, val, info) : condition + info.pass = pass + + const res = callback(key, val, info) + if (res === abortSymbol) return abortSymbol + acc[key] = res + + if (pass) { + fromSeen.push(acc[key]) + const res = drill(val, acc[key], {...globalInfo, path: newPath}) // Drill simple objects + if (res === abortSymbol) return abortSymbol + acc[key] = res + } + } + } + else { + info.simple = false + const res = callback(key, val, info) + if (res === abortSymbol) return abortSymbol + acc[key] = res + } + } else { + const res = callback(key, val, info) + if (res === abortSymbol) return abortSymbol + acc[key] = res + } + + + } + + return acc + } + + return drill(obj, accumulator, { path }) +} \ No newline at end of file diff --git a/benchmarks/utils/clone/index.js b/benchmarks/utils/clone/index.js new file mode 100644 index 00000000..fbe0bd4f --- /dev/null +++ b/benchmarks/utils/clone/index.js @@ -0,0 +1,32 @@ +import { drillSimple } from "./drill" +import { all } from "./properties" + +export const shallow = (obj, opts={}) => { + if (typeof obj === 'object') { + if (Array.isArray(obj)) { + obj = [...obj] // Clone the orignal object + opts.accumulator = [] + } else { + const keys = all(obj) + const newObj = {} + for (let key of keys) newObj[key] = obj[key] // Clone the orignal object + obj = newObj + opts.accumulator = {} + } + } + + return obj +} + +export const deep = (obj, opts={}) => { + if (typeof obj !== 'object') return obj + obj = shallow(obj, opts) + + drillSimple(obj, (key, val, info) => { + if (info.simple && info.object) return Array.isArray(val) ? [] : {} // Create new references + // else if (info.typeof === 'function') return val.bind({}) // Clone Functions + else return val + }, opts) + + return opts.accumulator +} \ No newline at end of file diff --git a/benchmarks/utils/clone/properties.js b/benchmarks/utils/clone/properties.js new file mode 100644 index 00000000..8dabfc65 --- /dev/null +++ b/benchmarks/utils/clone/properties.js @@ -0,0 +1,27 @@ + +// ------------ Get All Property Names ------------ + +const rawProperties = {} +const globalObjects = ['Object', 'Array', 'Map', 'Set'] + +export function all( obj ) { + + var props = []; + if (obj) { + do { + + const name = obj.constructor?.name + const isGlobalObject = globalObjects.includes(name) + if (globalObjects.includes(name)) { + if (!rawProperties[name]) rawProperties[name] = [...Object.getOwnPropertyNames(globalThis[name].prototype)] + } + + Object.getOwnPropertyNames( obj ).forEach(function ( prop ) { + if (isGlobalObject && rawProperties[name].includes(prop)) return; // Skip inbuilt class prototypes + if ( props.indexOf( prop ) === -1 ) props.push( prop ) + }); + } while ( obj = Object.getPrototypeOf( obj )); + } + + return props; +} diff --git a/benchmarks/utils/index.ts b/benchmarks/utils/index.ts new file mode 100644 index 00000000..dec8f468 --- /dev/null +++ b/benchmarks/utils/index.ts @@ -0,0 +1,20 @@ +// Benchmark Performance on Graph Construction +import {performance } from 'perf_hooks'; + +export const checkPerformance = async (callback, times = 1, cleanupCallback?) => { + const callbacks = Array.from({length: times}).map(() => callback) + + const timesArr: number[] = [] + let count = 0 + for await (callback of callbacks) { + const start = performance.now() + const res = await callback(count) + const end = performance.now() + if (cleanupCallback) cleanupCallback(res) + const time = end - start + timesArr.push(time) + count++ + } + return timesArr.reduce((acc, item) => acc + item, 0) / timesArr.length + +} \ No newline at end of file diff --git a/build/core/index.core.ts b/build/core/index.core.ts new file mode 100644 index 00000000..523b8a13 --- /dev/null +++ b/build/core/index.core.ts @@ -0,0 +1,4 @@ + +export * from '../../src/core/Graph' + +export * from '../../src/loaders' \ No newline at end of file diff --git a/___package.json b/build/core/package.json similarity index 62% rename from ___package.json rename to build/core/package.json index 50c712c3..8e4f21c8 100644 --- a/___package.json +++ b/build/core/package.json @@ -1,12 +1,13 @@ { "name": "graphscript-core", - "version": "0.3.2", + "version": "0.2.27", "description": "Comprehensive acyclic-graph based application architecture with microservices and networking.", - "main": "dist/index.core.js", - "module": "dist/index.core.esm.js", - "types": "dist/index.core.d.ts", + "main": "dist/index.js", + "module": "dist/index.esm.js", + "types": "dist/index.d.ts", + "type": "module", "scripts": { - "start": "tinybuild path=tinybuild.node.config.js && tinybuild && tinybuild path=tinybuild.core.config.js", + "start": "tinybuild path=tinybuild.config.js", "build": "tinybuild build", "serve": "tinybuild serve", "init": "node tinybuild/init.js", @@ -21,18 +22,5 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", - "dependencies": {}, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - }, - "devDependencies": { - "@types/node": "~18.7.15" - } + "license": "AGPL-3.0-or-later" } diff --git a/tinybuild.core.config.js b/build/core/tinybuild.config.js similarity index 93% rename from tinybuild.core.config.js rename to build/core/tinybuild.config.js index d41a4d2d..3301796e 100644 --- a/tinybuild.core.config.js +++ b/build/core/tinybuild.config.js @@ -4,7 +4,7 @@ const config = { entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types "index.core.ts" ], - outfile: "dist/index.core", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags + outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags //outdir:[] //exit point files, define for multiple bundle files bundleBrowser: true, //create plain js build? Can include globals and init scripts bundleESM: true, //create esm module js files @@ -37,4 +37,4 @@ const config = { // } } -module.exports = config; //es5 //export default config; // \ No newline at end of file +export default config; //es5 //export default config; // \ No newline at end of file diff --git a/build/main/index.ts b/build/main/index.ts new file mode 100644 index 00000000..ed03b7f8 --- /dev/null +++ b/build/main/index.ts @@ -0,0 +1,37 @@ +//frontend (browser-compatible) exports + +export * from '../../src/core/Graph' +export * from '../../src/loaders' + +export * from '../../src/services/Service' +export * from '../../src/services/unsafe/Unsafe.service' + +export * from '../../src/services/ecs/ECS.service' + +export * from '../../src/loaders/html/html.loader' + +export { DOMElement, addCustomElement } from '../../src/loaders/html/DOMElement' +export * from '../../src/loaders/html/wc.loader' //includes the web component spec, html loader is a little leaner otherwise + +export * from '../../src/services/e2ee/E2EE.service' + +//export * from './services/gpu/GPU.service' + +export * from '../../src/services/http/HTTP.browser' + +export * from '../../src/services/sse/SSE.browser' + +export * from '../../src/services/wss/WSS.browser' + +//export * from './services/struct/Struct.frontend' + +export * from '../../src/services/webrtc/WebRTC.browser' + +export * from '../../src/services/worker/Worker.service' +export * from '../../src/services/worker/ProxyListener' +export * from '../../src/services/worker/WorkerCanvas' +export * from '../../src/services/worker/Subprocess' + +export * from '../../src/services/sessions/sessions.service' + +export * from '../../src/services/router/Router' \ No newline at end of file diff --git a/build/main/package-lock.json b/build/main/package-lock.json new file mode 100644 index 00000000..e0c0ea18 --- /dev/null +++ b/build/main/package-lock.json @@ -0,0 +1,42 @@ +{ + "name": "graphscript", + "version": "0.2.28", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "graphscript", + "version": "0.2.28", + "license": "AGPL-3.0-or-later", + "dependencies": { + "sjcl": "^1.0.8", + "web-worker": "^1.2.0" + } + }, + "node_modules/sjcl": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/sjcl/-/sjcl-1.0.8.tgz", + "integrity": "sha512-LzIjEQ0S0DpIgnxMEayM1rq9aGwGRG4OnZhCdjx7glTaJtf4zRfpg87ImfjSJjoW9vKpagd82McDOwbRT5kQKQ==", + "engines": { + "node": "*" + } + }, + "node_modules/web-worker": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + } + }, + "dependencies": { + "sjcl": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/sjcl/-/sjcl-1.0.8.tgz", + "integrity": "sha512-LzIjEQ0S0DpIgnxMEayM1rq9aGwGRG4OnZhCdjx7glTaJtf4zRfpg87ImfjSJjoW9vKpagd82McDOwbRT5kQKQ==" + }, + "web-worker": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + } + } +} diff --git a/build/main/package.json b/build/main/package.json new file mode 100644 index 00000000..42f68d31 --- /dev/null +++ b/build/main/package.json @@ -0,0 +1,29 @@ +{ + "name": "graphscript", + "version": "0.2.28", + "description": "Comprehensive acyclic-graph based application architecture with microservices and networking", + "main": "dist/index.js", + "module": "dist/index.esm.js", + "types": "dist/index.d.ts", + "type": "module", + "scripts": { + "start": "tinybuild", + "build": "tinybuild build", + "serve": "tinybuild serve", + "init": "node tinybuild/init.js", + "concurrent": "concurrently \"npm run python\" \"npm start\"", + "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", + "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", + "python": "python python/server.py", + "pip": "pip install quart && pip install websockets", + "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" + }, + "keywords": [ + "esbuild" + ], + "author": "Joshua Brewster", + "license": "AGPL-3.0-or-later", + "dependencies": { + "web-worker": "^1.2.0" + } +} diff --git a/build/main/tinybuild.config.js b/build/main/tinybuild.config.js new file mode 100644 index 00000000..77f2ddfb --- /dev/null +++ b/build/main/tinybuild.config.js @@ -0,0 +1,40 @@ + +const config = { + bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) + entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types + "index.ts" + ], + outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags + //outdir:[] //exit point files, define for multiple bundle files + bundleBrowser: true, //create plain js build? Can include globals and init scripts + bundleESM: true, //create esm module js files + bundleTypes: true, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) + bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files + bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. + //minify: false, + minifyWhitespace:true, + sourcemap: false + //platform:'node' //for bundling the node.ts file + //globalThis:null //'mymodule' + //globals:{'index.js':['Graph']} + //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }} + }, + server: false//{ //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) + // debug: false, + // protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well + // host: "localhost", //'localhost' or '127.0.0.1' etc. + // port: 8080, //e.g. port 80, 443, 8000 + // startpage: "index.html", //home page + // socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost + // hotreload: 5000, //hotreload websocket server port + // //watch: ['../'], //watch additional directories other than the current working directory + // pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) + // python: false,//7000, //quart server port (configured via the python server script file still) + // python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) + // errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. + // certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions + // keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions + // } +} + +export default config; //es5 //export default config; // \ No newline at end of file diff --git a/build/node/index.node.ts b/build/node/index.node.ts new file mode 100644 index 00000000..10a675c3 --- /dev/null +++ b/build/node/index.node.ts @@ -0,0 +1,35 @@ +//frontend (browser-compatible) exports + +export * from '../../src/core/Graph' +export * from '../../src/loaders' + +export * from '../../src/services/Service' +export * from '../../src/services/unsafe/Unsafe.service' + +export * from '../../src/services/ecs/ECS.service' + +// export * from '../../src/services/dom/DOM.service' +// export * from '../../src/services/dom/components/index' + +export * from '../../src/services/e2ee/E2EE.service' + +//export * from '../../src/services/gpu/GPU.service' + +export * from '../../src/services/http/HTTP.node' + +export * from '../../src/services/sse/SSE.node' + +export * from '../../src/services/wss/WSS.node' + +export * from '../../src/services/cmd/CMD.node' + +//export * from '../../src/services/struct/Struct.frontend' + +// export * from '../../src/services/webrtc/WebRTC.browser' + +//export * from '../../src/services/worker/Worker.service' +//export * from '../../src/services/worker/Subprocess' + +export * from '../../src/services/sessions/sessions.service' + +export * from '../../src/services/router/Router' \ No newline at end of file diff --git a/build/node/package-lock.json b/build/node/package-lock.json new file mode 100644 index 00000000..736d3c33 --- /dev/null +++ b/build/node/package-lock.json @@ -0,0 +1,121 @@ +{ + "name": "graphscript-node", + "version": "0.2.27", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "graphscript-node", + "version": "0.2.27", + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "sjcl": "^1.0.8", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + }, + "devDependencies": { + "@types/node": "~18.7.15" + } + }, + "node_modules/@types/node": { + "version": "18.7.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.23.tgz", + "integrity": "sha512-DWNcCHolDq0ZKGizjx2DZjR/PqsYwAcYUJmfMWqtVU2MBMG5Mo+xFZrhGId5r/O5HOuMPyQEcM6KUBp5lBZZBg==", + "dev": true + }, + "node_modules/better-sse": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz", + "integrity": "sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA==", + "engines": { + "node": ">=12", + "pnpm": ">=6" + } + }, + "node_modules/brainsatplay-math": { + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + }, + "node_modules/bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, + "node_modules/sjcl": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/sjcl/-/sjcl-1.0.8.tgz", + "integrity": "sha512-LzIjEQ0S0DpIgnxMEayM1rq9aGwGRG4OnZhCdjx7glTaJtf4zRfpg87ImfjSJjoW9vKpagd82McDOwbRT5kQKQ==", + "engines": { + "node": "*" + } + }, + "node_modules/web-worker": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + }, + "node_modules/ws": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", + "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + }, + "dependencies": { + "@types/node": { + "version": "18.7.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.23.tgz", + "integrity": "sha512-DWNcCHolDq0ZKGizjx2DZjR/PqsYwAcYUJmfMWqtVU2MBMG5Mo+xFZrhGId5r/O5HOuMPyQEcM6KUBp5lBZZBg==", + "dev": true + }, + "better-sse": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz", + "integrity": "sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA==" + }, + "brainsatplay-math": { + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + }, + "bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, + "sjcl": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/sjcl/-/sjcl-1.0.8.tgz", + "integrity": "sha512-LzIjEQ0S0DpIgnxMEayM1rq9aGwGRG4OnZhCdjx7glTaJtf4zRfpg87ImfjSJjoW9vKpagd82McDOwbRT5kQKQ==" + }, + "web-worker": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + }, + "ws": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", + "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", + "requires": {} + } + } +} diff --git a/__package.json b/build/node/package.json similarity index 74% rename from __package.json rename to build/node/package.json index f9e4ebad..6b97fbc9 100644 --- a/__package.json +++ b/build/node/package.json @@ -1,11 +1,12 @@ { "name": "graphscript-node", - "version": "0.3.2", + "version": "0.2.27", "description": "Comprehensive acyclic-graph based application architecture with microservices and networking", - "main": "dist/index.node.js", - "types": "dist/index.node.d.ts", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "type": "module", "scripts": { - "start": "tinybuild path=tinybuild.node.config.js && tinybuild && tinybuild path=tinybuild.core.config.js", + "start": "tinybuild path=tinybuild.config.js", "build": "tinybuild build", "serve": "tinybuild serve", "init": "node tinybuild/init.js", @@ -20,13 +21,14 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "better-sse": "~0.10.0", - "brainsatplay-math": "~0.1.0", + "better-sse": "^0.8.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", + "sjcl": "^1.0.8", "web-worker": "~1.2.0", - "ws": "~8.14.2" + "ws": "~8.11.0" }, "nodemonConfig": { "env": { @@ -38,7 +40,6 @@ ] }, "devDependencies": { - "@types/node": "~18.7.15", - "@types/ws": "^8.5.3" + "@types/node": "~18.7.15" } } diff --git a/tinybuild.node.config.js b/build/node/tinybuild.config.js similarity index 93% rename from tinybuild.node.config.js rename to build/node/tinybuild.config.js index 8268b979..6f6a9933 100644 --- a/tinybuild.node.config.js +++ b/build/node/tinybuild.config.js @@ -4,7 +4,7 @@ const config = { entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types "index.node.ts" ], - outfile: "dist/index.node", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags + outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags //outdir:[] //exit point files, define for multiple bundle files bundleBrowser: false, //create plain js build? Can include globals and init scripts bundleESM: false, //create esm module js files @@ -37,4 +37,4 @@ const config = { // } } -module.exports = config; //es5 //export default config; // \ No newline at end of file +export default config; //es5 //export default config; // \ No newline at end of file diff --git a/coverage/clover.xml b/coverage/clover.xml new file mode 100644 index 00000000..b912105c --- /dev/null +++ b/coverage/clover.xml @@ -0,0 +1,2261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/coverage/coverage-final.json b/coverage/coverage-final.json new file mode 100644 index 00000000..4351651d --- /dev/null +++ b/coverage/coverage-final.json @@ -0,0 +1,20 @@ +{"/Users/garrettflynn/Documents/Github/graphscript/examples/graph/operations.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/examples/graph/operations.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":0}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":56}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":26}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":0}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":63}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":59}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":53}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":0}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":19}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":15}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":19}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":14}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":0}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":17}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":23}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":18}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":22}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":1}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":0}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":37}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":0}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":28}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":0}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":21}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":26}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":12}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":0}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":43}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":0}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":24}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":19}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":52}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":36}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":34}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":61}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":33}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":54}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":5}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":0}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":25}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":39}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":0}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":29}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":21}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":16}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":7}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":0}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":38}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":0}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":37}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":29}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":42}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":6}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":0}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":48}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":33}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":25}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":0}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":17}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":1}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":0}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":27}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":40}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":1}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":0}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":27}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":5}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":35}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":50}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":6}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":5}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":36}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":25}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":83}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":43}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":9}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":6}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":5}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":41}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":25}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":53}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":37}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":27}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":9}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":6}},"85":{"start":{"line":86,"column":0},"end":{"line":86,"column":5}},"86":{"start":{"line":87,"column":0},"end":{"line":87,"column":42}},"87":{"start":{"line":88,"column":0},"end":{"line":88,"column":25}},"88":{"start":{"line":89,"column":0},"end":{"line":89,"column":53}},"89":{"start":{"line":90,"column":0},"end":{"line":90,"column":64}},"90":{"start":{"line":91,"column":0},"end":{"line":91,"column":27}},"91":{"start":{"line":92,"column":0},"end":{"line":92,"column":9}},"92":{"start":{"line":93,"column":0},"end":{"line":93,"column":6}},"93":{"start":{"line":94,"column":0},"end":{"line":94,"column":5}},"94":{"start":{"line":95,"column":0},"end":{"line":95,"column":44}},"95":{"start":{"line":96,"column":0},"end":{"line":96,"column":91}},"96":{"start":{"line":97,"column":0},"end":{"line":97,"column":6}},"97":{"start":{"line":98,"column":0},"end":{"line":98,"column":5}},"98":{"start":{"line":99,"column":0},"end":{"line":99,"column":48}},"99":{"start":{"line":100,"column":0},"end":{"line":100,"column":25}},"100":{"start":{"line":101,"column":0},"end":{"line":101,"column":58}},"101":{"start":{"line":102,"column":0},"end":{"line":102,"column":25}},"102":{"start":{"line":103,"column":0},"end":{"line":103,"column":27}},"103":{"start":{"line":104,"column":0},"end":{"line":104,"column":9}},"104":{"start":{"line":105,"column":0},"end":{"line":105,"column":6}},"105":{"start":{"line":106,"column":0},"end":{"line":106,"column":5}},"106":{"start":{"line":107,"column":0},"end":{"line":107,"column":42}},"107":{"start":{"line":108,"column":0},"end":{"line":108,"column":25}},"108":{"start":{"line":109,"column":0},"end":{"line":109,"column":53}},"109":{"start":{"line":110,"column":0},"end":{"line":110,"column":64}},"110":{"start":{"line":111,"column":0},"end":{"line":111,"column":9}},"111":{"start":{"line":112,"column":0},"end":{"line":112,"column":6}},"112":{"start":{"line":113,"column":0},"end":{"line":113,"column":5}},"113":{"start":{"line":114,"column":0},"end":{"line":114,"column":40}},"114":{"start":{"line":115,"column":0},"end":{"line":115,"column":62}},"115":{"start":{"line":116,"column":0},"end":{"line":116,"column":6}},"116":{"start":{"line":117,"column":0},"end":{"line":117,"column":0}},"117":{"start":{"line":118,"column":0},"end":{"line":118,"column":0}},"118":{"start":{"line":119,"column":0},"end":{"line":119,"column":36}},"119":{"start":{"line":120,"column":0},"end":{"line":120,"column":5}},"120":{"start":{"line":121,"column":0},"end":{"line":121,"column":37}},"121":{"start":{"line":122,"column":0},"end":{"line":122,"column":25}},"122":{"start":{"line":123,"column":0},"end":{"line":123,"column":74}},"123":{"start":{"line":124,"column":0},"end":{"line":124,"column":34}},"124":{"start":{"line":125,"column":0},"end":{"line":125,"column":9}},"125":{"start":{"line":126,"column":0},"end":{"line":126,"column":6}},"126":{"start":{"line":127,"column":0},"end":{"line":127,"column":5}},"127":{"start":{"line":128,"column":0},"end":{"line":128,"column":33}},"128":{"start":{"line":129,"column":0},"end":{"line":129,"column":25}},"129":{"start":{"line":130,"column":0},"end":{"line":130,"column":59}},"130":{"start":{"line":131,"column":0},"end":{"line":131,"column":60}},"131":{"start":{"line":132,"column":0},"end":{"line":132,"column":34}},"132":{"start":{"line":133,"column":0},"end":{"line":133,"column":9}},"133":{"start":{"line":134,"column":0},"end":{"line":134,"column":6}},"134":{"start":{"line":135,"column":0},"end":{"line":135,"column":5}},"135":{"start":{"line":136,"column":0},"end":{"line":136,"column":42}},"136":{"start":{"line":137,"column":0},"end":{"line":137,"column":25}},"137":{"start":{"line":138,"column":0},"end":{"line":138,"column":53}},"138":{"start":{"line":139,"column":0},"end":{"line":139,"column":68}},"139":{"start":{"line":140,"column":0},"end":{"line":140,"column":9}},"140":{"start":{"line":141,"column":0},"end":{"line":141,"column":6}},"141":{"start":{"line":142,"column":0},"end":{"line":142,"column":5}},"142":{"start":{"line":143,"column":0},"end":{"line":143,"column":45}},"143":{"start":{"line":144,"column":0},"end":{"line":144,"column":25}},"144":{"start":{"line":145,"column":0},"end":{"line":145,"column":84}},"145":{"start":{"line":146,"column":0},"end":{"line":146,"column":106}},"146":{"start":{"line":147,"column":0},"end":{"line":147,"column":33}},"147":{"start":{"line":148,"column":0},"end":{"line":148,"column":9}},"148":{"start":{"line":149,"column":0},"end":{"line":149,"column":6}},"149":{"start":{"line":150,"column":0},"end":{"line":150,"column":5}},"150":{"start":{"line":151,"column":0},"end":{"line":151,"column":30}},"151":{"start":{"line":152,"column":0},"end":{"line":152,"column":25}},"152":{"start":{"line":153,"column":0},"end":{"line":153,"column":87}},"153":{"start":{"line":154,"column":0},"end":{"line":154,"column":36}},"154":{"start":{"line":155,"column":0},"end":{"line":155,"column":9}},"155":{"start":{"line":156,"column":0},"end":{"line":156,"column":6}},"156":{"start":{"line":157,"column":0},"end":{"line":157,"column":5}},"157":{"start":{"line":158,"column":0},"end":{"line":158,"column":54}},"158":{"start":{"line":159,"column":0},"end":{"line":159,"column":25}},"159":{"start":{"line":160,"column":0},"end":{"line":160,"column":61}},"160":{"start":{"line":161,"column":0},"end":{"line":161,"column":40}},"161":{"start":{"line":162,"column":0},"end":{"line":162,"column":9}},"162":{"start":{"line":163,"column":0},"end":{"line":163,"column":6}},"163":{"start":{"line":164,"column":0},"end":{"line":164,"column":5}},"164":{"start":{"line":165,"column":0},"end":{"line":165,"column":42}},"165":{"start":{"line":166,"column":0},"end":{"line":166,"column":120}},"166":{"start":{"line":167,"column":0},"end":{"line":167,"column":6}},"167":{"start":{"line":168,"column":0},"end":{"line":168,"column":5}},"168":{"start":{"line":169,"column":0},"end":{"line":169,"column":49}},"169":{"start":{"line":170,"column":0},"end":{"line":170,"column":25}},"170":{"start":{"line":171,"column":0},"end":{"line":171,"column":45}},"171":{"start":{"line":172,"column":0},"end":{"line":172,"column":32}},"172":{"start":{"line":173,"column":0},"end":{"line":173,"column":40}},"173":{"start":{"line":174,"column":0},"end":{"line":174,"column":34}},"174":{"start":{"line":175,"column":0},"end":{"line":175,"column":25}},"175":{"start":{"line":176,"column":0},"end":{"line":176,"column":14}},"176":{"start":{"line":177,"column":0},"end":{"line":177,"column":9}},"177":{"start":{"line":178,"column":0},"end":{"line":178,"column":5}},"178":{"start":{"line":179,"column":0},"end":{"line":179,"column":1}},"179":{"start":{"line":180,"column":0},"end":{"line":180,"column":0}},"180":{"start":{"line":181,"column":0},"end":{"line":181,"column":0}},"181":{"start":{"line":182,"column":0},"end":{"line":182,"column":25}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"27":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":6,"34":6,"35":6,"36":1,"37":1,"38":1,"39":1,"40":1,"41":1,"42":1,"43":1,"44":1,"45":1,"46":1,"47":1,"48":1,"49":1,"50":6,"51":6,"52":1,"53":1,"54":1,"55":1,"56":1,"57":1,"58":1,"59":1,"60":1,"61":1,"62":1,"63":1,"64":1,"65":1,"66":1,"67":1,"68":1,"69":1,"70":1,"71":1,"72":1,"73":1,"74":1,"75":1,"76":1,"77":1,"78":1,"79":1,"80":1,"81":1,"82":1,"83":1,"84":1,"85":1,"86":1,"87":1,"88":1,"89":1,"90":1,"91":1,"92":1,"93":1,"94":1,"95":1,"96":1,"97":1,"98":1,"99":1,"100":1,"101":1,"102":1,"103":1,"104":1,"105":1,"106":1,"107":1,"108":1,"109":1,"110":1,"111":1,"112":1,"113":1,"114":1,"115":1,"116":1,"117":1,"118":1,"119":1,"120":1,"121":1,"122":0,"123":0,"124":0,"125":1,"126":1,"127":1,"128":1,"129":0,"130":0,"131":0,"132":0,"133":1,"134":1,"135":1,"136":1,"137":0,"138":0,"139":0,"140":1,"141":1,"142":1,"143":1,"144":0,"145":0,"146":0,"147":0,"148":1,"149":1,"150":1,"151":1,"152":0,"153":0,"154":0,"155":1,"156":1,"157":1,"158":1,"159":0,"160":0,"161":0,"162":1,"163":1,"164":1,"165":1,"166":1,"167":1,"168":1,"169":1,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":1,"178":1,"179":1,"180":1,"181":1},"branchMap":{"0":{"type":"branch","line":22,"loc":{"start":{"line":22,"column":21},"end":{"line":60,"column":1}},"locations":[{"start":{"line":22,"column":21},"end":{"line":60,"column":1}}]},"1":{"type":"branch","line":28,"loc":{"start":{"line":28,"column":17},"end":{"line":28,"column":43}},"locations":[{"start":{"line":28,"column":17},"end":{"line":28,"column":43}}]},"2":{"type":"branch","line":33,"loc":{"start":{"line":33,"column":13},"end":{"line":37,"column":9}},"locations":[{"start":{"line":33,"column":13},"end":{"line":37,"column":9}}]},"3":{"type":"branch","line":35,"loc":{"start":{"line":35,"column":30},"end":{"line":35,"column":53}},"locations":[{"start":{"line":35,"column":30},"end":{"line":35,"column":53}}]},"4":{"type":"branch","line":35,"loc":{"start":{"line":35,"column":54},"end":{"line":35,"column":60}},"locations":[{"start":{"line":35,"column":54},"end":{"line":35,"column":60}}]},"5":{"type":"branch","line":50,"loc":{"start":{"line":50,"column":31},"end":{"line":53,"column":5}},"locations":[{"start":{"line":50,"column":31},"end":{"line":53,"column":5}}]},"6":{"type":"branch","line":62,"loc":{"start":{"line":62,"column":20},"end":{"line":64,"column":1}},"locations":[{"start":{"line":62,"column":20},"end":{"line":64,"column":1}}]},"7":{"type":"branch","line":69,"loc":{"start":{"line":69,"column":18},"end":{"line":69,"column":50}},"locations":[{"start":{"line":69,"column":18},"end":{"line":69,"column":50}}]},"8":{"type":"branch","line":73,"loc":{"start":{"line":73,"column":18},"end":{"line":76,"column":9}},"locations":[{"start":{"line":73,"column":18},"end":{"line":76,"column":9}}]},"9":{"type":"branch","line":80,"loc":{"start":{"line":80,"column":18},"end":{"line":84,"column":9}},"locations":[{"start":{"line":80,"column":18},"end":{"line":84,"column":9}}]},"10":{"type":"branch","line":88,"loc":{"start":{"line":88,"column":18},"end":{"line":92,"column":9}},"locations":[{"start":{"line":88,"column":18},"end":{"line":92,"column":9}}]},"11":{"type":"branch","line":96,"loc":{"start":{"line":96,"column":18},"end":{"line":96,"column":59}},"locations":[{"start":{"line":96,"column":18},"end":{"line":96,"column":59}}]},"12":{"type":"branch","line":100,"loc":{"start":{"line":100,"column":18},"end":{"line":104,"column":9}},"locations":[{"start":{"line":100,"column":18},"end":{"line":104,"column":9}}]},"13":{"type":"branch","line":108,"loc":{"start":{"line":108,"column":18},"end":{"line":111,"column":9}},"locations":[{"start":{"line":108,"column":18},"end":{"line":111,"column":9}}]},"14":{"type":"branch","line":115,"loc":{"start":{"line":115,"column":18},"end":{"line":115,"column":55}},"locations":[{"start":{"line":115,"column":18},"end":{"line":115,"column":55}}]}},"b":{"0":[1],"1":[0],"2":[6],"3":[5],"4":[1],"5":[6],"6":[1],"7":[1],"8":[1],"9":[1],"10":[1],"11":[1],"12":[1],"13":[1],"14":[1]},"fnMap":{"0":{"name":"start","decl":{"start":{"line":22,"column":21},"end":{"line":60,"column":1}},"loc":{"start":{"line":22,"column":21},"end":{"line":60,"column":1}},"line":22},"1":{"name":"get","decl":{"start":{"line":33,"column":13},"end":{"line":37,"column":9}},"loc":{"start":{"line":33,"column":13},"end":{"line":37,"column":9}},"line":33},"2":{"name":"stop","decl":{"start":{"line":62,"column":20},"end":{"line":64,"column":1}},"loc":{"start":{"line":62,"column":20},"end":{"line":64,"column":1}},"line":62},"3":{"name":"function","decl":{"start":{"line":69,"column":18},"end":{"line":69,"column":50}},"loc":{"start":{"line":69,"column":18},"end":{"line":69,"column":50}},"line":69},"4":{"name":"function","decl":{"start":{"line":73,"column":18},"end":{"line":76,"column":9}},"loc":{"start":{"line":73,"column":18},"end":{"line":76,"column":9}},"line":73},"5":{"name":"function","decl":{"start":{"line":80,"column":18},"end":{"line":84,"column":9}},"loc":{"start":{"line":80,"column":18},"end":{"line":84,"column":9}},"line":80},"6":{"name":"function","decl":{"start":{"line":88,"column":18},"end":{"line":92,"column":9}},"loc":{"start":{"line":88,"column":18},"end":{"line":92,"column":9}},"line":88},"7":{"name":"function","decl":{"start":{"line":96,"column":18},"end":{"line":96,"column":59}},"loc":{"start":{"line":96,"column":18},"end":{"line":96,"column":59}},"line":96},"8":{"name":"function","decl":{"start":{"line":100,"column":18},"end":{"line":104,"column":9}},"loc":{"start":{"line":100,"column":18},"end":{"line":104,"column":9}},"line":100},"9":{"name":"function","decl":{"start":{"line":108,"column":18},"end":{"line":111,"column":9}},"loc":{"start":{"line":108,"column":18},"end":{"line":111,"column":9}},"line":108},"10":{"name":"function","decl":{"start":{"line":115,"column":18},"end":{"line":115,"column":55}},"loc":{"start":{"line":115,"column":18},"end":{"line":115,"column":55}},"line":115},"11":{"name":"function","decl":{"start":{"line":122,"column":18},"end":{"line":125,"column":9}},"loc":{"start":{"line":122,"column":18},"end":{"line":125,"column":9}},"line":122},"12":{"name":"function","decl":{"start":{"line":129,"column":18},"end":{"line":133,"column":9}},"loc":{"start":{"line":129,"column":18},"end":{"line":133,"column":9}},"line":129},"13":{"name":"function","decl":{"start":{"line":137,"column":18},"end":{"line":140,"column":9}},"loc":{"start":{"line":137,"column":18},"end":{"line":140,"column":9}},"line":137},"14":{"name":"function","decl":{"start":{"line":144,"column":18},"end":{"line":148,"column":9}},"loc":{"start":{"line":144,"column":18},"end":{"line":148,"column":9}},"line":144},"15":{"name":"function","decl":{"start":{"line":152,"column":18},"end":{"line":155,"column":9}},"loc":{"start":{"line":152,"column":18},"end":{"line":155,"column":9}},"line":152},"16":{"name":"function","decl":{"start":{"line":159,"column":18},"end":{"line":162,"column":9}},"loc":{"start":{"line":159,"column":18},"end":{"line":162,"column":9}},"line":159},"17":{"name":"function","decl":{"start":{"line":166,"column":18},"end":{"line":166,"column":57}},"loc":{"start":{"line":166,"column":18},"end":{"line":166,"column":57}},"line":166},"18":{"name":"function","decl":{"start":{"line":170,"column":18},"end":{"line":177,"column":9}},"loc":{"start":{"line":170,"column":18},"end":{"line":177,"column":9}},"line":170}},"f":{"0":1,"1":6,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/examples/graph/tree.js": {"path":"/Users/garrettflynn/Documents/Github/graphscript/examples/graph/tree.js","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":41}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":53}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":0}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":94}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":24}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":54}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":24}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":19}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":5}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":1}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":0}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":12}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":0}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":61}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":0}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":11}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":12}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":12}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":20}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":23}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":24}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":38}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":48}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":44}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":22}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":45}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":37}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":79}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":40}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":39}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":22}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":33}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":51}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":82}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":44}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":66}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":26}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":54}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":68}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":44}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":69}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":25}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":21}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":17}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":13}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":8}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":6}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":0}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":138}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":0}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":0}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":11}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":31}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":36}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":28}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":24}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":10}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":16}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":22}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":24}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":9}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":6}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":0}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":20}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":0}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":2}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":0}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":0}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":14}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":18}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":172}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":40}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":36}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":50}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":56}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":46}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":10}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":41}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":52}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":9}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":8}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":5}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":1}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":0}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":19}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"27":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":2,"34":2,"35":2,"36":1,"37":1,"38":4,"39":4,"40":4,"41":4,"42":1,"43":1,"44":1,"45":1,"46":1,"47":1,"48":1,"49":1,"50":1,"51":1,"52":1,"53":1,"54":1,"55":1,"56":1,"57":1,"58":1,"59":1,"60":1,"61":1,"62":1,"63":1,"64":1,"65":1,"66":1,"67":1,"68":1,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":1,"84":1},"branchMap":{"0":{"type":"branch","line":1,"loc":{"start":{"line":1,"column":0},"end":{"line":85,"column":19}},"locations":[{"start":{"line":1,"column":0},"end":{"line":85,"column":19}}]},"1":{"type":"branch","line":69,"loc":{"start":{"line":69,"column":13},"end":{"line":83,"column":1}},"locations":[{"start":{"line":69,"column":13},"end":{"line":83,"column":1}}]},"2":{"type":"branch","line":5,"loc":{"start":{"line":5,"column":4},"end":{"line":9,"column":5}},"locations":[{"start":{"line":5,"column":4},"end":{"line":9,"column":5}}]},"3":{"type":"branch","line":5,"loc":{"start":{"line":5,"column":17},"end":{"line":9,"column":5}},"locations":[{"start":{"line":5,"column":17},"end":{"line":9,"column":5}}]},"4":{"type":"branch","line":26,"loc":{"start":{"line":26,"column":31},"end":{"line":31,"column":21}},"locations":[{"start":{"line":26,"column":31},"end":{"line":31,"column":21}}]},"5":{"type":"branch","line":33,"loc":{"start":{"line":33,"column":34},"end":{"line":37,"column":25}},"locations":[{"start":{"line":33,"column":34},"end":{"line":37,"column":25}}]},"6":{"type":"branch","line":38,"loc":{"start":{"line":38,"column":37},"end":{"line":42,"column":25}},"locations":[{"start":{"line":38,"column":37},"end":{"line":42,"column":25}}]},"7":{"type":"branch","line":53,"loc":{"start":{"line":53,"column":19},"end":{"line":57,"column":9}},"locations":[{"start":{"line":53,"column":19},"end":{"line":57,"column":9}}]}},"b":{"0":[1],"1":[0],"2":[1],"3":[1],"4":[1],"5":[2],"6":[4],"7":[1]},"fnMap":{"0":{"name":"","decl":{"start":{"line":5,"column":4},"end":{"line":9,"column":5}},"loc":{"start":{"line":5,"column":4},"end":{"line":9,"column":5}},"line":5},"1":{"name":"__operator","decl":{"start":{"line":5,"column":17},"end":{"line":9,"column":5}},"loc":{"start":{"line":5,"column":17},"end":{"line":9,"column":5}},"line":5},"2":{"name":"__operator","decl":{"start":{"line":26,"column":31},"end":{"line":31,"column":21}},"loc":{"start":{"line":26,"column":31},"end":{"line":31,"column":21}},"line":26},"3":{"name":"nodeA.x","decl":{"start":{"line":33,"column":34},"end":{"line":37,"column":25}},"loc":{"start":{"line":33,"column":34},"end":{"line":37,"column":25}},"line":33},"4":{"name":"nodeA.jump","decl":{"start":{"line":38,"column":37},"end":{"line":42,"column":25}},"loc":{"start":{"line":38,"column":37},"end":{"line":42,"column":25}},"line":38},"5":{"name":"nodeD","decl":{"start":{"line":49,"column":10},"end":{"line":49,"column":36}},"loc":{"start":{"line":49,"column":10},"end":{"line":49,"column":36}},"line":49},"6":{"name":"__operator","decl":{"start":{"line":53,"column":19},"end":{"line":57,"column":9}},"loc":{"start":{"line":53,"column":19},"end":{"line":57,"column":9}},"line":53},"7":{"name":"__onconnected","decl":{"start":{"line":72,"column":22},"end":{"line":77,"column":9}},"loc":{"start":{"line":72,"column":22},"end":{"line":77,"column":9}},"line":72},"8":{"name":"__ondisconnected","decl":{"start":{"line":78,"column":25},"end":{"line":80,"column":9}},"loc":{"start":{"line":78,"column":25},"end":{"line":80,"column":9}},"line":78}},"f":{"0":1,"1":1,"2":1,"3":2,"4":4,"5":0,"6":1,"7":0,"8":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/examples/graph/nodes/nodeA.js": {"path":"/Users/garrettflynn/Documents/Github/graphscript/examples/graph/nodes/nodeA.js","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":48}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":0}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":0}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":18}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":18}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":0}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":30}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":27}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":20}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":0}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":25}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":38}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":17}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":1}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":0}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":32}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":29}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":30}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":1}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":0}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":28}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":69}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":34}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":66}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":24}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":46}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":6}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":36}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":63}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":24}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":48}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":6}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":19}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":4,"8":4,"9":4,"10":4,"11":4,"12":4,"13":4,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"27":1,"28":2,"29":2,"30":2,"31":1,"32":1,"33":1},"branchMap":{"0":{"type":"branch","line":1,"loc":{"start":{"line":1,"column":0},"end":{"line":34,"column":1}},"locations":[{"start":{"line":1,"column":0},"end":{"line":34,"column":1}}]},"1":{"type":"branch","line":7,"loc":{"start":{"line":7,"column":20},"end":{"line":14,"column":1}},"locations":[{"start":{"line":7,"column":20},"end":{"line":14,"column":1}}]},"2":{"type":"branch","line":12,"loc":{"start":{"line":12,"column":15},"end":{"line":12,"column":38}},"locations":[{"start":{"line":12,"column":15},"end":{"line":12,"column":38}}]},"3":{"type":"branch","line":23,"loc":{"start":{"line":23,"column":18},"end":{"line":27,"column":5}},"locations":[{"start":{"line":23,"column":18},"end":{"line":27,"column":5}}]},"4":{"type":"branch","line":28,"loc":{"start":{"line":28,"column":20},"end":{"line":32,"column":5}},"locations":[{"start":{"line":28,"column":20},"end":{"line":32,"column":5}}]}},"b":{"0":[1],"1":[4],"2":[2],"3":[1],"4":[2]},"fnMap":{"0":{"name":"jump","decl":{"start":{"line":7,"column":20},"end":{"line":14,"column":1}},"loc":{"start":{"line":7,"column":20},"end":{"line":14,"column":1}},"line":7},"1":{"name":"nodeB.nodeC","decl":{"start":{"line":23,"column":18},"end":{"line":27,"column":5}},"loc":{"start":{"line":23,"column":18},"end":{"line":27,"column":5}},"line":23},"2":{"name":"nodeB.nodeC.z","decl":{"start":{"line":28,"column":20},"end":{"line":32,"column":5}},"loc":{"start":{"line":28,"column":20},"end":{"line":32,"column":5}},"line":28}},"f":{"0":4,"1":1,"2":2}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/EventHandler.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/EventHandler.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":69}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":130}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":27}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":0}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":18}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":11}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":15}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":0}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":92}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":0}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":50}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":44}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":106}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":25}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":5}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":32}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":31}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":37}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":5}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":36}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":88}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":5}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":110}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":17}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":0}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":61}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":88}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":53}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":29}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":49}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":22}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":36}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":50}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":22}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":36}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":37}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":19}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":13}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":0}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":37}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":40}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":13}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":0}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":46}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":0}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":0}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":55}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":47}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":32}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":5}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":52}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":41}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":22}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":22}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":42}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":69}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":13}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":18}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":36}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":48}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":37}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":32}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":36}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":21}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":19}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":0}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":47}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":56}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":46}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":73}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":17}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":16}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":55}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":28}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":13}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":9}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":5}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":68}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":16}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":8}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":34}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":28}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":43}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":9}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":47}},"85":{"start":{"line":86,"column":0},"end":{"line":86,"column":5}},"86":{"start":{"line":87,"column":0},"end":{"line":87,"column":29}},"87":{"start":{"line":88,"column":0},"end":{"line":88,"column":44}},"88":{"start":{"line":89,"column":0},"end":{"line":89,"column":79}},"89":{"start":{"line":90,"column":0},"end":{"line":90,"column":9}},"90":{"start":{"line":91,"column":0},"end":{"line":91,"column":5}},"91":{"start":{"line":92,"column":0},"end":{"line":92,"column":60}},"92":{"start":{"line":93,"column":0},"end":{"line":93,"column":28}},"93":{"start":{"line":94,"column":0},"end":{"line":94,"column":37}},"94":{"start":{"line":95,"column":0},"end":{"line":95,"column":143}},"95":{"start":{"line":96,"column":0},"end":{"line":96,"column":9}},"96":{"start":{"line":97,"column":0},"end":{"line":97,"column":5}},"97":{"start":{"line":98,"column":0},"end":{"line":98,"column":62}},"98":{"start":{"line":99,"column":0},"end":{"line":99,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":0,"12":0,"13":0,"14":0,"15":1,"16":2,"17":2,"18":2,"19":1,"20":11,"21":11,"22":1,"23":6,"24":6,"25":6,"26":4,"27":4,"28":4,"29":5,"30":4,"31":4,"32":0,"33":4,"34":4,"35":4,"36":4,"37":4,"38":6,"39":6,"40":6,"41":6,"42":6,"43":6,"44":6,"45":6,"46":6,"47":6,"48":6,"49":6,"50":1,"51":2,"52":2,"53":1,"54":1,"55":1,"56":1,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":1,"76":2,"77":1,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":1,"87":6,"88":6,"89":6,"90":0,"91":1,"92":0,"93":0,"94":0,"95":0,"96":0,"97":1,"98":1},"branchMap":{"0":{"type":"branch","line":9,"loc":{"start":{"line":9,"column":4},"end":{"line":9,"column":92}},"locations":[{"start":{"line":9,"column":4},"end":{"line":9,"column":92}}]},"1":{"type":"branch","line":9,"loc":{"start":{"line":9,"column":73},"end":{"line":9,"column":90}},"locations":[{"start":{"line":9,"column":73},"end":{"line":9,"column":90}}]},"2":{"type":"branch","line":16,"loc":{"start":{"line":16,"column":15},"end":{"line":19,"column":5}},"locations":[{"start":{"line":16,"column":15},"end":{"line":19,"column":5}}]},"3":{"type":"branch","line":20,"loc":{"start":{"line":20,"column":19},"end":{"line":22,"column":5}},"locations":[{"start":{"line":20,"column":19},"end":{"line":22,"column":5}}]},"4":{"type":"branch","line":21,"loc":{"start":{"line":21,"column":58},"end":{"line":21,"column":86}},"locations":[{"start":{"line":21,"column":58},"end":{"line":21,"column":86}}]},"5":{"type":"branch","line":23,"loc":{"start":{"line":23,"column":21},"end":{"line":50,"column":5}},"locations":[{"start":{"line":23,"column":21},"end":{"line":50,"column":5}}]},"6":{"type":"branch","line":26,"loc":{"start":{"line":26,"column":34},"end":{"line":26,"column":57}},"locations":[{"start":{"line":26,"column":34},"end":{"line":26,"column":57}}]},"7":{"type":"branch","line":26,"loc":{"start":{"line":26,"column":59},"end":{"line":38,"column":13}},"locations":[{"start":{"line":26,"column":59},"end":{"line":38,"column":13}}]},"8":{"type":"branch","line":49,"loc":{"start":{"line":49,"column":9},"end":{"line":49,"column":32}},"locations":[{"start":{"line":49,"column":9},"end":{"line":49,"column":32}}]},"9":{"type":"branch","line":29,"loc":{"start":{"line":29,"column":24},"end":{"line":31,"column":21}},"locations":[{"start":{"line":29,"column":24},"end":{"line":31,"column":21}}]},"10":{"type":"branch","line":51,"loc":{"start":{"line":51,"column":23},"end":{"line":77,"column":5}},"locations":[{"start":{"line":51,"column":23},"end":{"line":77,"column":5}}]},"11":{"type":"branch","line":53,"loc":{"start":{"line":53,"column":21},"end":{"line":76,"column":9}},"locations":[{"start":{"line":53,"column":21},"end":{"line":76,"column":9}}]},"12":{"type":"branch","line":58,"loc":{"start":{"line":58,"column":-1},"end":{"line":75,"column":13}},"locations":[{"start":{"line":58,"column":-1},"end":{"line":75,"column":13}}]},"13":{"type":"branch","line":87,"loc":{"start":{"line":87,"column":15},"end":{"line":91,"column":5}},"locations":[{"start":{"line":87,"column":15},"end":{"line":91,"column":5}}]},"14":{"type":"branch","line":91,"loc":{"start":{"line":91,"column":-1},"end":{"line":91,"column":5}},"locations":[{"start":{"line":91,"column":-1},"end":{"line":91,"column":5}}]}},"b":{"0":[1],"1":[0],"2":[2],"3":[11],"4":[11],"5":[6],"6":[4],"7":[4],"8":[0],"9":[5],"10":[2],"11":[1],"12":[0],"13":[6],"14":[0]},"fnMap":{"0":{"name":"EventHandler","decl":{"start":{"line":9,"column":4},"end":{"line":9,"column":92}},"loc":{"start":{"line":9,"column":4},"end":{"line":9,"column":92}},"line":9},"1":{"name":"EventHandler.setState","decl":{"start":{"line":11,"column":15},"end":{"line":15,"column":5}},"loc":{"start":{"line":11,"column":15},"end":{"line":15,"column":5}},"line":11},"2":{"name":"EventHandler.setValue","decl":{"start":{"line":16,"column":15},"end":{"line":19,"column":5}},"loc":{"start":{"line":16,"column":15},"end":{"line":19,"column":5}},"line":16},"3":{"name":"EventHandler.triggerEvent","decl":{"start":{"line":20,"column":19},"end":{"line":22,"column":5}},"loc":{"start":{"line":20,"column":19},"end":{"line":22,"column":5}},"line":20},"4":{"name":"EventHandler.subscribeEvent","decl":{"start":{"line":23,"column":21},"end":{"line":50,"column":5}},"loc":{"start":{"line":23,"column":21},"end":{"line":50,"column":5}},"line":23},"5":{"name":"get","decl":{"start":{"line":29,"column":24},"end":{"line":31,"column":21}},"loc":{"start":{"line":29,"column":24},"end":{"line":31,"column":21}},"line":29},"6":{"name":"set","decl":{"start":{"line":32,"column":24},"end":{"line":34,"column":21}},"loc":{"start":{"line":32,"column":24},"end":{"line":34,"column":21}},"line":32},"7":{"name":"EventHandler.unsubscribeEvent","decl":{"start":{"line":51,"column":23},"end":{"line":77,"column":5}},"loc":{"start":{"line":51,"column":23},"end":{"line":77,"column":5}},"line":51},"8":{"name":"EventHandler.subscribeEventOnce","decl":{"start":{"line":78,"column":25},"end":{"line":86,"column":5}},"loc":{"start":{"line":78,"column":25},"end":{"line":86,"column":5}},"line":78},"9":{"name":"EventHandler.getEvent","decl":{"start":{"line":87,"column":15},"end":{"line":91,"column":5}},"loc":{"start":{"line":87,"column":15},"end":{"line":91,"column":5}},"line":87},"10":{"name":"EventHandler.getSnapshot","decl":{"start":{"line":92,"column":18},"end":{"line":97,"column":5}},"loc":{"start":{"line":92,"column":18},"end":{"line":97,"column":5}},"line":92}},"f":{"0":1,"1":0,"2":2,"3":11,"4":6,"5":5,"6":0,"7":2,"8":0,"9":6,"10":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/Graph.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/Graph.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":97}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":122}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":0}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":39}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":46}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":37}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":69}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":70}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":37}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":51}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":67}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":0}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":48}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":0}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":70}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":0}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":35}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":241}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":227}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":118}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":258}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":92}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":95}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":71}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":20}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":67}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":24}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":6}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":20}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":1}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":0}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":0}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":22}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":19}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":27}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":16}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":14}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":35}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":14}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":8}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":0}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":54}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":0}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":28}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":49}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":14}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":29}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":26}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":37}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":39}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":10}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":24}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":148}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":20}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":1}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":0}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":17}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":24}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":0}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":12}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":19}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":22}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":27}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":24}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":42}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":64}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":35}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":14}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":38}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":35}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":38}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":40}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":70}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":70}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":104}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":84}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":5}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":0}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":41}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":30}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":16}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":17}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":13}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":0}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":20}},"85":{"start":{"line":86,"column":0},"end":{"line":86,"column":4}},"86":{"start":{"line":87,"column":0},"end":{"line":87,"column":65}},"87":{"start":{"line":88,"column":0},"end":{"line":88,"column":75}},"88":{"start":{"line":89,"column":0},"end":{"line":89,"column":0}},"89":{"start":{"line":90,"column":0},"end":{"line":90,"column":34}},"90":{"start":{"line":91,"column":0},"end":{"line":91,"column":88}},"91":{"start":{"line":92,"column":0},"end":{"line":92,"column":95}},"92":{"start":{"line":93,"column":0},"end":{"line":93,"column":0}},"93":{"start":{"line":94,"column":0},"end":{"line":94,"column":45}},"94":{"start":{"line":95,"column":0},"end":{"line":95,"column":12}},"95":{"start":{"line":96,"column":0},"end":{"line":96,"column":86}},"96":{"start":{"line":97,"column":0},"end":{"line":97,"column":77}},"97":{"start":{"line":98,"column":0},"end":{"line":98,"column":0}},"98":{"start":{"line":99,"column":0},"end":{"line":99,"column":81}},"99":{"start":{"line":100,"column":0},"end":{"line":100,"column":59}},"100":{"start":{"line":101,"column":0},"end":{"line":101,"column":0}},"101":{"start":{"line":102,"column":0},"end":{"line":102,"column":89}},"102":{"start":{"line":103,"column":0},"end":{"line":103,"column":50}},"103":{"start":{"line":104,"column":0},"end":{"line":104,"column":53}},"104":{"start":{"line":105,"column":0},"end":{"line":105,"column":60}},"105":{"start":{"line":106,"column":0},"end":{"line":106,"column":155}},"106":{"start":{"line":107,"column":0},"end":{"line":107,"column":0}},"107":{"start":{"line":108,"column":0},"end":{"line":108,"column":54}},"108":{"start":{"line":109,"column":0},"end":{"line":109,"column":0}},"109":{"start":{"line":110,"column":0},"end":{"line":110,"column":85}},"110":{"start":{"line":111,"column":0},"end":{"line":111,"column":62}},"111":{"start":{"line":112,"column":0},"end":{"line":112,"column":37}},"112":{"start":{"line":113,"column":0},"end":{"line":113,"column":0}},"113":{"start":{"line":114,"column":0},"end":{"line":114,"column":68}},"114":{"start":{"line":115,"column":0},"end":{"line":115,"column":64}},"115":{"start":{"line":116,"column":0},"end":{"line":116,"column":44}},"116":{"start":{"line":117,"column":0},"end":{"line":117,"column":81}},"117":{"start":{"line":118,"column":0},"end":{"line":118,"column":131}},"118":{"start":{"line":119,"column":0},"end":{"line":119,"column":17}},"119":{"start":{"line":120,"column":0},"end":{"line":120,"column":0}},"120":{"start":{"line":121,"column":0},"end":{"line":121,"column":60}},"121":{"start":{"line":122,"column":0},"end":{"line":122,"column":50}},"122":{"start":{"line":123,"column":0},"end":{"line":123,"column":47}},"123":{"start":{"line":124,"column":0},"end":{"line":124,"column":56}},"124":{"start":{"line":125,"column":0},"end":{"line":125,"column":97}},"125":{"start":{"line":126,"column":0},"end":{"line":126,"column":18}},"126":{"start":{"line":127,"column":0},"end":{"line":127,"column":13}},"127":{"start":{"line":128,"column":0},"end":{"line":128,"column":0}},"128":{"start":{"line":129,"column":0},"end":{"line":129,"column":77}},"129":{"start":{"line":130,"column":0},"end":{"line":130,"column":77}},"130":{"start":{"line":131,"column":0},"end":{"line":131,"column":0}},"131":{"start":{"line":132,"column":0},"end":{"line":132,"column":0}},"132":{"start":{"line":133,"column":0},"end":{"line":133,"column":75}},"133":{"start":{"line":134,"column":0},"end":{"line":134,"column":53}},"134":{"start":{"line":135,"column":0},"end":{"line":135,"column":9}},"135":{"start":{"line":136,"column":0},"end":{"line":136,"column":5}},"136":{"start":{"line":137,"column":0},"end":{"line":137,"column":1}},"137":{"start":{"line":138,"column":0},"end":{"line":138,"column":0}},"138":{"start":{"line":139,"column":0},"end":{"line":139,"column":20}},"139":{"start":{"line":140,"column":0},"end":{"line":140,"column":0}},"140":{"start":{"line":141,"column":0},"end":{"line":141,"column":21}},"141":{"start":{"line":142,"column":0},"end":{"line":142,"column":0}},"142":{"start":{"line":143,"column":0},"end":{"line":143,"column":12}},"143":{"start":{"line":144,"column":0},"end":{"line":144,"column":19}},"144":{"start":{"line":145,"column":0},"end":{"line":145,"column":22}},"145":{"start":{"line":146,"column":0},"end":{"line":146,"column":27}},"146":{"start":{"line":147,"column":0},"end":{"line":147,"column":40}},"147":{"start":{"line":148,"column":0},"end":{"line":148,"column":33}},"148":{"start":{"line":149,"column":0},"end":{"line":149,"column":27}},"149":{"start":{"line":150,"column":0},"end":{"line":150,"column":25}},"150":{"start":{"line":151,"column":0},"end":{"line":151,"column":24}},"151":{"start":{"line":152,"column":0},"end":{"line":152,"column":9}},"152":{"start":{"line":153,"column":0},"end":{"line":153,"column":65}},"153":{"start":{"line":154,"column":0},"end":{"line":154,"column":34}},"154":{"start":{"line":155,"column":0},"end":{"line":155,"column":24}},"155":{"start":{"line":156,"column":0},"end":{"line":156,"column":14}},"156":{"start":{"line":157,"column":0},"end":{"line":157,"column":20}},"157":{"start":{"line":158,"column":0},"end":{"line":158,"column":153}},"158":{"start":{"line":159,"column":0},"end":{"line":159,"column":34}},"159":{"start":{"line":160,"column":0},"end":{"line":160,"column":36}},"160":{"start":{"line":161,"column":0},"end":{"line":161,"column":5}},"161":{"start":{"line":162,"column":0},"end":{"line":162,"column":0}},"162":{"start":{"line":163,"column":0},"end":{"line":163,"column":0}},"163":{"start":{"line":164,"column":0},"end":{"line":164,"column":16}},"164":{"start":{"line":165,"column":0},"end":{"line":165,"column":29}},"165":{"start":{"line":166,"column":0},"end":{"line":166,"column":7}},"166":{"start":{"line":167,"column":0},"end":{"line":167,"column":27}},"167":{"start":{"line":168,"column":0},"end":{"line":168,"column":5}},"168":{"start":{"line":169,"column":0},"end":{"line":169,"column":0}},"169":{"start":{"line":170,"column":0},"end":{"line":170,"column":38}},"170":{"start":{"line":171,"column":0},"end":{"line":171,"column":21}},"171":{"start":{"line":172,"column":0},"end":{"line":172,"column":118}},"172":{"start":{"line":173,"column":0},"end":{"line":173,"column":73}},"173":{"start":{"line":174,"column":0},"end":{"line":174,"column":55}},"174":{"start":{"line":175,"column":0},"end":{"line":175,"column":9}},"175":{"start":{"line":176,"column":0},"end":{"line":176,"column":5}},"176":{"start":{"line":177,"column":0},"end":{"line":177,"column":0}},"177":{"start":{"line":178,"column":0},"end":{"line":178,"column":42}},"178":{"start":{"line":179,"column":0},"end":{"line":179,"column":0}},"179":{"start":{"line":180,"column":0},"end":{"line":180,"column":93}},"180":{"start":{"line":181,"column":0},"end":{"line":181,"column":0}},"181":{"start":{"line":182,"column":0},"end":{"line":182,"column":42}},"182":{"start":{"line":183,"column":0},"end":{"line":183,"column":113}},"183":{"start":{"line":184,"column":0},"end":{"line":184,"column":0}},"184":{"start":{"line":185,"column":0},"end":{"line":185,"column":43}},"185":{"start":{"line":186,"column":0},"end":{"line":186,"column":0}},"186":{"start":{"line":187,"column":0},"end":{"line":187,"column":70}},"187":{"start":{"line":188,"column":0},"end":{"line":188,"column":26}},"188":{"start":{"line":189,"column":0},"end":{"line":189,"column":106}},"189":{"start":{"line":190,"column":0},"end":{"line":190,"column":51}},"190":{"start":{"line":191,"column":0},"end":{"line":191,"column":106}},"191":{"start":{"line":192,"column":0},"end":{"line":192,"column":52}},"192":{"start":{"line":193,"column":0},"end":{"line":193,"column":38}},"193":{"start":{"line":194,"column":0},"end":{"line":194,"column":13}},"194":{"start":{"line":195,"column":0},"end":{"line":195,"column":75}},"195":{"start":{"line":196,"column":0},"end":{"line":196,"column":0}},"196":{"start":{"line":197,"column":0},"end":{"line":197,"column":32}},"197":{"start":{"line":198,"column":0},"end":{"line":198,"column":38}},"198":{"start":{"line":199,"column":0},"end":{"line":199,"column":42}},"199":{"start":{"line":200,"column":0},"end":{"line":200,"column":53}},"200":{"start":{"line":201,"column":0},"end":{"line":201,"column":13}},"201":{"start":{"line":202,"column":0},"end":{"line":202,"column":9}},"202":{"start":{"line":203,"column":0},"end":{"line":203,"column":0}},"203":{"start":{"line":204,"column":0},"end":{"line":204,"column":46}},"204":{"start":{"line":205,"column":0},"end":{"line":205,"column":0}},"205":{"start":{"line":206,"column":0},"end":{"line":206,"column":5}},"206":{"start":{"line":207,"column":0},"end":{"line":207,"column":0}},"207":{"start":{"line":208,"column":0},"end":{"line":208,"column":57}},"208":{"start":{"line":209,"column":0},"end":{"line":209,"column":50}},"209":{"start":{"line":210,"column":0},"end":{"line":210,"column":56}},"210":{"start":{"line":211,"column":0},"end":{"line":211,"column":0}},"211":{"start":{"line":212,"column":0},"end":{"line":212,"column":35}},"212":{"start":{"line":213,"column":0},"end":{"line":213,"column":5}},"213":{"start":{"line":214,"column":0},"end":{"line":214,"column":0}},"214":{"start":{"line":215,"column":0},"end":{"line":215,"column":30}},"215":{"start":{"line":216,"column":0},"end":{"line":216,"column":49}},"216":{"start":{"line":217,"column":0},"end":{"line":217,"column":53}},"217":{"start":{"line":218,"column":0},"end":{"line":218,"column":36}},"218":{"start":{"line":219,"column":0},"end":{"line":219,"column":45}},"219":{"start":{"line":220,"column":0},"end":{"line":220,"column":56}},"220":{"start":{"line":221,"column":0},"end":{"line":221,"column":74}},"221":{"start":{"line":222,"column":0},"end":{"line":222,"column":83}},"222":{"start":{"line":223,"column":0},"end":{"line":223,"column":135}},"223":{"start":{"line":224,"column":0},"end":{"line":224,"column":5}},"224":{"start":{"line":225,"column":0},"end":{"line":225,"column":0}},"225":{"start":{"line":226,"column":0},"end":{"line":226,"column":57}},"226":{"start":{"line":227,"column":0},"end":{"line":227,"column":0}},"227":{"start":{"line":228,"column":0},"end":{"line":228,"column":65}},"228":{"start":{"line":229,"column":0},"end":{"line":229,"column":0}},"229":{"start":{"line":230,"column":0},"end":{"line":230,"column":22}},"230":{"start":{"line":231,"column":0},"end":{"line":231,"column":46}},"231":{"start":{"line":232,"column":0},"end":{"line":232,"column":69}},"232":{"start":{"line":233,"column":0},"end":{"line":233,"column":207}},"233":{"start":{"line":234,"column":0},"end":{"line":234,"column":101}},"234":{"start":{"line":235,"column":0},"end":{"line":235,"column":58}},"235":{"start":{"line":236,"column":0},"end":{"line":236,"column":9}},"236":{"start":{"line":237,"column":0},"end":{"line":237,"column":92}},"237":{"start":{"line":238,"column":0},"end":{"line":238,"column":8}},"238":{"start":{"line":239,"column":0},"end":{"line":239,"column":24}},"239":{"start":{"line":240,"column":0},"end":{"line":240,"column":105}},"240":{"start":{"line":241,"column":0},"end":{"line":241,"column":9}},"241":{"start":{"line":242,"column":0},"end":{"line":242,"column":54}},"242":{"start":{"line":243,"column":0},"end":{"line":243,"column":48}},"243":{"start":{"line":244,"column":0},"end":{"line":244,"column":0}},"244":{"start":{"line":245,"column":0},"end":{"line":245,"column":110}},"245":{"start":{"line":246,"column":0},"end":{"line":246,"column":21}},"246":{"start":{"line":247,"column":0},"end":{"line":247,"column":44}},"247":{"start":{"line":248,"column":0},"end":{"line":248,"column":77}},"248":{"start":{"line":249,"column":0},"end":{"line":249,"column":43}},"249":{"start":{"line":250,"column":0},"end":{"line":250,"column":34}},"250":{"start":{"line":251,"column":0},"end":{"line":251,"column":124}},"251":{"start":{"line":252,"column":0},"end":{"line":252,"column":71}},"252":{"start":{"line":253,"column":0},"end":{"line":253,"column":4}},"253":{"start":{"line":254,"column":0},"end":{"line":254,"column":93}},"254":{"start":{"line":255,"column":0},"end":{"line":255,"column":0}},"255":{"start":{"line":256,"column":0},"end":{"line":256,"column":24}},"256":{"start":{"line":257,"column":0},"end":{"line":257,"column":0}},"257":{"start":{"line":258,"column":0},"end":{"line":258,"column":9}},"258":{"start":{"line":259,"column":0},"end":{"line":259,"column":0}},"259":{"start":{"line":260,"column":0},"end":{"line":260,"column":15}},"260":{"start":{"line":261,"column":0},"end":{"line":261,"column":5}},"261":{"start":{"line":262,"column":0},"end":{"line":262,"column":0}},"262":{"start":{"line":263,"column":0},"end":{"line":263,"column":70}},"263":{"start":{"line":264,"column":0},"end":{"line":264,"column":31}},"264":{"start":{"line":265,"column":0},"end":{"line":265,"column":0}},"265":{"start":{"line":266,"column":0},"end":{"line":266,"column":59}},"266":{"start":{"line":267,"column":0},"end":{"line":267,"column":0}},"267":{"start":{"line":268,"column":0},"end":{"line":268,"column":39}},"268":{"start":{"line":269,"column":0},"end":{"line":269,"column":41}},"269":{"start":{"line":270,"column":0},"end":{"line":270,"column":54}},"270":{"start":{"line":271,"column":0},"end":{"line":271,"column":0}},"271":{"start":{"line":272,"column":0},"end":{"line":272,"column":32}},"272":{"start":{"line":273,"column":0},"end":{"line":273,"column":42}},"273":{"start":{"line":274,"column":0},"end":{"line":274,"column":13}},"274":{"start":{"line":275,"column":0},"end":{"line":275,"column":0}},"275":{"start":{"line":276,"column":0},"end":{"line":276,"column":43}},"276":{"start":{"line":277,"column":0},"end":{"line":277,"column":1}},"277":{"start":{"line":278,"column":0},"end":{"line":278,"column":44}},"278":{"start":{"line":279,"column":0},"end":{"line":279,"column":37}},"279":{"start":{"line":280,"column":0},"end":{"line":280,"column":45}},"280":{"start":{"line":281,"column":0},"end":{"line":281,"column":51}},"281":{"start":{"line":282,"column":0},"end":{"line":282,"column":63}},"282":{"start":{"line":283,"column":0},"end":{"line":283,"column":37}},"283":{"start":{"line":284,"column":0},"end":{"line":284,"column":49}},"284":{"start":{"line":285,"column":0},"end":{"line":285,"column":0}},"285":{"start":{"line":286,"column":0},"end":{"line":286,"column":64}},"286":{"start":{"line":287,"column":0},"end":{"line":287,"column":106}},"287":{"start":{"line":288,"column":0},"end":{"line":288,"column":0}},"288":{"start":{"line":289,"column":0},"end":{"line":289,"column":40}},"289":{"start":{"line":290,"column":0},"end":{"line":290,"column":52}},"290":{"start":{"line":291,"column":0},"end":{"line":291,"column":21}},"291":{"start":{"line":292,"column":0},"end":{"line":292,"column":0}},"292":{"start":{"line":293,"column":0},"end":{"line":293,"column":53}},"293":{"start":{"line":294,"column":0},"end":{"line":294,"column":19}},"294":{"start":{"line":295,"column":0},"end":{"line":295,"column":43}},"295":{"start":{"line":296,"column":0},"end":{"line":296,"column":59}},"296":{"start":{"line":297,"column":0},"end":{"line":297,"column":21}},"297":{"start":{"line":298,"column":0},"end":{"line":298,"column":0}},"298":{"start":{"line":299,"column":0},"end":{"line":299,"column":53}},"299":{"start":{"line":300,"column":0},"end":{"line":300,"column":18}},"300":{"start":{"line":301,"column":0},"end":{"line":301,"column":13}},"301":{"start":{"line":302,"column":0},"end":{"line":302,"column":0}},"302":{"start":{"line":303,"column":0},"end":{"line":303,"column":33}},"303":{"start":{"line":304,"column":0},"end":{"line":304,"column":49}},"304":{"start":{"line":305,"column":0},"end":{"line":305,"column":13}},"305":{"start":{"line":306,"column":0},"end":{"line":306,"column":9}},"306":{"start":{"line":307,"column":0},"end":{"line":307,"column":0}},"307":{"start":{"line":308,"column":0},"end":{"line":308,"column":66}},"308":{"start":{"line":309,"column":0},"end":{"line":309,"column":42}},"309":{"start":{"line":310,"column":0},"end":{"line":310,"column":115}},"310":{"start":{"line":311,"column":0},"end":{"line":311,"column":9}},"311":{"start":{"line":312,"column":0},"end":{"line":312,"column":0}},"312":{"start":{"line":313,"column":0},"end":{"line":313,"column":32}},"313":{"start":{"line":314,"column":0},"end":{"line":314,"column":5}},"314":{"start":{"line":315,"column":0},"end":{"line":315,"column":0}},"315":{"start":{"line":316,"column":0},"end":{"line":316,"column":53}},"316":{"start":{"line":317,"column":0},"end":{"line":317,"column":38}},"317":{"start":{"line":318,"column":0},"end":{"line":318,"column":36}},"318":{"start":{"line":319,"column":0},"end":{"line":319,"column":43}},"319":{"start":{"line":320,"column":0},"end":{"line":320,"column":71}},"320":{"start":{"line":321,"column":0},"end":{"line":321,"column":148}},"321":{"start":{"line":322,"column":0},"end":{"line":322,"column":68}},"322":{"start":{"line":323,"column":0},"end":{"line":323,"column":9}},"323":{"start":{"line":324,"column":0},"end":{"line":324,"column":45}},"324":{"start":{"line":325,"column":0},"end":{"line":325,"column":60}},"325":{"start":{"line":326,"column":0},"end":{"line":326,"column":9}},"326":{"start":{"line":327,"column":0},"end":{"line":327,"column":5}},"327":{"start":{"line":328,"column":0},"end":{"line":328,"column":0}},"328":{"start":{"line":329,"column":0},"end":{"line":329,"column":66}},"329":{"start":{"line":330,"column":0},"end":{"line":330,"column":72}},"330":{"start":{"line":331,"column":0},"end":{"line":331,"column":31}},"331":{"start":{"line":332,"column":0},"end":{"line":332,"column":45}},"332":{"start":{"line":333,"column":0},"end":{"line":333,"column":44}},"333":{"start":{"line":334,"column":0},"end":{"line":334,"column":48}},"334":{"start":{"line":335,"column":0},"end":{"line":335,"column":59}},"335":{"start":{"line":336,"column":0},"end":{"line":336,"column":75}},"336":{"start":{"line":337,"column":0},"end":{"line":337,"column":38}},"337":{"start":{"line":338,"column":0},"end":{"line":338,"column":24}},"338":{"start":{"line":339,"column":0},"end":{"line":339,"column":72}},"339":{"start":{"line":340,"column":0},"end":{"line":340,"column":101}},"340":{"start":{"line":341,"column":0},"end":{"line":341,"column":27}},"341":{"start":{"line":342,"column":0},"end":{"line":342,"column":63}},"342":{"start":{"line":343,"column":0},"end":{"line":343,"column":67}},"343":{"start":{"line":344,"column":0},"end":{"line":344,"column":157}},"344":{"start":{"line":345,"column":0},"end":{"line":345,"column":29}},"345":{"start":{"line":346,"column":0},"end":{"line":346,"column":150}},"346":{"start":{"line":347,"column":0},"end":{"line":347,"column":21}},"347":{"start":{"line":348,"column":0},"end":{"line":348,"column":24}},"348":{"start":{"line":349,"column":0},"end":{"line":349,"column":59}},"349":{"start":{"line":350,"column":0},"end":{"line":350,"column":63}},"350":{"start":{"line":351,"column":0},"end":{"line":351,"column":125}},"351":{"start":{"line":352,"column":0},"end":{"line":352,"column":25}},"352":{"start":{"line":353,"column":0},"end":{"line":353,"column":118}},"353":{"start":{"line":354,"column":0},"end":{"line":354,"column":17}},"354":{"start":{"line":355,"column":0},"end":{"line":355,"column":0}},"355":{"start":{"line":356,"column":0},"end":{"line":356,"column":50}},"356":{"start":{"line":357,"column":0},"end":{"line":357,"column":45}},"357":{"start":{"line":358,"column":0},"end":{"line":358,"column":13}},"358":{"start":{"line":359,"column":0},"end":{"line":359,"column":9}},"359":{"start":{"line":360,"column":0},"end":{"line":360,"column":5}},"360":{"start":{"line":361,"column":0},"end":{"line":361,"column":0}},"361":{"start":{"line":362,"column":0},"end":{"line":362,"column":65}},"362":{"start":{"line":363,"column":0},"end":{"line":363,"column":85}},"363":{"start":{"line":364,"column":0},"end":{"line":364,"column":70}},"364":{"start":{"line":365,"column":0},"end":{"line":365,"column":0}},"365":{"start":{"line":366,"column":0},"end":{"line":366,"column":64}},"366":{"start":{"line":367,"column":0},"end":{"line":367,"column":59}},"367":{"start":{"line":368,"column":0},"end":{"line":368,"column":0}},"368":{"start":{"line":369,"column":0},"end":{"line":369,"column":39}},"369":{"start":{"line":370,"column":0},"end":{"line":370,"column":12}},"370":{"start":{"line":371,"column":0},"end":{"line":371,"column":20}},"371":{"start":{"line":372,"column":0},"end":{"line":372,"column":87}},"372":{"start":{"line":373,"column":0},"end":{"line":373,"column":18}},"373":{"start":{"line":374,"column":0},"end":{"line":374,"column":52}},"374":{"start":{"line":375,"column":0},"end":{"line":375,"column":72}},"375":{"start":{"line":376,"column":0},"end":{"line":376,"column":41}},"376":{"start":{"line":377,"column":0},"end":{"line":377,"column":44}},"377":{"start":{"line":378,"column":0},"end":{"line":378,"column":34}},"378":{"start":{"line":379,"column":0},"end":{"line":379,"column":44}},"379":{"start":{"line":380,"column":0},"end":{"line":380,"column":39}},"380":{"start":{"line":381,"column":0},"end":{"line":381,"column":13}},"381":{"start":{"line":382,"column":0},"end":{"line":382,"column":9}},"382":{"start":{"line":383,"column":0},"end":{"line":383,"column":5}},"383":{"start":{"line":384,"column":0},"end":{"line":384,"column":0}},"384":{"start":{"line":385,"column":0},"end":{"line":385,"column":17}},"385":{"start":{"line":386,"column":0},"end":{"line":386,"column":31}},"386":{"start":{"line":387,"column":0},"end":{"line":387,"column":53}},"387":{"start":{"line":388,"column":0},"end":{"line":388,"column":31}},"388":{"start":{"line":389,"column":0},"end":{"line":389,"column":27}},"389":{"start":{"line":390,"column":0},"end":{"line":390,"column":37}},"390":{"start":{"line":391,"column":0},"end":{"line":391,"column":10}},"391":{"start":{"line":392,"column":0},"end":{"line":392,"column":0}},"392":{"start":{"line":393,"column":0},"end":{"line":393,"column":0}},"393":{"start":{"line":394,"column":0},"end":{"line":394,"column":22}},"394":{"start":{"line":395,"column":0},"end":{"line":395,"column":61}},"395":{"start":{"line":396,"column":0},"end":{"line":396,"column":0}},"396":{"start":{"line":397,"column":0},"end":{"line":397,"column":16}},"397":{"start":{"line":398,"column":0},"end":{"line":398,"column":0}},"398":{"start":{"line":399,"column":0},"end":{"line":399,"column":42}},"399":{"start":{"line":400,"column":0},"end":{"line":400,"column":68}},"400":{"start":{"line":401,"column":0},"end":{"line":401,"column":24}},"401":{"start":{"line":402,"column":0},"end":{"line":402,"column":72}},"402":{"start":{"line":403,"column":0},"end":{"line":403,"column":39}},"403":{"start":{"line":404,"column":0},"end":{"line":404,"column":48}},"404":{"start":{"line":405,"column":0},"end":{"line":405,"column":62}},"405":{"start":{"line":406,"column":0},"end":{"line":406,"column":17}},"406":{"start":{"line":407,"column":0},"end":{"line":407,"column":61}},"407":{"start":{"line":408,"column":0},"end":{"line":408,"column":10}},"408":{"start":{"line":409,"column":0},"end":{"line":409,"column":0}},"409":{"start":{"line":410,"column":0},"end":{"line":410,"column":37}},"410":{"start":{"line":411,"column":0},"end":{"line":411,"column":84}},"411":{"start":{"line":412,"column":0},"end":{"line":412,"column":11}},"412":{"start":{"line":413,"column":0},"end":{"line":413,"column":34}},"413":{"start":{"line":414,"column":0},"end":{"line":414,"column":81}},"414":{"start":{"line":415,"column":0},"end":{"line":415,"column":13}},"415":{"start":{"line":416,"column":0},"end":{"line":416,"column":0}},"416":{"start":{"line":417,"column":0},"end":{"line":417,"column":34}},"417":{"start":{"line":418,"column":0},"end":{"line":418,"column":45}},"418":{"start":{"line":419,"column":0},"end":{"line":419,"column":46}},"419":{"start":{"line":420,"column":0},"end":{"line":420,"column":32}},"420":{"start":{"line":421,"column":0},"end":{"line":421,"column":74}},"421":{"start":{"line":422,"column":0},"end":{"line":422,"column":148}},"422":{"start":{"line":423,"column":0},"end":{"line":423,"column":42}},"423":{"start":{"line":424,"column":0},"end":{"line":424,"column":72}},"424":{"start":{"line":425,"column":0},"end":{"line":425,"column":58}},"425":{"start":{"line":426,"column":0},"end":{"line":426,"column":21}},"426":{"start":{"line":427,"column":0},"end":{"line":427,"column":0}},"427":{"start":{"line":428,"column":0},"end":{"line":428,"column":48}},"428":{"start":{"line":429,"column":0},"end":{"line":429,"column":53}},"429":{"start":{"line":430,"column":0},"end":{"line":430,"column":17}},"430":{"start":{"line":431,"column":0},"end":{"line":431,"column":90}},"431":{"start":{"line":432,"column":0},"end":{"line":432,"column":120}},"432":{"start":{"line":433,"column":0},"end":{"line":433,"column":20}},"433":{"start":{"line":434,"column":0},"end":{"line":434,"column":95}},"434":{"start":{"line":435,"column":0},"end":{"line":435,"column":17}},"435":{"start":{"line":436,"column":0},"end":{"line":436,"column":20}},"436":{"start":{"line":437,"column":0},"end":{"line":437,"column":104}},"437":{"start":{"line":438,"column":0},"end":{"line":438,"column":106}},"438":{"start":{"line":439,"column":0},"end":{"line":439,"column":13}},"439":{"start":{"line":440,"column":0},"end":{"line":440,"column":9}},"440":{"start":{"line":441,"column":0},"end":{"line":441,"column":19}},"441":{"start":{"line":442,"column":0},"end":{"line":442,"column":5}},"442":{"start":{"line":443,"column":0},"end":{"line":443,"column":0}},"443":{"start":{"line":444,"column":0},"end":{"line":444,"column":92}},"444":{"start":{"line":445,"column":0},"end":{"line":445,"column":39}},"445":{"start":{"line":446,"column":0},"end":{"line":446,"column":71}},"446":{"start":{"line":447,"column":0},"end":{"line":447,"column":9}},"447":{"start":{"line":448,"column":0},"end":{"line":448,"column":83}},"448":{"start":{"line":449,"column":0},"end":{"line":449,"column":5}},"449":{"start":{"line":450,"column":0},"end":{"line":450,"column":0}},"450":{"start":{"line":451,"column":0},"end":{"line":451,"column":47}},"451":{"start":{"line":452,"column":0},"end":{"line":452,"column":43}},"452":{"start":{"line":453,"column":0},"end":{"line":453,"column":5}},"453":{"start":{"line":454,"column":0},"end":{"line":454,"column":0}},"454":{"start":{"line":455,"column":0},"end":{"line":455,"column":1}},"455":{"start":{"line":456,"column":0},"end":{"line":456,"column":0}},"456":{"start":{"line":457,"column":0},"end":{"line":457,"column":0}},"457":{"start":{"line":458,"column":0},"end":{"line":458,"column":41}},"458":{"start":{"line":459,"column":0},"end":{"line":459,"column":27}},"459":{"start":{"line":460,"column":0},"end":{"line":460,"column":81}},"460":{"start":{"line":461,"column":0},"end":{"line":461,"column":131}},"461":{"start":{"line":462,"column":0},"end":{"line":462,"column":63}},"462":{"start":{"line":463,"column":0},"end":{"line":463,"column":38}},"463":{"start":{"line":464,"column":0},"end":{"line":464,"column":5}},"464":{"start":{"line":465,"column":0},"end":{"line":465,"column":0}},"465":{"start":{"line":466,"column":0},"end":{"line":466,"column":18}},"466":{"start":{"line":467,"column":0},"end":{"line":467,"column":1}},"467":{"start":{"line":468,"column":0},"end":{"line":468,"column":0}},"468":{"start":{"line":469,"column":0},"end":{"line":469,"column":0}},"469":{"start":{"line":470,"column":0},"end":{"line":470,"column":166}},"470":{"start":{"line":471,"column":0},"end":{"line":471,"column":36}},"471":{"start":{"line":472,"column":0},"end":{"line":472,"column":10}},"472":{"start":{"line":473,"column":0},"end":{"line":473,"column":55}},"473":{"start":{"line":474,"column":0},"end":{"line":474,"column":40}},"474":{"start":{"line":475,"column":0},"end":{"line":475,"column":49}},"475":{"start":{"line":476,"column":0},"end":{"line":476,"column":38}},"476":{"start":{"line":477,"column":0},"end":{"line":477,"column":13}},"477":{"start":{"line":478,"column":0},"end":{"line":478,"column":49}},"478":{"start":{"line":479,"column":0},"end":{"line":479,"column":23}},"479":{"start":{"line":480,"column":0},"end":{"line":480,"column":4}},"480":{"start":{"line":481,"column":0},"end":{"line":481,"column":0}},"481":{"start":{"line":482,"column":0},"end":{"line":482,"column":0}},"482":{"start":{"line":483,"column":0},"end":{"line":483,"column":24}},"483":{"start":{"line":484,"column":0},"end":{"line":484,"column":55}},"484":{"start":{"line":485,"column":0},"end":{"line":485,"column":0}},"485":{"start":{"line":486,"column":0},"end":{"line":486,"column":46}},"486":{"start":{"line":487,"column":0},"end":{"line":487,"column":0}},"487":{"start":{"line":488,"column":0},"end":{"line":488,"column":29}},"488":{"start":{"line":489,"column":0},"end":{"line":489,"column":14}},"489":{"start":{"line":490,"column":0},"end":{"line":490,"column":12}},"490":{"start":{"line":491,"column":0},"end":{"line":491,"column":0}},"491":{"start":{"line":492,"column":0},"end":{"line":492,"column":47}},"492":{"start":{"line":493,"column":0},"end":{"line":493,"column":63}},"493":{"start":{"line":494,"column":0},"end":{"line":494,"column":47}},"494":{"start":{"line":495,"column":0},"end":{"line":495,"column":123}},"495":{"start":{"line":496,"column":0},"end":{"line":496,"column":13}},"496":{"start":{"line":497,"column":0},"end":{"line":497,"column":0}},"497":{"start":{"line":498,"column":0},"end":{"line":498,"column":73}},"498":{"start":{"line":499,"column":0},"end":{"line":499,"column":83}},"499":{"start":{"line":500,"column":0},"end":{"line":500,"column":114}},"500":{"start":{"line":501,"column":0},"end":{"line":501,"column":101}},"501":{"start":{"line":502,"column":0},"end":{"line":502,"column":70}},"502":{"start":{"line":503,"column":0},"end":{"line":503,"column":15}},"503":{"start":{"line":504,"column":0},"end":{"line":504,"column":54}},"504":{"start":{"line":505,"column":0},"end":{"line":505,"column":5}},"505":{"start":{"line":506,"column":0},"end":{"line":506,"column":0}},"506":{"start":{"line":507,"column":0},"end":{"line":507,"column":17}},"507":{"start":{"line":508,"column":0},"end":{"line":508,"column":1}},"508":{"start":{"line":509,"column":0},"end":{"line":509,"column":0}},"509":{"start":{"line":510,"column":0},"end":{"line":510,"column":37}},"510":{"start":{"line":511,"column":0},"end":{"line":511,"column":50}},"511":{"start":{"line":512,"column":0},"end":{"line":512,"column":22}},"512":{"start":{"line":513,"column":0},"end":{"line":513,"column":53}},"513":{"start":{"line":514,"column":0},"end":{"line":514,"column":20}},"514":{"start":{"line":515,"column":0},"end":{"line":515,"column":159}},"515":{"start":{"line":516,"column":0},"end":{"line":516,"column":1}},"516":{"start":{"line":517,"column":0},"end":{"line":517,"column":0}},"517":{"start":{"line":518,"column":0},"end":{"line":518,"column":23}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"27":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1,"41":1,"42":1,"43":1,"44":1,"45":1,"46":1,"47":1,"48":1,"49":1,"50":1,"51":1,"52":1,"53":1,"54":1,"55":1,"56":1,"57":1,"58":1,"59":1,"60":1,"61":1,"62":1,"63":1,"64":1,"65":1,"66":1,"67":1,"68":1,"69":1,"70":1,"71":1,"72":1,"73":1,"74":1,"75":1,"76":1,"77":1,"78":1,"79":1,"80":1,"81":1,"82":1,"83":1,"84":1,"85":1,"86":1,"87":1,"88":6,"89":6,"90":6,"91":6,"92":6,"93":6,"94":6,"95":6,"96":6,"97":6,"98":6,"99":6,"100":6,"101":6,"102":6,"103":6,"104":6,"105":6,"106":6,"107":6,"108":6,"109":6,"110":6,"111":6,"112":39,"113":39,"114":39,"115":39,"116":31,"117":31,"118":31,"119":39,"120":39,"121":39,"122":39,"123":39,"124":39,"125":39,"126":39,"127":6,"128":6,"129":6,"130":6,"131":6,"132":6,"133":6,"134":6,"135":6,"136":1,"137":1,"138":1,"139":1,"140":1,"141":1,"142":1,"143":1,"144":1,"145":1,"146":1,"147":1,"148":1,"149":1,"150":1,"151":1,"152":1,"153":1,"154":1,"155":1,"156":1,"157":1,"158":1,"159":1,"160":1,"161":1,"162":1,"163":1,"164":1,"165":1,"166":1,"167":1,"168":1,"169":1,"170":1,"171":1,"172":1,"173":1,"174":1,"175":1,"176":1,"177":1,"178":1,"179":1,"180":1,"181":1,"182":1,"183":1,"184":1,"185":1,"186":1,"187":1,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":1,"195":1,"196":1,"197":5,"198":5,"199":5,"200":5,"201":5,"202":1,"203":1,"204":1,"205":1,"206":1,"207":1,"208":0,"209":0,"210":0,"211":0,"212":0,"213":1,"214":1,"215":6,"216":48,"217":48,"218":48,"219":0,"220":0,"221":0,"222":6,"223":6,"224":1,"225":1,"226":0,"227":0,"228":0,"229":0,"230":0,"231":0,"232":0,"233":0,"234":0,"235":0,"236":0,"237":0,"238":0,"239":0,"240":0,"241":0,"242":0,"243":0,"244":0,"245":0,"246":0,"247":0,"248":0,"249":0,"250":0,"251":0,"252":0,"253":0,"254":0,"255":0,"256":0,"257":0,"258":0,"259":0,"260":0,"261":1,"262":1,"263":1,"264":1,"265":1,"266":1,"267":1,"268":1,"269":1,"270":1,"271":1,"272":1,"273":1,"274":1,"275":1,"276":1,"277":1,"278":0,"279":0,"280":0,"281":0,"282":0,"283":0,"284":0,"285":0,"286":0,"287":0,"288":0,"289":0,"290":0,"291":0,"292":0,"293":0,"294":0,"295":0,"296":0,"297":0,"298":0,"299":0,"300":0,"301":1,"302":1,"303":0,"304":0,"305":1,"306":1,"307":1,"308":1,"309":1,"310":1,"311":1,"312":1,"313":1,"314":1,"315":1,"316":3,"317":3,"318":3,"319":1,"320":1,"321":3,"322":3,"323":3,"324":0,"325":0,"326":3,"327":1,"328":1,"329":1,"330":1,"331":1,"332":1,"333":1,"334":0,"335":0,"336":0,"337":0,"338":0,"339":0,"340":0,"341":0,"342":0,"343":0,"344":0,"345":0,"346":0,"347":0,"348":0,"349":0,"350":0,"351":0,"352":0,"353":0,"354":0,"355":0,"356":0,"357":0,"358":1,"359":1,"360":1,"361":1,"362":1,"363":1,"364":1,"365":1,"366":0,"367":0,"368":0,"369":0,"370":0,"371":0,"372":0,"373":0,"374":0,"375":0,"376":0,"377":0,"378":0,"379":0,"380":0,"381":0,"382":0,"383":1,"384":1,"385":6,"386":6,"387":6,"388":6,"389":6,"390":6,"391":6,"392":6,"393":6,"394":6,"395":6,"396":6,"397":6,"398":6,"399":2,"400":2,"401":2,"402":2,"403":2,"404":2,"405":2,"406":2,"407":2,"408":6,"409":6,"410":6,"411":6,"412":6,"413":1,"414":1,"415":6,"416":6,"417":6,"418":6,"419":0,"420":0,"421":0,"422":0,"423":0,"424":0,"425":0,"426":0,"427":0,"428":0,"429":0,"430":0,"431":0,"432":0,"433":0,"434":0,"435":0,"436":0,"437":0,"438":0,"439":0,"440":6,"441":6,"442":1,"443":1,"444":1,"445":0,"446":0,"447":1,"448":1,"449":1,"450":1,"451":0,"452":0,"453":1,"454":1,"455":1,"456":1,"457":13,"458":13,"459":42,"460":12,"461":12,"462":42,"463":42,"464":13,"465":13,"466":13,"467":1,"468":1,"469":1,"470":1,"471":1,"472":1,"473":1,"474":1,"475":1,"476":1,"477":1,"478":1,"479":1,"480":1,"481":1,"482":1,"483":1,"484":1,"485":1,"486":0,"487":0,"488":0,"489":0,"490":0,"491":0,"492":0,"493":0,"494":0,"495":0,"496":0,"497":0,"498":0,"499":0,"500":0,"501":0,"502":0,"503":0,"504":0,"505":0,"506":0,"507":0,"508":1,"509":1,"510":0,"511":0,"512":0,"513":0,"514":0,"515":0,"516":1,"517":1},"branchMap":{"0":{"type":"branch","line":88,"loc":{"start":{"line":88,"column":4},"end":{"line":136,"column":5}},"locations":[{"start":{"line":88,"column":4},"end":{"line":136,"column":5}}]},"1":{"type":"branch","line":91,"loc":{"start":{"line":91,"column":46},"end":{"line":91,"column":88}},"locations":[{"start":{"line":91,"column":46},"end":{"line":91,"column":88}}]},"2":{"type":"branch","line":92,"loc":{"start":{"line":92,"column":49},"end":{"line":92,"column":95}},"locations":[{"start":{"line":92,"column":49},"end":{"line":92,"column":95}}]},"3":{"type":"branch","line":106,"loc":{"start":{"line":106,"column":36},"end":{"line":106,"column":87}},"locations":[{"start":{"line":106,"column":36},"end":{"line":106,"column":87}}]},"4":{"type":"branch","line":112,"loc":{"start":{"line":112,"column":36},"end":{"line":127,"column":13}},"locations":[{"start":{"line":112,"column":36},"end":{"line":127,"column":13}}]},"5":{"type":"branch","line":116,"loc":{"start":{"line":116,"column":43},"end":{"line":119,"column":17}},"locations":[{"start":{"line":116,"column":43},"end":{"line":119,"column":17}}]},"6":{"type":"branch","line":118,"loc":{"start":{"line":118,"column":51},"end":{"line":118,"column":131}},"locations":[{"start":{"line":118,"column":51},"end":{"line":118,"column":131}}]},"7":{"type":"branch","line":125,"loc":{"start":{"line":125,"column":51},"end":{"line":125,"column":58}},"locations":[{"start":{"line":125,"column":51},"end":{"line":125,"column":58}}]},"8":{"type":"branch","line":125,"loc":{"start":{"line":125,"column":59},"end":{"line":125,"column":65}},"locations":[{"start":{"line":125,"column":59},"end":{"line":125,"column":65}}]},"9":{"type":"branch","line":130,"loc":{"start":{"line":130,"column":45},"end":{"line":130,"column":77}},"locations":[{"start":{"line":130,"column":45},"end":{"line":130,"column":77}}]},"10":{"type":"branch","line":123,"loc":{"start":{"line":123,"column":25},"end":{"line":123,"column":46}},"locations":[{"start":{"line":123,"column":25},"end":{"line":123,"column":46}}]},"11":{"type":"branch","line":124,"loc":{"start":{"line":124,"column":25},"end":{"line":124,"column":55}},"locations":[{"start":{"line":124,"column":25},"end":{"line":124,"column":55}}]},"12":{"type":"branch","line":164,"loc":{"start":{"line":164,"column":4},"end":{"line":168,"column":5}},"locations":[{"start":{"line":164,"column":4},"end":{"line":168,"column":5}}]},"13":{"type":"branch","line":170,"loc":{"start":{"line":170,"column":11},"end":{"line":176,"column":5}},"locations":[{"start":{"line":170,"column":11},"end":{"line":176,"column":5}}]},"14":{"type":"branch","line":178,"loc":{"start":{"line":178,"column":11},"end":{"line":206,"column":5}},"locations":[{"start":{"line":178,"column":11},"end":{"line":206,"column":5}}]},"15":{"type":"branch","line":180,"loc":{"start":{"line":180,"column":80},"end":{"line":180,"column":84}},"locations":[{"start":{"line":180,"column":80},"end":{"line":180,"column":84}}]},"16":{"type":"branch","line":183,"loc":{"start":{"line":183,"column":23},"end":{"line":183,"column":41}},"locations":[{"start":{"line":183,"column":23},"end":{"line":183,"column":41}}]},"17":{"type":"branch","line":188,"loc":{"start":{"line":188,"column":25},"end":{"line":195,"column":15}},"locations":[{"start":{"line":188,"column":25},"end":{"line":195,"column":15}}]},"18":{"type":"branch","line":195,"loc":{"start":{"line":195,"column":38},"end":{"line":195,"column":75}},"locations":[{"start":{"line":195,"column":38},"end":{"line":195,"column":75}}]},"19":{"type":"branch","line":197,"loc":{"start":{"line":197,"column":31},"end":{"line":202,"column":9}},"locations":[{"start":{"line":197,"column":31},"end":{"line":202,"column":9}}]},"20":{"type":"branch","line":215,"loc":{"start":{"line":215,"column":17},"end":{"line":224,"column":5}},"locations":[{"start":{"line":215,"column":17},"end":{"line":224,"column":5}}]},"21":{"type":"branch","line":216,"loc":{"start":{"line":216,"column":47},"end":{"line":223,"column":80}},"locations":[{"start":{"line":216,"column":47},"end":{"line":223,"column":80}}]},"22":{"type":"branch","line":219,"loc":{"start":{"line":219,"column":43},"end":{"line":223,"column":19}},"locations":[{"start":{"line":219,"column":43},"end":{"line":223,"column":19}}]},"23":{"type":"branch","line":263,"loc":{"start":{"line":263,"column":13},"end":{"line":314,"column":5}},"locations":[{"start":{"line":263,"column":13},"end":{"line":314,"column":5}}]},"24":{"type":"branch","line":303,"loc":{"start":{"line":303,"column":32},"end":{"line":305,"column":13}},"locations":[{"start":{"line":303,"column":32},"end":{"line":305,"column":13}}]},"25":{"type":"branch","line":316,"loc":{"start":{"line":316,"column":10},"end":{"line":327,"column":5}},"locations":[{"start":{"line":316,"column":10},"end":{"line":327,"column":5}}]},"26":{"type":"branch","line":319,"loc":{"start":{"line":319,"column":18},"end":{"line":319,"column":40}},"locations":[{"start":{"line":319,"column":18},"end":{"line":319,"column":40}}]},"27":{"type":"branch","line":319,"loc":{"start":{"line":319,"column":42},"end":{"line":322,"column":19}},"locations":[{"start":{"line":319,"column":42},"end":{"line":322,"column":19}}]},"28":{"type":"branch","line":322,"loc":{"start":{"line":322,"column":13},"end":{"line":322,"column":68}},"locations":[{"start":{"line":322,"column":13},"end":{"line":322,"column":68}}]},"29":{"type":"branch","line":324,"loc":{"start":{"line":324,"column":-1},"end":{"line":324,"column":42}},"locations":[{"start":{"line":324,"column":-1},"end":{"line":324,"column":42}}]},"30":{"type":"branch","line":324,"loc":{"start":{"line":324,"column":44},"end":{"line":326,"column":9}},"locations":[{"start":{"line":324,"column":44},"end":{"line":326,"column":9}}]},"31":{"type":"branch","line":329,"loc":{"start":{"line":329,"column":21},"end":{"line":360,"column":5}},"locations":[{"start":{"line":329,"column":21},"end":{"line":360,"column":5}}]},"32":{"type":"branch","line":330,"loc":{"start":{"line":330,"column":37},"end":{"line":330,"column":72}},"locations":[{"start":{"line":330,"column":37},"end":{"line":330,"column":72}}]},"33":{"type":"branch","line":334,"loc":{"start":{"line":334,"column":47},"end":{"line":358,"column":13}},"locations":[{"start":{"line":334,"column":47},"end":{"line":358,"column":13}}]},"34":{"type":"branch","line":362,"loc":{"start":{"line":362,"column":10},"end":{"line":362,"column":64}},"locations":[{"start":{"line":362,"column":10},"end":{"line":362,"column":64}}]},"35":{"type":"branch","line":363,"loc":{"start":{"line":363,"column":10},"end":{"line":363,"column":84}},"locations":[{"start":{"line":363,"column":10},"end":{"line":363,"column":84}}]},"36":{"type":"branch","line":364,"loc":{"start":{"line":364,"column":13},"end":{"line":364,"column":70}},"locations":[{"start":{"line":364,"column":13},"end":{"line":364,"column":70}}]},"37":{"type":"branch","line":385,"loc":{"start":{"line":385,"column":16},"end":{"line":442,"column":5}},"locations":[{"start":{"line":385,"column":16},"end":{"line":442,"column":5}}]},"38":{"type":"branch","line":395,"loc":{"start":{"line":395,"column":41},"end":{"line":395,"column":61}},"locations":[{"start":{"line":395,"column":41},"end":{"line":395,"column":61}}]},"39":{"type":"branch","line":399,"loc":{"start":{"line":399,"column":41},"end":{"line":408,"column":10}},"locations":[{"start":{"line":399,"column":41},"end":{"line":408,"column":10}}]},"40":{"type":"branch","line":407,"loc":{"start":{"line":407,"column":13},"end":{"line":407,"column":61}},"locations":[{"start":{"line":407,"column":13},"end":{"line":407,"column":61}}]},"41":{"type":"branch","line":419,"loc":{"start":{"line":419,"column":9},"end":{"line":440,"column":9}},"locations":[{"start":{"line":419,"column":9},"end":{"line":440,"column":9}}]},"42":{"type":"branch","line":405,"loc":{"start":{"line":405,"column":31},"end":{"line":405,"column":61}},"locations":[{"start":{"line":405,"column":31},"end":{"line":405,"column":61}}]},"43":{"type":"branch","line":413,"loc":{"start":{"line":413,"column":27},"end":{"line":415,"column":13}},"locations":[{"start":{"line":413,"column":27},"end":{"line":415,"column":13}}]},"44":{"type":"branch","line":444,"loc":{"start":{"line":444,"column":18},"end":{"line":449,"column":5}},"locations":[{"start":{"line":444,"column":18},"end":{"line":449,"column":5}}]},"45":{"type":"branch","line":445,"loc":{"start":{"line":445,"column":38},"end":{"line":447,"column":9}},"locations":[{"start":{"line":445,"column":38},"end":{"line":447,"column":9}}]},"46":{"type":"branch","line":458,"loc":{"start":{"line":458,"column":0},"end":{"line":467,"column":1}},"locations":[{"start":{"line":458,"column":0},"end":{"line":467,"column":1}}]},"47":{"type":"branch","line":459,"loc":{"start":{"line":459,"column":26},"end":{"line":464,"column":5}},"locations":[{"start":{"line":459,"column":26},"end":{"line":464,"column":5}}]},"48":{"type":"branch","line":460,"loc":{"start":{"line":460,"column":19},"end":{"line":460,"column":32}},"locations":[{"start":{"line":460,"column":19},"end":{"line":460,"column":32}}]},"49":{"type":"branch","line":460,"loc":{"start":{"line":460,"column":50},"end":{"line":460,"column":78}},"locations":[{"start":{"line":460,"column":50},"end":{"line":460,"column":78}}]},"50":{"type":"branch","line":460,"loc":{"start":{"line":460,"column":80},"end":{"line":463,"column":15}},"locations":[{"start":{"line":460,"column":80},"end":{"line":463,"column":15}}]},"51":{"type":"branch","line":461,"loc":{"start":{"line":461,"column":26},"end":{"line":461,"column":39}},"locations":[{"start":{"line":461,"column":26},"end":{"line":461,"column":39}}]},"52":{"type":"branch","line":461,"loc":{"start":{"line":461,"column":57},"end":{"line":461,"column":88}},"locations":[{"start":{"line":461,"column":57},"end":{"line":461,"column":88}}]},"53":{"type":"branch","line":461,"loc":{"start":{"line":461,"column":90},"end":{"line":461,"column":131}},"locations":[{"start":{"line":461,"column":90},"end":{"line":461,"column":131}}]},"54":{"type":"branch","line":462,"loc":{"start":{"line":462,"column":-1},"end":{"line":462,"column":62}},"locations":[{"start":{"line":462,"column":-1},"end":{"line":462,"column":62}}]},"55":{"type":"branch","line":463,"loc":{"start":{"line":463,"column":9},"end":{"line":463,"column":38}},"locations":[{"start":{"line":463,"column":9},"end":{"line":463,"column":38}}]}},"b":{"0":[6],"1":[0],"2":[0],"3":[0],"4":[39],"5":[31],"6":[5],"7":[31],"8":[8],"9":[0],"10":[138],"11":[5],"12":[1],"13":[1],"14":[1],"15":[0],"16":[0],"17":[0],"18":[0],"19":[5],"20":[6],"21":[48],"22":[0],"23":[1],"24":[0],"25":[3],"26":[1],"27":[1],"28":[2],"29":[0],"30":[0],"31":[1],"32":[0],"33":[0],"34":[47],"35":[6],"36":[1],"37":[6],"38":[0],"39":[2],"40":[0],"41":[0],"42":[2],"43":[1],"44":[1],"45":[0],"46":[13],"47":[42],"48":[38],"49":[12],"50":[12],"51":[1],"52":[1],"53":[1],"54":[11],"55":[30]},"fnMap":{"0":{"name":"GraphNode","decl":{"start":{"line":88,"column":4},"end":{"line":136,"column":5}},"loc":{"start":{"line":88,"column":4},"end":{"line":136,"column":5}},"line":88},"1":{"name":"get","decl":{"start":{"line":123,"column":25},"end":{"line":123,"column":46}},"loc":{"start":{"line":123,"column":25},"end":{"line":123,"column":46}},"line":123},"2":{"name":"set","decl":{"start":{"line":124,"column":25},"end":{"line":124,"column":55}},"loc":{"start":{"line":124,"column":25},"end":{"line":124,"column":55}},"line":124},"3":{"name":"Graph","decl":{"start":{"line":164,"column":4},"end":{"line":168,"column":5}},"loc":{"start":{"line":164,"column":4},"end":{"line":168,"column":5}},"line":164},"4":{"name":"Graph.init","decl":{"start":{"line":170,"column":11},"end":{"line":176,"column":5}},"loc":{"start":{"line":170,"column":11},"end":{"line":176,"column":5}},"line":170},"5":{"name":"Graph.load","decl":{"start":{"line":178,"column":11},"end":{"line":206,"column":5}},"loc":{"start":{"line":178,"column":11},"end":{"line":206,"column":5}},"line":178},"6":{"name":"Graph.setLoaders","decl":{"start":{"line":208,"column":17},"end":{"line":213,"column":5}},"loc":{"start":{"line":208,"column":17},"end":{"line":213,"column":5}},"line":208},"7":{"name":"Graph.runLoaders","decl":{"start":{"line":215,"column":17},"end":{"line":224,"column":5}},"loc":{"start":{"line":215,"column":17},"end":{"line":224,"column":5}},"line":215},"8":{"name":"Graph.add","decl":{"start":{"line":226,"column":10},"end":{"line":261,"column":5}},"loc":{"start":{"line":226,"column":10},"end":{"line":261,"column":5}},"line":226},"9":{"name":"Graph.remove","decl":{"start":{"line":263,"column":13},"end":{"line":314,"column":5}},"loc":{"start":{"line":263,"column":13},"end":{"line":314,"column":5}},"line":263},"10":{"name":"recursiveRemove","decl":{"start":{"line":278,"column":36},"end":{"line":301,"column":13}},"loc":{"start":{"line":278,"column":36},"end":{"line":301,"column":13}},"line":278},"11":{"name":"Graph.run","decl":{"start":{"line":316,"column":10},"end":{"line":327,"column":5}},"loc":{"start":{"line":316,"column":10},"end":{"line":327,"column":5}},"line":316},"12":{"name":"Graph.clearListeners","decl":{"start":{"line":329,"column":21},"end":{"line":360,"column":5}},"loc":{"start":{"line":329,"column":21},"end":{"line":360,"column":5}},"line":329},"13":{"name":"Graph.get","decl":{"start":{"line":362,"column":10},"end":{"line":362,"column":64}},"loc":{"start":{"line":362,"column":10},"end":{"line":362,"column":64}},"line":362},"14":{"name":"Graph.set","decl":{"start":{"line":363,"column":10},"end":{"line":363,"column":84}},"loc":{"start":{"line":363,"column":10},"end":{"line":363,"column":84}},"line":363},"15":{"name":"Graph.delete","decl":{"start":{"line":364,"column":13},"end":{"line":364,"column":70}},"loc":{"start":{"line":364,"column":13},"end":{"line":364,"column":70}},"line":364},"16":{"name":"Graph.getProps","decl":{"start":{"line":366,"column":15},"end":{"line":383,"column":5}},"loc":{"start":{"line":366,"column":15},"end":{"line":383,"column":5}},"line":366},"17":{"name":"Graph.subscribe","decl":{"start":{"line":385,"column":16},"end":{"line":442,"column":5}},"loc":{"start":{"line":385,"column":16},"end":{"line":442,"column":5}},"line":385},"18":{"name":"callback","decl":{"start":{"line":405,"column":31},"end":{"line":405,"column":61}},"loc":{"start":{"line":405,"column":31},"end":{"line":405,"column":61}},"line":405},"19":{"name":"ondelete","decl":{"start":{"line":413,"column":27},"end":{"line":415,"column":13}},"loc":{"start":{"line":413,"column":27},"end":{"line":415,"column":13}},"line":413},"20":{"name":"ondelete","decl":{"start":{"line":423,"column":35},"end":{"line":426,"column":21}},"loc":{"start":{"line":423,"column":35},"end":{"line":426,"column":21}},"line":423},"21":{"name":"Graph.unsubscribe","decl":{"start":{"line":444,"column":18},"end":{"line":449,"column":5}},"loc":{"start":{"line":444,"column":18},"end":{"line":449,"column":5}},"line":444},"22":{"name":"Graph.setState","decl":{"start":{"line":451,"column":15},"end":{"line":453,"column":5}},"loc":{"start":{"line":451,"column":15},"end":{"line":453,"column":5}},"line":451},"23":{"name":"recursivelyAssign","decl":{"start":{"line":458,"column":0},"end":{"line":467,"column":1}},"loc":{"start":{"line":458,"column":0},"end":{"line":467,"column":1}},"line":458},"24":{"name":"getAllProperties","decl":{"start":{"line":486,"column":6},"end":{"line":508,"column":1}},"loc":{"start":{"line":486,"column":6},"end":{"line":508,"column":1}},"line":486},"25":{"name":"instanceObject","decl":{"start":{"line":510,"column":6},"end":{"line":516,"column":1}},"loc":{"start":{"line":510,"column":6},"end":{"line":516,"column":1}},"line":510}},"f":{"0":6,"1":138,"2":5,"3":1,"4":1,"5":1,"6":0,"7":6,"8":0,"9":1,"10":0,"11":3,"12":1,"13":47,"14":6,"15":1,"16":0,"17":6,"18":2,"19":1,"20":0,"21":1,"22":0,"23":13,"24":0,"25":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":58}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":60}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":58}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":54}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":52}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":50}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":64}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":0}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":8}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":13}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":20}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":14}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":13}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":11}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":10}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":8}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1},"branchMap":{},"b":{},"fnMap":{},"f":{}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-children-loader/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-children-loader/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":26}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":40}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":55}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":0}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":32}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":35}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":29}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":31}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":92}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":59}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":5}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":0}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":39}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":17}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":41}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":118}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":5}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":0}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":21}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":1}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":0}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":55}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":50}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":28}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":40}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":28}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":38}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":22}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":37}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":60}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":78}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":134}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":40}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":43}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":72}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":43}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":44}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":76}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":45}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":9}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":0}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":35}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":12}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":57}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":88}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":13}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":40}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":49}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":60}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":259}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":32}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":53}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":25}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":72}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":197}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":78}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":85}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":63}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":51}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":48}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":61}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":0}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":63}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":120}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":13}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":9}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":6}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":6,"6":6,"7":6,"8":1,"9":1,"10":1,"11":6,"12":6,"13":6,"14":6,"15":6,"16":6,"17":6,"18":6,"19":6,"20":1,"21":1,"22":2,"23":2,"24":6,"25":6,"26":6,"27":6,"28":6,"29":2,"30":1,"31":1,"32":1,"33":6,"34":0,"35":0,"36":4,"37":0,"38":0,"39":0,"40":6,"41":6,"42":6,"43":6,"44":6,"45":6,"46":6,"47":6,"48":6,"49":6,"50":6,"51":6,"52":0,"53":6,"54":6,"55":0,"56":0,"57":0,"58":6,"59":6,"60":6,"61":6,"62":6,"63":6,"64":6,"65":6,"66":6,"67":2},"branchMap":{"0":{"type":"branch","line":5,"loc":{"start":{"line":5,"column":15},"end":{"line":20,"column":1}},"locations":[{"start":{"line":5,"column":15},"end":{"line":20,"column":1}}]},"1":{"type":"branch","line":8,"loc":{"start":{"line":8,"column":30},"end":{"line":11,"column":5}},"locations":[{"start":{"line":8,"column":30},"end":{"line":11,"column":5}}]},"2":{"type":"branch","line":16,"loc":{"start":{"line":16,"column":39},"end":{"line":16,"column":85}},"locations":[{"start":{"line":16,"column":39},"end":{"line":16,"column":85}}]},"3":{"type":"branch","line":22,"loc":{"start":{"line":22,"column":6},"end":{"line":68,"column":1}},"locations":[{"start":{"line":22,"column":6},"end":{"line":68,"column":1}}]},"4":{"type":"branch","line":24,"loc":{"start":{"line":24,"column":27},"end":{"line":67,"column":6}},"locations":[{"start":{"line":24,"column":27},"end":{"line":67,"column":6}}]},"5":{"type":"branch","line":25,"loc":{"start":{"line":25,"column":31},"end":{"line":25,"column":40}},"locations":[{"start":{"line":25,"column":31},"end":{"line":25,"column":40}}]},"6":{"type":"branch","line":27,"loc":{"start":{"line":27,"column":29},"end":{"line":27,"column":38}},"locations":[{"start":{"line":27,"column":29},"end":{"line":27,"column":38}}]},"7":{"type":"branch","line":29,"loc":{"start":{"line":29,"column":36},"end":{"line":34,"column":15}},"locations":[{"start":{"line":29,"column":36},"end":{"line":34,"column":15}}]},"8":{"type":"branch","line":30,"loc":{"start":{"line":30,"column":33},"end":{"line":33,"column":40}},"locations":[{"start":{"line":30,"column":33},"end":{"line":33,"column":40}}]},"9":{"type":"branch","line":32,"loc":{"start":{"line":32,"column":43},"end":{"line":32,"column":110}},"locations":[{"start":{"line":32,"column":43},"end":{"line":32,"column":110}}]},"10":{"type":"branch","line":34,"loc":{"start":{"line":34,"column":9},"end":{"line":40,"column":9}},"locations":[{"start":{"line":34,"column":9},"end":{"line":40,"column":9}}]},"11":{"type":"branch","line":34,"loc":{"start":{"line":34,"column":42},"end":{"line":37,"column":15}},"locations":[{"start":{"line":34,"column":42},"end":{"line":37,"column":15}}]},"12":{"type":"branch","line":37,"loc":{"start":{"line":37,"column":43},"end":{"line":40,"column":9}},"locations":[{"start":{"line":37,"column":43},"end":{"line":40,"column":9}}]},"13":{"type":"branch","line":47,"loc":{"start":{"line":47,"column":26},"end":{"line":47,"column":40}},"locations":[{"start":{"line":47,"column":26},"end":{"line":47,"column":40}}]},"14":{"type":"branch","line":50,"loc":{"start":{"line":50,"column":39},"end":{"line":50,"column":113}},"locations":[{"start":{"line":50,"column":39},"end":{"line":50,"column":113}}]},"15":{"type":"branch","line":50,"loc":{"start":{"line":50,"column":189},"end":{"line":50,"column":198}},"locations":[{"start":{"line":50,"column":189},"end":{"line":50,"column":198}}]},"16":{"type":"branch","line":52,"loc":{"start":{"line":52,"column":52},"end":{"line":54,"column":19}},"locations":[{"start":{"line":52,"column":52},"end":{"line":54,"column":19}}]},"17":{"type":"branch","line":55,"loc":{"start":{"line":55,"column":37},"end":{"line":55,"column":51}},"locations":[{"start":{"line":55,"column":37},"end":{"line":55,"column":51}}]},"18":{"type":"branch","line":55,"loc":{"start":{"line":55,"column":51},"end":{"line":55,"column":82}},"locations":[{"start":{"line":55,"column":51},"end":{"line":55,"column":82}}]},"19":{"type":"branch","line":55,"loc":{"start":{"line":55,"column":84},"end":{"line":59,"column":19}},"locations":[{"start":{"line":55,"column":84},"end":{"line":59,"column":19}}]}},"b":{"0":[6],"1":[1],"2":[1],"3":[2],"4":[6],"5":[0],"6":[0],"7":[2],"8":[1],"9":[0],"10":[4],"11":[0],"12":[0],"13":[5],"14":[0],"15":[0],"16":[0],"17":[0],"18":[0],"19":[0]},"fnMap":{"0":{"name":"default","decl":{"start":{"line":5,"column":15},"end":{"line":20,"column":1}},"loc":{"start":{"line":5,"column":15},"end":{"line":20,"column":1}},"line":5},"1":{"name":"recursiveSet","decl":{"start":{"line":22,"column":6},"end":{"line":68,"column":1}},"loc":{"start":{"line":22,"column":6},"end":{"line":68,"column":1}},"line":22},"2":{"name":"ondelete","decl":{"start":{"line":57,"column":31},"end":{"line":57,"column":85}},"loc":{"start":{"line":57,"column":31},"end":{"line":57,"column":85}},"line":57}},"f":{"0":6,"1":2,"2":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-default-loader/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-default-loader/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":32}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":15}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":115}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":35}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":46}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":117}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":37}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":52}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":148}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":110}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":26}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":10}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":0}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":45}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":5}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":4}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":21}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":1}}},"s":{"0":1,"1":6,"2":6,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":6,"16":6,"17":6},"branchMap":{"0":{"type":"branch","line":1,"loc":{"start":{"line":1,"column":15},"end":{"line":18,"column":1}},"locations":[{"start":{"line":1,"column":15},"end":{"line":18,"column":1}}]},"1":{"type":"branch","line":3,"loc":{"start":{"line":3,"column":48},"end":{"line":3,"column":74}},"locations":[{"start":{"line":3,"column":48},"end":{"line":3,"column":74}}]},"2":{"type":"branch","line":3,"loc":{"start":{"line":3,"column":76},"end":{"line":15,"column":5}},"locations":[{"start":{"line":3,"column":76},"end":{"line":15,"column":5}}]}},"b":{"0":[6],"1":[0],"2":[0]},"fnMap":{"0":{"name":"default","decl":{"start":{"line":1,"column":15},"end":{"line":18,"column":1}},"loc":{"start":{"line":1,"column":15},"end":{"line":18,"column":1}},"line":1},"1":{"name":"defaultFunction","decl":{"start":{"line":5,"column":32},"end":{"line":12,"column":9}},"loc":{"start":{"line":5,"column":32},"end":{"line":12,"column":9}},"line":5}},"f":{"0":6,"1":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-listeners-loader/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-listeners-loader/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":47}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":0}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":58}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":0}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":31}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":33}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":34}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":48}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":44}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":37}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":24}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":113}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":102}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":56}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":71}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":87}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":125}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":25}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":47}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":32}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":37}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":76}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":52}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":40}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":174}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":205}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":70}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":33}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":36}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":141}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":202}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":66}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":29}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":25}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":21}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":17}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":50}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":109}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":147}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":28}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":68}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":43}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":31}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":157}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":181}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":58}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":25}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":28}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":128}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":178}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":54}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":21}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":39}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":17}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":13}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":9}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":5}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":1}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":0}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":32}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":41}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":44}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":34}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":0}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":0}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":18}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":25}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":22}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":29}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":57}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":38}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":10}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":46}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":50}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":54}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":5}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":0}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":54}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":31}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":26}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":24}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":28}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":6}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":0}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":64}},"85":{"start":{"line":86,"column":0},"end":{"line":86,"column":0}},"86":{"start":{"line":87,"column":0},"end":{"line":87,"column":32}},"87":{"start":{"line":88,"column":0},"end":{"line":88,"column":24}},"88":{"start":{"line":89,"column":0},"end":{"line":89,"column":67}},"89":{"start":{"line":90,"column":0},"end":{"line":90,"column":18}},"90":{"start":{"line":91,"column":0},"end":{"line":91,"column":6}},"91":{"start":{"line":92,"column":0},"end":{"line":92,"column":21}},"92":{"start":{"line":93,"column":0},"end":{"line":93,"column":1}},"93":{"start":{"line":94,"column":0},"end":{"line":94,"column":0}},"94":{"start":{"line":95,"column":0},"end":{"line":95,"column":0}},"95":{"start":{"line":96,"column":0},"end":{"line":96,"column":0}},"96":{"start":{"line":97,"column":0},"end":{"line":97,"column":61}},"97":{"start":{"line":98,"column":0},"end":{"line":98,"column":129}},"98":{"start":{"line":99,"column":0},"end":{"line":99,"column":0}},"99":{"start":{"line":100,"column":0},"end":{"line":100,"column":137}},"100":{"start":{"line":101,"column":0},"end":{"line":101,"column":86}},"101":{"start":{"line":102,"column":0},"end":{"line":102,"column":0}},"102":{"start":{"line":103,"column":0},"end":{"line":103,"column":37}},"103":{"start":{"line":104,"column":0},"end":{"line":104,"column":60}},"104":{"start":{"line":105,"column":0},"end":{"line":105,"column":45}},"105":{"start":{"line":106,"column":0},"end":{"line":106,"column":38}},"106":{"start":{"line":107,"column":0},"end":{"line":107,"column":68}},"107":{"start":{"line":108,"column":0},"end":{"line":108,"column":44}},"108":{"start":{"line":109,"column":0},"end":{"line":109,"column":0}},"109":{"start":{"line":110,"column":0},"end":{"line":110,"column":22}},"110":{"start":{"line":111,"column":0},"end":{"line":111,"column":9}},"111":{"start":{"line":112,"column":0},"end":{"line":112,"column":0}},"112":{"start":{"line":113,"column":0},"end":{"line":113,"column":48}},"113":{"start":{"line":114,"column":0},"end":{"line":114,"column":53}},"114":{"start":{"line":115,"column":0},"end":{"line":115,"column":47}},"115":{"start":{"line":116,"column":0},"end":{"line":116,"column":94}},"116":{"start":{"line":117,"column":0},"end":{"line":117,"column":74}},"117":{"start":{"line":118,"column":0},"end":{"line":118,"column":106}},"118":{"start":{"line":119,"column":0},"end":{"line":119,"column":37}},"119":{"start":{"line":120,"column":0},"end":{"line":120,"column":13}},"120":{"start":{"line":121,"column":0},"end":{"line":121,"column":9}},"121":{"start":{"line":122,"column":0},"end":{"line":122,"column":0}},"122":{"start":{"line":123,"column":0},"end":{"line":123,"column":17}},"123":{"start":{"line":124,"column":0},"end":{"line":124,"column":70}},"124":{"start":{"line":125,"column":0},"end":{"line":125,"column":136}},"125":{"start":{"line":126,"column":0},"end":{"line":126,"column":13}},"126":{"start":{"line":127,"column":0},"end":{"line":127,"column":46}},"127":{"start":{"line":128,"column":0},"end":{"line":128,"column":83}},"128":{"start":{"line":129,"column":0},"end":{"line":129,"column":69}},"129":{"start":{"line":130,"column":0},"end":{"line":130,"column":13}},"130":{"start":{"line":131,"column":0},"end":{"line":131,"column":20}},"131":{"start":{"line":132,"column":0},"end":{"line":132,"column":12}},"132":{"start":{"line":133,"column":0},"end":{"line":133,"column":95}},"133":{"start":{"line":134,"column":0},"end":{"line":134,"column":0}},"134":{"start":{"line":135,"column":0},"end":{"line":135,"column":75}},"135":{"start":{"line":136,"column":0},"end":{"line":136,"column":82}},"136":{"start":{"line":137,"column":0},"end":{"line":137,"column":94}},"137":{"start":{"line":138,"column":0},"end":{"line":138,"column":102}},"138":{"start":{"line":139,"column":0},"end":{"line":139,"column":13}},"139":{"start":{"line":140,"column":0},"end":{"line":140,"column":0}},"140":{"start":{"line":141,"column":0},"end":{"line":141,"column":23}},"141":{"start":{"line":142,"column":0},"end":{"line":142,"column":9}},"142":{"start":{"line":143,"column":0},"end":{"line":143,"column":14}},"143":{"start":{"line":144,"column":0},"end":{"line":144,"column":0}},"144":{"start":{"line":145,"column":0},"end":{"line":145,"column":42}},"145":{"start":{"line":146,"column":0},"end":{"line":146,"column":46}},"146":{"start":{"line":147,"column":0},"end":{"line":147,"column":81}},"147":{"start":{"line":148,"column":0},"end":{"line":148,"column":70}},"148":{"start":{"line":149,"column":0},"end":{"line":149,"column":13}},"149":{"start":{"line":150,"column":0},"end":{"line":150,"column":0}},"150":{"start":{"line":151,"column":0},"end":{"line":151,"column":20}},"151":{"start":{"line":152,"column":0},"end":{"line":152,"column":79}},"152":{"start":{"line":153,"column":0},"end":{"line":153,"column":75}},"153":{"start":{"line":154,"column":0},"end":{"line":154,"column":82}},"154":{"start":{"line":155,"column":0},"end":{"line":155,"column":94}},"155":{"start":{"line":156,"column":0},"end":{"line":156,"column":102}},"156":{"start":{"line":157,"column":0},"end":{"line":157,"column":13}},"157":{"start":{"line":158,"column":0},"end":{"line":158,"column":0}},"158":{"start":{"line":159,"column":0},"end":{"line":159,"column":23}},"159":{"start":{"line":160,"column":0},"end":{"line":160,"column":9}},"160":{"start":{"line":161,"column":0},"end":{"line":161,"column":5}},"161":{"start":{"line":162,"column":0},"end":{"line":162,"column":4}},"162":{"start":{"line":163,"column":0},"end":{"line":163,"column":24}},"163":{"start":{"line":164,"column":0},"end":{"line":164,"column":73}},"164":{"start":{"line":165,"column":0},"end":{"line":165,"column":141}},"165":{"start":{"line":166,"column":0},"end":{"line":166,"column":122}},"166":{"start":{"line":167,"column":0},"end":{"line":167,"column":5}},"167":{"start":{"line":168,"column":0},"end":{"line":168,"column":0}},"168":{"start":{"line":169,"column":0},"end":{"line":169,"column":170}},"169":{"start":{"line":170,"column":0},"end":{"line":170,"column":26}},"170":{"start":{"line":171,"column":0},"end":{"line":171,"column":37}},"171":{"start":{"line":172,"column":0},"end":{"line":172,"column":40}},"172":{"start":{"line":173,"column":0},"end":{"line":173,"column":9}},"173":{"start":{"line":174,"column":0},"end":{"line":174,"column":50}},"174":{"start":{"line":175,"column":0},"end":{"line":175,"column":40}},"175":{"start":{"line":176,"column":0},"end":{"line":176,"column":47}},"176":{"start":{"line":177,"column":0},"end":{"line":177,"column":60}},"177":{"start":{"line":178,"column":0},"end":{"line":178,"column":70}},"178":{"start":{"line":179,"column":0},"end":{"line":179,"column":57}},"179":{"start":{"line":180,"column":0},"end":{"line":180,"column":131}},"180":{"start":{"line":181,"column":0},"end":{"line":181,"column":99}},"181":{"start":{"line":182,"column":0},"end":{"line":182,"column":45}},"182":{"start":{"line":183,"column":0},"end":{"line":183,"column":57}},"183":{"start":{"line":184,"column":0},"end":{"line":184,"column":106}},"184":{"start":{"line":185,"column":0},"end":{"line":185,"column":116}},"185":{"start":{"line":186,"column":0},"end":{"line":186,"column":74}},"186":{"start":{"line":187,"column":0},"end":{"line":187,"column":21}},"187":{"start":{"line":188,"column":0},"end":{"line":188,"column":20}},"188":{"start":{"line":189,"column":0},"end":{"line":189,"column":34}},"189":{"start":{"line":190,"column":0},"end":{"line":190,"column":17}},"190":{"start":{"line":191,"column":0},"end":{"line":191,"column":20}},"191":{"start":{"line":192,"column":0},"end":{"line":192,"column":47}},"192":{"start":{"line":193,"column":0},"end":{"line":193,"column":39}},"193":{"start":{"line":194,"column":0},"end":{"line":194,"column":58}},"194":{"start":{"line":195,"column":0},"end":{"line":195,"column":34}},"195":{"start":{"line":196,"column":0},"end":{"line":196,"column":102}},"196":{"start":{"line":197,"column":0},"end":{"line":197,"column":44}},"197":{"start":{"line":198,"column":0},"end":{"line":198,"column":164}},"198":{"start":{"line":199,"column":0},"end":{"line":199,"column":22}},"199":{"start":{"line":200,"column":0},"end":{"line":200,"column":24}},"200":{"start":{"line":201,"column":0},"end":{"line":201,"column":46}},"201":{"start":{"line":202,"column":0},"end":{"line":202,"column":56}},"202":{"start":{"line":203,"column":0},"end":{"line":203,"column":34}},"203":{"start":{"line":204,"column":0},"end":{"line":204,"column":102}},"204":{"start":{"line":205,"column":0},"end":{"line":205,"column":42}},"205":{"start":{"line":206,"column":0},"end":{"line":206,"column":164}},"206":{"start":{"line":207,"column":0},"end":{"line":207,"column":22}},"207":{"start":{"line":208,"column":0},"end":{"line":208,"column":17}},"208":{"start":{"line":209,"column":0},"end":{"line":209,"column":48}},"209":{"start":{"line":210,"column":0},"end":{"line":210,"column":0}},"210":{"start":{"line":211,"column":0},"end":{"line":211,"column":36}},"211":{"start":{"line":212,"column":0},"end":{"line":212,"column":29}},"212":{"start":{"line":213,"column":0},"end":{"line":213,"column":37}},"213":{"start":{"line":214,"column":0},"end":{"line":214,"column":38}},"214":{"start":{"line":215,"column":0},"end":{"line":215,"column":18}},"215":{"start":{"line":216,"column":0},"end":{"line":216,"column":0}},"216":{"start":{"line":217,"column":0},"end":{"line":217,"column":60}},"217":{"start":{"line":218,"column":0},"end":{"line":218,"column":16}},"218":{"start":{"line":219,"column":0},"end":{"line":219,"column":61}},"219":{"start":{"line":220,"column":0},"end":{"line":220,"column":85}},"220":{"start":{"line":221,"column":0},"end":{"line":221,"column":64}},"221":{"start":{"line":222,"column":0},"end":{"line":222,"column":82}},"222":{"start":{"line":223,"column":0},"end":{"line":223,"column":21}},"223":{"start":{"line":224,"column":0},"end":{"line":224,"column":17}},"224":{"start":{"line":225,"column":0},"end":{"line":225,"column":13}},"225":{"start":{"line":226,"column":0},"end":{"line":226,"column":9}},"226":{"start":{"line":227,"column":0},"end":{"line":227,"column":0}},"227":{"start":{"line":228,"column":0},"end":{"line":228,"column":37}},"228":{"start":{"line":229,"column":0},"end":{"line":229,"column":57}},"229":{"start":{"line":230,"column":0},"end":{"line":230,"column":5}}},"s":{"0":1,"1":1,"2":1,"3":2,"4":2,"5":2,"6":2,"7":2,"8":2,"9":6,"10":6,"11":6,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":6,"37":6,"38":6,"39":6,"40":4,"41":4,"42":4,"43":4,"44":4,"45":4,"46":4,"47":6,"48":2,"49":2,"50":2,"51":2,"52":6,"53":6,"54":6,"55":2,"56":2,"57":2,"58":1,"59":1,"60":6,"61":6,"62":6,"63":6,"64":6,"65":6,"66":6,"67":6,"68":6,"69":2,"70":2,"71":6,"72":6,"73":6,"74":6,"75":6,"76":6,"77":6,"78":6,"79":6,"80":6,"81":6,"82":6,"83":6,"84":6,"85":6,"86":6,"87":6,"88":6,"89":6,"90":6,"91":6,"92":6,"93":1,"94":1,"95":1,"96":1,"97":1,"98":6,"99":6,"100":6,"101":6,"102":6,"103":6,"104":6,"105":6,"106":6,"107":6,"108":6,"109":6,"110":6,"111":6,"112":6,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":6,"122":6,"123":4,"124":4,"125":4,"126":4,"127":0,"128":0,"129":0,"130":4,"131":4,"132":4,"133":4,"134":4,"135":0,"136":0,"137":0,"138":0,"139":4,"140":4,"141":4,"142":2,"143":2,"144":2,"145":2,"146":0,"147":0,"148":0,"149":2,"150":2,"151":2,"152":2,"153":0,"154":0,"155":0,"156":0,"157":2,"158":2,"159":2,"160":6,"161":1,"162":1,"163":1,"164":2,"165":2,"166":2,"167":1,"168":1,"169":4,"170":4,"171":3,"172":3,"173":4,"174":4,"175":4,"176":4,"177":4,"178":1,"179":1,"180":4,"181":4,"182":4,"183":4,"184":0,"185":4,"186":4,"187":4,"188":4,"189":4,"190":4,"191":3,"192":3,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":3,"200":3,"201":3,"202":3,"203":5,"204":5,"205":5,"206":3,"207":3,"208":3,"209":3,"210":3,"211":3,"212":3,"213":3,"214":3,"215":3,"216":3,"217":3,"218":3,"219":3,"220":3,"221":3,"222":3,"223":3,"224":3,"225":4,"226":4,"227":4,"228":0,"229":4},"branchMap":{"0":{"type":"branch","line":3,"loc":{"start":{"line":3,"column":28},"end":{"line":58,"column":1}},"locations":[{"start":{"line":3,"column":28},"end":{"line":58,"column":1}}]},"1":{"type":"branch","line":9,"loc":{"start":{"line":9,"column":43},"end":{"line":55,"column":13}},"locations":[{"start":{"line":9,"column":43},"end":{"line":55,"column":13}}]},"2":{"type":"branch","line":13,"loc":{"start":{"line":13,"column":-1},"end":{"line":36,"column":17}},"locations":[{"start":{"line":13,"column":-1},"end":{"line":36,"column":17}}]},"3":{"type":"branch","line":38,"loc":{"start":{"line":38,"column":62},"end":{"line":38,"column":109}},"locations":[{"start":{"line":38,"column":62},"end":{"line":38,"column":109}}]},"4":{"type":"branch","line":39,"loc":{"start":{"line":39,"column":76},"end":{"line":39,"column":147}},"locations":[{"start":{"line":39,"column":76},"end":{"line":39,"column":147}}]},"5":{"type":"branch","line":40,"loc":{"start":{"line":40,"column":27},"end":{"line":48,"column":27}},"locations":[{"start":{"line":40,"column":27},"end":{"line":48,"column":27}}]},"6":{"type":"branch","line":45,"loc":{"start":{"line":45,"column":72},"end":{"line":45,"column":181}},"locations":[{"start":{"line":45,"column":72},"end":{"line":45,"column":181}}]},"7":{"type":"branch","line":48,"loc":{"start":{"line":48,"column":21},"end":{"line":52,"column":21}},"locations":[{"start":{"line":48,"column":21},"end":{"line":52,"column":21}}]},"8":{"type":"branch","line":50,"loc":{"start":{"line":50,"column":68},"end":{"line":50,"column":178}},"locations":[{"start":{"line":50,"column":68},"end":{"line":50,"column":178}}]},"9":{"type":"branch","line":60,"loc":{"start":{"line":60,"column":15},"end":{"line":93,"column":1}},"locations":[{"start":{"line":60,"column":15},"end":{"line":93,"column":1}}]},"10":{"type":"branch","line":79,"loc":{"start":{"line":79,"column":24},"end":{"line":79,"column":30}},"locations":[{"start":{"line":79,"column":24},"end":{"line":79,"column":30}}]},"11":{"type":"branch","line":85,"loc":{"start":{"line":85,"column":19},"end":{"line":85,"column":64}},"locations":[{"start":{"line":85,"column":19},"end":{"line":85,"column":64}}]},"12":{"type":"branch","line":69,"loc":{"start":{"line":69,"column":13},"end":{"line":72,"column":9}},"locations":[{"start":{"line":69,"column":13},"end":{"line":72,"column":9}}]},"13":{"type":"branch","line":70,"loc":{"start":{"line":70,"column":27},"end":{"line":70,"column":57}},"locations":[{"start":{"line":70,"column":27},"end":{"line":70,"column":57}}]},"14":{"type":"branch","line":87,"loc":{"start":{"line":87,"column":24},"end":{"line":91,"column":5}},"locations":[{"start":{"line":87,"column":24},"end":{"line":91,"column":5}}]},"15":{"type":"branch","line":89,"loc":{"start":{"line":89,"column":22},"end":{"line":89,"column":66}},"locations":[{"start":{"line":89,"column":22},"end":{"line":89,"column":66}}]},"16":{"type":"branch","line":98,"loc":{"start":{"line":98,"column":4},"end":{"line":161,"column":5}},"locations":[{"start":{"line":98,"column":4},"end":{"line":161,"column":5}}]},"17":{"type":"branch","line":123,"loc":{"start":{"line":123,"column":16},"end":{"line":142,"column":9}},"locations":[{"start":{"line":123,"column":16},"end":{"line":142,"column":9}}]},"18":{"type":"branch","line":125,"loc":{"start":{"line":125,"column":38},"end":{"line":125,"column":70}},"locations":[{"start":{"line":125,"column":38},"end":{"line":125,"column":70}}]},"19":{"type":"branch","line":127,"loc":{"start":{"line":127,"column":45},"end":{"line":130,"column":13}},"locations":[{"start":{"line":127,"column":45},"end":{"line":130,"column":13}}]},"20":{"type":"branch","line":133,"loc":{"start":{"line":133,"column":29},"end":{"line":133,"column":65}},"locations":[{"start":{"line":133,"column":29},"end":{"line":133,"column":65}}]},"21":{"type":"branch","line":136,"loc":{"start":{"line":136,"column":-1},"end":{"line":139,"column":13}},"locations":[{"start":{"line":136,"column":-1},"end":{"line":139,"column":13}}]},"22":{"type":"branch","line":143,"loc":{"start":{"line":143,"column":-1},"end":{"line":160,"column":9}},"locations":[{"start":{"line":143,"column":-1},"end":{"line":160,"column":9}}]},"23":{"type":"branch","line":146,"loc":{"start":{"line":146,"column":45},"end":{"line":149,"column":13}},"locations":[{"start":{"line":146,"column":45},"end":{"line":149,"column":13}}]},"24":{"type":"branch","line":152,"loc":{"start":{"line":152,"column":29},"end":{"line":152,"column":57}},"locations":[{"start":{"line":152,"column":29},"end":{"line":152,"column":57}}]},"25":{"type":"branch","line":154,"loc":{"start":{"line":154,"column":-1},"end":{"line":157,"column":13}},"locations":[{"start":{"line":154,"column":-1},"end":{"line":157,"column":13}}]},"26":{"type":"branch","line":100,"loc":{"start":{"line":100,"column":36},"end":{"line":111,"column":9}},"locations":[{"start":{"line":100,"column":36},"end":{"line":111,"column":9}}]},"27":{"type":"branch","line":106,"loc":{"start":{"line":106,"column":20},"end":{"line":106,"column":38}},"locations":[{"start":{"line":106,"column":20},"end":{"line":106,"column":38}}]},"28":{"type":"branch","line":100,"loc":{"start":{"line":100,"column":52},"end":{"line":100,"column":83}},"locations":[{"start":{"line":100,"column":52},"end":{"line":100,"column":83}}]},"29":{"type":"branch","line":164,"loc":{"start":{"line":164,"column":4},"end":{"line":167,"column":5}},"locations":[{"start":{"line":164,"column":4},"end":{"line":167,"column":5}}]},"30":{"type":"branch","line":165,"loc":{"start":{"line":165,"column":16},"end":{"line":165,"column":141}},"locations":[{"start":{"line":165,"column":16},"end":{"line":165,"column":141}}]},"31":{"type":"branch","line":166,"loc":{"start":{"line":166,"column":66},"end":{"line":166,"column":94}},"locations":[{"start":{"line":166,"column":66},"end":{"line":166,"column":94}}]},"32":{"type":"branch","line":169,"loc":{"start":{"line":169,"column":4},"end":{"line":230,"column":5}},"locations":[{"start":{"line":169,"column":4},"end":{"line":230,"column":5}}]},"33":{"type":"branch","line":170,"loc":{"start":{"line":170,"column":19},"end":{"line":170,"column":26}},"locations":[{"start":{"line":170,"column":19},"end":{"line":170,"column":26}}]},"34":{"type":"branch","line":171,"loc":{"start":{"line":171,"column":36},"end":{"line":173,"column":9}},"locations":[{"start":{"line":171,"column":36},"end":{"line":173,"column":9}}]},"35":{"type":"branch","line":229,"loc":{"start":{"line":229,"column":-1},"end":{"line":229,"column":57}},"locations":[{"start":{"line":229,"column":-1},"end":{"line":229,"column":57}}]},"36":{"type":"branch","line":175,"loc":{"start":{"line":175,"column":26},"end":{"line":226,"column":9}},"locations":[{"start":{"line":175,"column":26},"end":{"line":226,"column":9}}]},"37":{"type":"branch","line":178,"loc":{"start":{"line":178,"column":45},"end":{"line":178,"column":67}},"locations":[{"start":{"line":178,"column":45},"end":{"line":178,"column":67}}]},"38":{"type":"branch","line":178,"loc":{"start":{"line":178,"column":69},"end":{"line":191,"column":19}},"locations":[{"start":{"line":178,"column":69},"end":{"line":191,"column":19}}]},"39":{"type":"branch","line":191,"loc":{"start":{"line":191,"column":13},"end":{"line":225,"column":13}},"locations":[{"start":{"line":191,"column":13},"end":{"line":225,"column":13}}]},"40":{"type":"branch","line":193,"loc":{"start":{"line":193,"column":31},"end":{"line":193,"column":36}},"locations":[{"start":{"line":193,"column":31},"end":{"line":193,"column":36}}]},"41":{"type":"branch","line":193,"loc":{"start":{"line":193,"column":38},"end":{"line":200,"column":23}},"locations":[{"start":{"line":193,"column":38},"end":{"line":200,"column":23}}]},"42":{"type":"branch","line":180,"loc":{"start":{"line":180,"column":27},"end":{"line":190,"column":17}},"locations":[{"start":{"line":180,"column":27},"end":{"line":190,"column":17}}]},"43":{"type":"branch","line":181,"loc":{"start":{"line":181,"column":59},"end":{"line":181,"column":99}},"locations":[{"start":{"line":181,"column":59},"end":{"line":181,"column":99}}]},"44":{"type":"branch","line":184,"loc":{"start":{"line":184,"column":63},"end":{"line":186,"column":31}},"locations":[{"start":{"line":184,"column":63},"end":{"line":186,"column":31}}]},"45":{"type":"branch","line":202,"loc":{"start":{"line":202,"column":26},"end":{"line":202,"column":55}},"locations":[{"start":{"line":202,"column":26},"end":{"line":202,"column":55}}]},"46":{"type":"branch","line":203,"loc":{"start":{"line":203,"column":26},"end":{"line":207,"column":21}},"locations":[{"start":{"line":203,"column":26},"end":{"line":207,"column":21}}]}},"b":{"0":[2],"1":[6],"2":[0],"3":[0],"4":[4],"5":[4],"6":[0],"7":[2],"8":[0],"9":[6],"10":[4],"11":[2],"12":[2],"13":[0],"14":[6],"15":[2],"16":[6],"17":[4],"18":[1],"19":[0],"20":[0],"21":[0],"22":[2],"23":[0],"24":[0],"25":[0],"26":[6],"27":[4],"28":[6],"29":[2],"30":[0],"31":[0],"32":[4],"33":[0],"34":[3],"35":[0],"36":[4],"37":[1],"38":[1],"39":[3],"40":[0],"41":[0],"42":[4],"43":[0],"44":[0],"45":[14],"46":[5]},"fnMap":{"0":{"name":"setListeners","decl":{"start":{"line":3,"column":28},"end":{"line":58,"column":1}},"loc":{"start":{"line":3,"column":28},"end":{"line":58,"column":1}},"line":3},"1":{"name":"default","decl":{"start":{"line":60,"column":15},"end":{"line":93,"column":1}},"loc":{"start":{"line":60,"column":15},"end":{"line":93,"column":1}},"line":60},"2":{"name":"set","decl":{"start":{"line":69,"column":13},"end":{"line":72,"column":9}},"loc":{"start":{"line":69,"column":13},"end":{"line":72,"column":9}},"line":69},"3":{"name":"subscribe","decl":{"start":{"line":98,"column":4},"end":{"line":161,"column":5}},"loc":{"start":{"line":98,"column":4},"end":{"line":161,"column":5}},"line":98},"4":{"name":"subscribeToFunction","decl":{"start":{"line":100,"column":36},"end":{"line":111,"column":9}},"loc":{"start":{"line":100,"column":36},"end":{"line":111,"column":9}},"line":100},"5":{"name":"setTarget","decl":{"start":{"line":100,"column":52},"end":{"line":100,"column":83}},"loc":{"start":{"line":100,"column":52},"end":{"line":100,"column":83}},"line":100},"6":{"name":"subscribeToGraph","decl":{"start":{"line":113,"column":33},"end":{"line":121,"column":9}},"loc":{"start":{"line":113,"column":33},"end":{"line":121,"column":9}},"line":113},"7":{"name":"unsubscribe","decl":{"start":{"line":164,"column":4},"end":{"line":167,"column":5}},"loc":{"start":{"line":164,"column":4},"end":{"line":167,"column":5}},"line":164},"8":{"name":"addLocalState","decl":{"start":{"line":169,"column":4},"end":{"line":230,"column":5}},"loc":{"start":{"line":169,"column":4},"end":{"line":230,"column":5}},"line":169},"9":{"name":"initState","decl":{"start":{"line":175,"column":26},"end":{"line":226,"column":9}},"loc":{"start":{"line":175,"column":26},"end":{"line":226,"column":9}},"line":175},"10":{"name":"props.","decl":{"start":{"line":180,"column":27},"end":{"line":190,"column":17}},"loc":{"start":{"line":180,"column":27},"end":{"line":190,"column":17}},"line":180},"11":{"name":"get","decl":{"start":{"line":194,"column":26},"end":{"line":194,"column":57}},"loc":{"start":{"line":194,"column":26},"end":{"line":194,"column":57}},"line":194},"12":{"name":"set","decl":{"start":{"line":195,"column":26},"end":{"line":199,"column":21}},"loc":{"start":{"line":195,"column":26},"end":{"line":199,"column":21}},"line":195},"13":{"name":"get","decl":{"start":{"line":202,"column":26},"end":{"line":202,"column":55}},"loc":{"start":{"line":202,"column":26},"end":{"line":202,"column":55}},"line":202},"14":{"name":"set","decl":{"start":{"line":203,"column":26},"end":{"line":207,"column":21}},"loc":{"start":{"line":203,"column":26},"end":{"line":207,"column":21}},"line":203}},"f":{"0":2,"1":6,"2":2,"3":6,"4":6,"5":6,"6":0,"7":2,"8":4,"9":4,"10":4,"11":0,"12":0,"13":14,"14":5}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-operator-loader/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-operator-loader/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":40}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":0}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":0}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":37}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":28}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":61}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":0}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":36}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":67}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":72}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":65}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":123}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":12}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":66}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":45}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":52}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":9}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":5}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":1}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":0}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":32}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":0}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":35}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":42}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":38}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":0}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":37}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":0}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":21}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":33}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":5}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":0}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":53}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":25}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":43}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":56}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":12}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":60}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":0}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":34}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":107}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":41}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":141}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":60}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":156}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":118}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":17}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":30}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":14}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":4}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":72}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":0}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":51}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":101}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":0}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":9}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":6}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":0}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":0}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":16}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":0}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":40}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":23}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":41}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":43}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":120}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":13}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":9}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":0}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":71}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":8}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":5}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":0}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":21}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":5,"5":5,"6":5,"7":5,"8":5,"9":5,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":5,"18":5,"19":1,"20":1,"21":6,"22":6,"23":6,"24":6,"25":6,"26":6,"27":6,"28":6,"29":6,"30":6,"31":6,"32":6,"33":6,"34":6,"35":5,"36":5,"37":5,"38":5,"39":5,"40":4,"41":4,"42":4,"43":3,"44":0,"45":3,"46":3,"47":4,"48":5,"49":5,"50":5,"51":5,"52":5,"53":5,"54":0,"55":0,"56":6,"57":6,"58":6,"59":6,"60":4,"61":4,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":4,"69":4,"70":4,"71":4,"72":6,"73":6,"74":6},"branchMap":{"0":{"type":"branch","line":4,"loc":{"start":{"line":4,"column":26},"end":{"line":19,"column":1}},"locations":[{"start":{"line":4,"column":26},"end":{"line":19,"column":1}}]},"1":{"type":"branch","line":9,"loc":{"start":{"line":9,"column":60},"end":{"line":9,"column":66}},"locations":[{"start":{"line":9,"column":60},"end":{"line":9,"column":66}}]},"2":{"type":"branch","line":10,"loc":{"start":{"line":10,"column":41},"end":{"line":10,"column":69}},"locations":[{"start":{"line":10,"column":41},"end":{"line":10,"column":69}}]},"3":{"type":"branch","line":10,"loc":{"start":{"line":10,"column":71},"end":{"line":17,"column":9}},"locations":[{"start":{"line":10,"column":71},"end":{"line":17,"column":9}}]},"4":{"type":"branch","line":21,"loc":{"start":{"line":21,"column":15},"end":{"line":75,"column":1}},"locations":[{"start":{"line":21,"column":15},"end":{"line":75,"column":1}}]},"5":{"type":"branch","line":60,"loc":{"start":{"line":60,"column":15},"end":{"line":72,"column":5}},"locations":[{"start":{"line":60,"column":15},"end":{"line":72,"column":5}}]},"6":{"type":"branch","line":62,"loc":{"start":{"line":62,"column":39},"end":{"line":68,"column":9}},"locations":[{"start":{"line":62,"column":39},"end":{"line":68,"column":9}}]},"7":{"type":"branch","line":34,"loc":{"start":{"line":34,"column":13},"end":{"line":34,"column":24}},"locations":[{"start":{"line":34,"column":13},"end":{"line":34,"column":24}}]},"8":{"type":"branch","line":35,"loc":{"start":{"line":35,"column":13},"end":{"line":56,"column":9}},"locations":[{"start":{"line":35,"column":13},"end":{"line":56,"column":9}}]},"9":{"type":"branch","line":54,"loc":{"start":{"line":54,"column":38},"end":{"line":56,"column":9}},"locations":[{"start":{"line":54,"column":38},"end":{"line":56,"column":9}}]},"10":{"type":"branch","line":40,"loc":{"start":{"line":40,"column":20},"end":{"line":49,"column":13}},"locations":[{"start":{"line":40,"column":20},"end":{"line":49,"column":13}}]},"11":{"type":"branch","line":41,"loc":{"start":{"line":41,"column":61},"end":{"line":41,"column":107}},"locations":[{"start":{"line":41,"column":61},"end":{"line":41,"column":107}}]},"12":{"type":"branch","line":43,"loc":{"start":{"line":43,"column":79},"end":{"line":47,"column":17}},"locations":[{"start":{"line":43,"column":79},"end":{"line":47,"column":17}}]},"13":{"type":"branch","line":44,"loc":{"start":{"line":44,"column":36},"end":{"line":44,"column":42}},"locations":[{"start":{"line":44,"column":36},"end":{"line":44,"column":42}}]},"14":{"type":"branch","line":44,"loc":{"start":{"line":44,"column":59},"end":{"line":46,"column":27}},"locations":[{"start":{"line":44,"column":59},"end":{"line":46,"column":27}}]},"15":{"type":"branch","line":46,"loc":{"start":{"line":46,"column":52},"end":{"line":46,"column":118}},"locations":[{"start":{"line":46,"column":52},"end":{"line":46,"column":118}}]}},"b":{"0":[5],"1":[0],"2":[1],"3":[0],"4":[6],"5":[4],"6":[0],"7":[29],"8":[5],"9":[0],"10":[4],"11":[0],"12":[3],"13":[2],"14":[0],"15":[2]},"fnMap":{"0":{"name":"checkIfSubscribed","decl":{"start":{"line":4,"column":26},"end":{"line":19,"column":1}},"loc":{"start":{"line":4,"column":26},"end":{"line":19,"column":1}},"line":4},"1":{"name":"ondelete","decl":{"start":{"line":12,"column":27},"end":{"line":12,"column":123}},"loc":{"start":{"line":12,"column":27},"end":{"line":12,"column":123}},"line":12},"2":{"name":"default","decl":{"start":{"line":21,"column":15},"end":{"line":75,"column":1}},"loc":{"start":{"line":21,"column":15},"end":{"line":75,"column":1}},"line":21},"3":{"name":"get","decl":{"start":{"line":34,"column":13},"end":{"line":34,"column":24}},"loc":{"start":{"line":34,"column":13},"end":{"line":34,"column":24}},"line":34},"4":{"name":"set","decl":{"start":{"line":35,"column":13},"end":{"line":56,"column":9}},"loc":{"start":{"line":35,"column":13},"end":{"line":56,"column":9}},"line":35},"5":{"name":"value","decl":{"start":{"line":40,"column":20},"end":{"line":49,"column":13}},"loc":{"start":{"line":40,"column":20},"end":{"line":49,"column":13}},"line":40}},"f":{"0":5,"1":0,"2":6,"3":29,"4":5,"5":4}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-parent-loader/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-parent-loader/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":36}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":0}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":40}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":68}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":0}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":34}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":0}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":86}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":71}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":0}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":57}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":51}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":22}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":26}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":23}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":27}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":6}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":0}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":64}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":0}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":160}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":0}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":37}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":152}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":81}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":0}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":120}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":45}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":0}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":9}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":5}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":0}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":0}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":21}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":6,"4":6,"5":6,"6":6,"7":6,"8":6,"9":6,"10":6,"11":6,"12":6,"13":6,"14":6,"15":6,"16":6,"17":6,"18":6,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":6,"32":6,"33":6,"34":6},"branchMap":{"0":{"type":"branch","line":3,"loc":{"start":{"line":3,"column":15},"end":{"line":35,"column":1}},"locations":[{"start":{"line":3,"column":15},"end":{"line":35,"column":1}}]},"1":{"type":"branch","line":8,"loc":{"start":{"line":8,"column":51},"end":{"line":8,"column":82}},"locations":[{"start":{"line":8,"column":51},"end":{"line":8,"column":82}}]},"2":{"type":"branch","line":9,"loc":{"start":{"line":9,"column":4},"end":{"line":9,"column":50}},"locations":[{"start":{"line":9,"column":4},"end":{"line":9,"column":50}}]},"3":{"type":"branch","line":19,"loc":{"start":{"line":19,"column":30},"end":{"line":19,"column":61}},"locations":[{"start":{"line":19,"column":30},"end":{"line":19,"column":61}}]},"4":{"type":"branch","line":19,"loc":{"start":{"line":19,"column":63},"end":{"line":31,"column":5}},"locations":[{"start":{"line":19,"column":63},"end":{"line":31,"column":5}}]}},"b":{"0":[6],"1":[1],"2":[1],"3":[5],"4":[0]},"fnMap":{"0":{"name":"default","decl":{"start":{"line":3,"column":15},"end":{"line":35,"column":1}},"loc":{"start":{"line":3,"column":15},"end":{"line":35,"column":1}},"line":3},"1":{"name":"ondelete","decl":{"start":{"line":27,"column":27},"end":{"line":27,"column":120}},"loc":{"start":{"line":27,"column":27},"end":{"line":27,"column":120}},"line":27}},"f":{"0":6,"1":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-props-loader/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-props-loader/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":47}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":0}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":0}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":35}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":22}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":96}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":1}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":32}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":0}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":19}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":37}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":50}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":78}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":0}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":23}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":39}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":51}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":38}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":37}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":0}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":49}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":54}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":67}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":73}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":63}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":63}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":42}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":41}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":113}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":36}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":42}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":26}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":44}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":71}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":23}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":0}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":37}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":85}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":17}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":13}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":9}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":6}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":4}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":254}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":67}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":93}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":5}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":0}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":21}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":0,"5":0,"6":0,"7":1,"8":6,"9":6,"10":6,"11":6,"12":6,"13":6,"14":6,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":6,"42":6,"43":6,"44":0,"45":0,"46":0,"47":6,"48":6,"49":6},"branchMap":{"0":{"type":"branch","line":8,"loc":{"start":{"line":8,"column":15},"end":{"line":50,"column":1}},"locations":[{"start":{"line":8,"column":15},"end":{"line":50,"column":1}}]},"1":{"type":"branch","line":44,"loc":{"start":{"line":44,"column":16},"end":{"line":47,"column":5}},"locations":[{"start":{"line":44,"column":16},"end":{"line":47,"column":5}}]},"2":{"type":"branch","line":13,"loc":{"start":{"line":13,"column":13},"end":{"line":13,"column":26}},"locations":[{"start":{"line":13,"column":13},"end":{"line":13,"column":26}}]}},"b":{"0":[6],"1":[0],"2":[3]},"fnMap":{"0":{"name":"proxyFunction","decl":{"start":{"line":4,"column":22},"end":{"line":7,"column":1}},"loc":{"start":{"line":4,"column":22},"end":{"line":7,"column":1}},"line":4},"1":{"name":"default","decl":{"start":{"line":8,"column":15},"end":{"line":50,"column":1}},"loc":{"start":{"line":8,"column":15},"end":{"line":50,"column":1}},"line":8},"2":{"name":"get","decl":{"start":{"line":13,"column":13},"end":{"line":13,"column":26}},"loc":{"start":{"line":13,"column":13},"end":{"line":13,"column":26}},"line":13},"3":{"name":"set","decl":{"start":{"line":15,"column":13},"end":{"line":41,"column":9}},"loc":{"start":{"line":15,"column":13},"end":{"line":41,"column":9}},"line":15}},"f":{"0":0,"1":6,"2":3,"3":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-root-loader/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/loaders/graphscript-root-loader/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":0}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":48}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":48}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":1}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":0}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":51}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":51}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":1}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":0}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":26}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":32}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":78}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":1}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":0}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":29}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":32}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":82}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":1}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":0}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":55}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":0}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":50}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":48}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":93}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":5}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":0}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":38}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":134}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":43}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":59}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":55}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":0}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":18}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":20}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":26}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":24}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":27}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":5}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":0}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":54}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":0}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":28}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":58}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":64}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":56}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":62}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":46}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":52}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":4}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":57}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":66}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":0}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":33}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":33}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":0}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":0}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":21}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":103}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":0}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":35}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":19}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":78}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":76}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":5}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":0}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":21}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":1}}},"s":{"0":1,"1":8,"2":8,"3":8,"4":1,"5":7,"6":7,"7":7,"8":1,"9":6,"10":6,"11":6,"12":6,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":6,"21":6,"22":6,"23":0,"24":0,"25":6,"26":6,"27":6,"28":6,"29":6,"30":6,"31":6,"32":6,"33":6,"34":6,"35":6,"36":6,"37":6,"38":6,"39":6,"40":6,"41":6,"42":6,"43":6,"44":6,"45":6,"46":6,"47":6,"48":6,"49":6,"50":6,"51":6,"52":6,"53":6,"54":6,"55":6,"56":6,"57":6,"58":6,"59":6,"60":6,"61":0,"62":0,"63":0,"64":6,"65":6,"66":6},"branchMap":{"0":{"type":"branch","line":2,"loc":{"start":{"line":2,"column":0},"end":{"line":4,"column":1}},"locations":[{"start":{"line":2,"column":0},"end":{"line":4,"column":1}}]},"1":{"type":"branch","line":6,"loc":{"start":{"line":6,"column":0},"end":{"line":8,"column":1}},"locations":[{"start":{"line":6,"column":0},"end":{"line":8,"column":1}}]},"2":{"type":"branch","line":10,"loc":{"start":{"line":10,"column":0},"end":{"line":13,"column":1}},"locations":[{"start":{"line":10,"column":0},"end":{"line":13,"column":1}}]},"3":{"type":"branch","line":12,"loc":{"start":{"line":12,"column":41},"end":{"line":12,"column":77}},"locations":[{"start":{"line":12,"column":41},"end":{"line":12,"column":77}}]},"4":{"type":"branch","line":15,"loc":{"start":{"line":15,"column":0},"end":{"line":18,"column":1}},"locations":[{"start":{"line":15,"column":0},"end":{"line":18,"column":1}}]},"5":{"type":"branch","line":17,"loc":{"start":{"line":17,"column":44},"end":{"line":17,"column":80}},"locations":[{"start":{"line":17,"column":44},"end":{"line":17,"column":80}}]},"6":{"type":"branch","line":20,"loc":{"start":{"line":20,"column":14},"end":{"line":67,"column":1}},"locations":[{"start":{"line":20,"column":14},"end":{"line":67,"column":1}}]},"7":{"type":"branch","line":23,"loc":{"start":{"line":23,"column":47},"end":{"line":25,"column":5}},"locations":[{"start":{"line":23,"column":47},"end":{"line":25,"column":5}}]},"8":{"type":"branch","line":27,"loc":{"start":{"line":27,"column":32},"end":{"line":27,"column":38}},"locations":[{"start":{"line":27,"column":32},"end":{"line":27,"column":38}}]},"9":{"type":"branch","line":28,"loc":{"start":{"line":28,"column":21},"end":{"line":28,"column":52}},"locations":[{"start":{"line":28,"column":21},"end":{"line":28,"column":52}}]},"10":{"type":"branch","line":50,"loc":{"start":{"line":50,"column":38},"end":{"line":50,"column":51}},"locations":[{"start":{"line":50,"column":38},"end":{"line":50,"column":51}}]},"11":{"type":"branch","line":51,"loc":{"start":{"line":51,"column":44},"end":{"line":51,"column":60}},"locations":[{"start":{"line":51,"column":44},"end":{"line":51,"column":60}}]},"12":{"type":"branch","line":58,"loc":{"start":{"line":58,"column":36},"end":{"line":58,"column":73}},"locations":[{"start":{"line":58,"column":36},"end":{"line":58,"column":73}}]},"13":{"type":"branch","line":61,"loc":{"start":{"line":61,"column":18},"end":{"line":64,"column":5}},"locations":[{"start":{"line":61,"column":18},"end":{"line":64,"column":5}}]}},"b":{"0":[8],"1":[7],"2":[6],"3":[8],"4":[1],"5":[2],"6":[6],"7":[0],"8":[0],"9":[0],"10":[0],"11":[0],"12":[0],"13":[0]},"fnMap":{"0":{"name":"addOnConnected","decl":{"start":{"line":2,"column":0},"end":{"line":4,"column":1}},"loc":{"start":{"line":2,"column":0},"end":{"line":4,"column":1}},"line":2},"1":{"name":"addOnDisconnected","decl":{"start":{"line":6,"column":0},"end":{"line":8,"column":1}},"loc":{"start":{"line":6,"column":0},"end":{"line":8,"column":1}},"line":6},"2":{"name":"callConnected","decl":{"start":{"line":10,"column":0},"end":{"line":13,"column":1}},"loc":{"start":{"line":10,"column":0},"end":{"line":13,"column":1}},"line":10},"3":{"name":"callDisconnected","decl":{"start":{"line":15,"column":0},"end":{"line":18,"column":1}},"loc":{"start":{"line":15,"column":0},"end":{"line":18,"column":1}},"line":15},"4":{"name":"default","decl":{"start":{"line":20,"column":14},"end":{"line":67,"column":1}},"loc":{"start":{"line":20,"column":14},"end":{"line":67,"column":1}},"line":20}},"f":{"0":8,"1":7,"2":6,"3":1,"4":6}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/parsers/function.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/parsers/function.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":0}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":42}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":116}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":4}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":0}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":39}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":40}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":1}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":0}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":0}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":31}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":39}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":21}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":70}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":28}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":25}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":48}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":17}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":17}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":9}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":0}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":14}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":1}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":0}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":32}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":110}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":17}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":30}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":16}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":66}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":31}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":9}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":6}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":2,"7":2,"8":1,"9":1,"10":1,"11":2,"12":2,"13":2,"14":1,"15":1,"16":2,"17":1,"18":1,"19":2,"20":2,"21":2,"22":2,"23":1,"24":1,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0},"branchMap":{"0":{"type":"branch","line":6,"loc":{"start":{"line":6,"column":6},"end":{"line":8,"column":1}},"locations":[{"start":{"line":6,"column":6},"end":{"line":8,"column":1}}]},"1":{"type":"branch","line":11,"loc":{"start":{"line":11,"column":6},"end":{"line":23,"column":1}},"locations":[{"start":{"line":11,"column":6},"end":{"line":23,"column":1}}]},"2":{"type":"branch","line":14,"loc":{"start":{"line":14,"column":12},"end":{"line":16,"column":25}},"locations":[{"start":{"line":14,"column":12},"end":{"line":16,"column":25}}]},"3":{"type":"branch","line":15,"loc":{"start":{"line":15,"column":16},"end":{"line":15,"column":28}},"locations":[{"start":{"line":15,"column":16},"end":{"line":15,"column":28}}]},"4":{"type":"branch","line":17,"loc":{"start":{"line":17,"column":8},"end":{"line":19,"column":17}},"locations":[{"start":{"line":17,"column":8},"end":{"line":19,"column":17}}]},"5":{"type":"branch","line":18,"loc":{"start":{"line":18,"column":8},"end":{"line":18,"column":17}},"locations":[{"start":{"line":18,"column":8},"end":{"line":18,"column":17}}]},"6":{"type":"branch","line":20,"loc":{"start":{"line":20,"column":4},"end":{"line":20,"column":8}},"locations":[{"start":{"line":20,"column":4},"end":{"line":20,"column":8}}]}},"b":{"0":[2],"1":[2],"2":[1],"3":[0],"4":[1],"5":[0],"6":[0]},"fnMap":{"0":{"name":"isNativeClass","decl":{"start":{"line":6,"column":6},"end":{"line":8,"column":1}},"loc":{"start":{"line":6,"column":6},"end":{"line":8,"column":1}},"line":6},"1":{"name":"isFunction","decl":{"start":{"line":11,"column":6},"end":{"line":23,"column":1}},"loc":{"start":{"line":11,"column":6},"end":{"line":23,"column":1}},"line":11},"2":{"name":"default","decl":{"start":{"line":25,"column":15},"end":{"line":34,"column":1}},"loc":{"start":{"line":25,"column":15},"end":{"line":34,"column":1}},"line":25}},"f":{"0":2,"1":2,"2":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/parsers/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/parsers/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":34}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":29}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":0}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":8}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":14}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":10}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1},"branchMap":{},"b":{},"fnMap":{},"f":{}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/core/parsers/string.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/core/parsers/string.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":39}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":60}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":26}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":1}}},"s":{"0":1,"1":0,"2":0,"3":0},"branchMap":{},"b":{},"fnMap":{"0":{"name":"default","decl":{"start":{"line":1,"column":15},"end":{"line":4,"column":1}},"loc":{"start":{"line":1,"column":15},"end":{"line":4,"column":1}},"line":1}},"f":{"0":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/loaders/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/loaders/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":70}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":0}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":81}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":0}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":3}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":75}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":3}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":47}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":4}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":28}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":69}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":0}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":61}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":0}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":28}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":33}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":40}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":13}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":10}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":5}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":0}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":4}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":1}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":0}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":3}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":3}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":93}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":72}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":3}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":6}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":113}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":109}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":3}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":27}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":77}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":107}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":3}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":3}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":3}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":41}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":0}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":51}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":37}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":51}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":37}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":50}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":49}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":42}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":68}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":19}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":14}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":48}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":37}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":50}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":49}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":79}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":19}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":14}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":9}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":0}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":97}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":37}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":57}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":89}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":27}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":61}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":37}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":68}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":60}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":60}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":61}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":33}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":65}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":30}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":34}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":25}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":56}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":31}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":21}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":17}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":42}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":30}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":14}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":10}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":15}},"85":{"start":{"line":86,"column":0},"end":{"line":86,"column":70}},"86":{"start":{"line":87,"column":0},"end":{"line":87,"column":12}},"87":{"start":{"line":88,"column":0},"end":{"line":88,"column":36}},"88":{"start":{"line":89,"column":0},"end":{"line":89,"column":23}},"89":{"start":{"line":90,"column":0},"end":{"line":90,"column":12}},"90":{"start":{"line":91,"column":0},"end":{"line":91,"column":37}},"91":{"start":{"line":92,"column":0},"end":{"line":92,"column":45}},"92":{"start":{"line":93,"column":0},"end":{"line":93,"column":75}},"93":{"start":{"line":94,"column":0},"end":{"line":94,"column":41}},"94":{"start":{"line":95,"column":0},"end":{"line":95,"column":32}},"95":{"start":{"line":96,"column":0},"end":{"line":96,"column":80}},"96":{"start":{"line":97,"column":0},"end":{"line":97,"column":17}},"97":{"start":{"line":98,"column":0},"end":{"line":98,"column":14}},"98":{"start":{"line":99,"column":0},"end":{"line":99,"column":0}},"99":{"start":{"line":100,"column":0},"end":{"line":100,"column":70}},"100":{"start":{"line":101,"column":0},"end":{"line":101,"column":12}},"101":{"start":{"line":102,"column":0},"end":{"line":102,"column":38}},"102":{"start":{"line":103,"column":0},"end":{"line":103,"column":68}},"103":{"start":{"line":104,"column":0},"end":{"line":104,"column":13}},"104":{"start":{"line":105,"column":0},"end":{"line":105,"column":0}},"105":{"start":{"line":106,"column":0},"end":{"line":106,"column":39}},"106":{"start":{"line":107,"column":0},"end":{"line":107,"column":38}},"107":{"start":{"line":108,"column":0},"end":{"line":108,"column":14}},"108":{"start":{"line":109,"column":0},"end":{"line":109,"column":0}},"109":{"start":{"line":110,"column":0},"end":{"line":110,"column":45}},"110":{"start":{"line":111,"column":0},"end":{"line":111,"column":9}},"111":{"start":{"line":112,"column":0},"end":{"line":112,"column":5}},"112":{"start":{"line":113,"column":0},"end":{"line":113,"column":0}},"113":{"start":{"line":114,"column":0},"end":{"line":114,"column":1}},"114":{"start":{"line":115,"column":0},"end":{"line":115,"column":0}},"115":{"start":{"line":116,"column":0},"end":{"line":116,"column":14}},"116":{"start":{"line":117,"column":0},"end":{"line":117,"column":3}},"117":{"start":{"line":118,"column":0},"end":{"line":118,"column":31}},"118":{"start":{"line":119,"column":0},"end":{"line":119,"column":59}},"119":{"start":{"line":120,"column":0},"end":{"line":120,"column":79}},"120":{"start":{"line":121,"column":0},"end":{"line":121,"column":3}},"121":{"start":{"line":122,"column":0},"end":{"line":122,"column":40}},"122":{"start":{"line":123,"column":0},"end":{"line":123,"column":3}},"123":{"start":{"line":124,"column":0},"end":{"line":124,"column":3}},"124":{"start":{"line":125,"column":0},"end":{"line":125,"column":47}},"125":{"start":{"line":126,"column":0},"end":{"line":126,"column":58}},"126":{"start":{"line":127,"column":0},"end":{"line":127,"column":37}},"127":{"start":{"line":128,"column":0},"end":{"line":128,"column":0}},"128":{"start":{"line":129,"column":0},"end":{"line":129,"column":24}},"129":{"start":{"line":130,"column":0},"end":{"line":130,"column":44}},"130":{"start":{"line":131,"column":0},"end":{"line":131,"column":79}},"131":{"start":{"line":132,"column":0},"end":{"line":132,"column":43}},"132":{"start":{"line":133,"column":0},"end":{"line":133,"column":89}},"133":{"start":{"line":134,"column":0},"end":{"line":134,"column":37}},"134":{"start":{"line":135,"column":0},"end":{"line":135,"column":0}},"135":{"start":{"line":136,"column":0},"end":{"line":136,"column":91}},"136":{"start":{"line":137,"column":0},"end":{"line":137,"column":17}},"137":{"start":{"line":138,"column":0},"end":{"line":138,"column":13}},"138":{"start":{"line":139,"column":0},"end":{"line":139,"column":0}},"139":{"start":{"line":140,"column":0},"end":{"line":140,"column":121}},"140":{"start":{"line":141,"column":0},"end":{"line":141,"column":92}},"141":{"start":{"line":142,"column":0},"end":{"line":142,"column":13}},"142":{"start":{"line":143,"column":0},"end":{"line":143,"column":0}},"143":{"start":{"line":144,"column":0},"end":{"line":144,"column":0}},"144":{"start":{"line":145,"column":0},"end":{"line":145,"column":36}},"145":{"start":{"line":146,"column":0},"end":{"line":146,"column":39}},"146":{"start":{"line":147,"column":0},"end":{"line":147,"column":26}},"147":{"start":{"line":148,"column":0},"end":{"line":148,"column":14}},"148":{"start":{"line":149,"column":0},"end":{"line":149,"column":8}},"149":{"start":{"line":150,"column":0},"end":{"line":150,"column":0}},"150":{"start":{"line":151,"column":0},"end":{"line":151,"column":34}},"151":{"start":{"line":152,"column":0},"end":{"line":152,"column":68}},"152":{"start":{"line":153,"column":0},"end":{"line":153,"column":9}},"153":{"start":{"line":154,"column":0},"end":{"line":154,"column":0}},"154":{"start":{"line":155,"column":0},"end":{"line":155,"column":41}},"155":{"start":{"line":156,"column":0},"end":{"line":156,"column":5}},"156":{"start":{"line":157,"column":0},"end":{"line":157,"column":1}},"157":{"start":{"line":158,"column":0},"end":{"line":158,"column":0}},"158":{"start":{"line":159,"column":0},"end":{"line":159,"column":0}},"159":{"start":{"line":160,"column":0},"end":{"line":160,"column":24}},"160":{"start":{"line":161,"column":0},"end":{"line":161,"column":3}},"161":{"start":{"line":162,"column":0},"end":{"line":162,"column":117}},"162":{"start":{"line":163,"column":0},"end":{"line":163,"column":82}},"163":{"start":{"line":164,"column":0},"end":{"line":164,"column":3}},"164":{"start":{"line":165,"column":0},"end":{"line":165,"column":35}},"165":{"start":{"line":166,"column":0},"end":{"line":166,"column":29}},"166":{"start":{"line":167,"column":0},"end":{"line":167,"column":57}},"167":{"start":{"line":168,"column":0},"end":{"line":168,"column":4}},"168":{"start":{"line":169,"column":0},"end":{"line":169,"column":3}},"169":{"start":{"line":170,"column":0},"end":{"line":170,"column":3}},"170":{"start":{"line":171,"column":0},"end":{"line":171,"column":48}},"171":{"start":{"line":172,"column":0},"end":{"line":172,"column":87}},"172":{"start":{"line":173,"column":0},"end":{"line":173,"column":33}},"173":{"start":{"line":174,"column":0},"end":{"line":174,"column":36}},"174":{"start":{"line":175,"column":0},"end":{"line":175,"column":47}},"175":{"start":{"line":176,"column":0},"end":{"line":176,"column":37}},"176":{"start":{"line":177,"column":0},"end":{"line":177,"column":72}},"177":{"start":{"line":178,"column":0},"end":{"line":178,"column":39}},"178":{"start":{"line":179,"column":0},"end":{"line":179,"column":71}},"179":{"start":{"line":180,"column":0},"end":{"line":180,"column":77}},"180":{"start":{"line":181,"column":0},"end":{"line":181,"column":115}},"181":{"start":{"line":182,"column":0},"end":{"line":182,"column":80}},"182":{"start":{"line":183,"column":0},"end":{"line":183,"column":99}},"183":{"start":{"line":184,"column":0},"end":{"line":184,"column":17}},"184":{"start":{"line":185,"column":0},"end":{"line":185,"column":65}},"185":{"start":{"line":186,"column":0},"end":{"line":186,"column":63}},"186":{"start":{"line":187,"column":0},"end":{"line":187,"column":36}},"187":{"start":{"line":188,"column":0},"end":{"line":188,"column":21}},"188":{"start":{"line":189,"column":0},"end":{"line":189,"column":61}},"189":{"start":{"line":190,"column":0},"end":{"line":190,"column":32}},"190":{"start":{"line":191,"column":0},"end":{"line":191,"column":18}},"191":{"start":{"line":192,"column":0},"end":{"line":192,"column":13}},"192":{"start":{"line":193,"column":0},"end":{"line":193,"column":26}},"193":{"start":{"line":194,"column":0},"end":{"line":194,"column":11}},"194":{"start":{"line":195,"column":0},"end":{"line":195,"column":5}},"195":{"start":{"line":196,"column":0},"end":{"line":196,"column":26}},"196":{"start":{"line":197,"column":0},"end":{"line":197,"column":44}},"197":{"start":{"line":198,"column":0},"end":{"line":198,"column":59}},"198":{"start":{"line":199,"column":0},"end":{"line":199,"column":90}},"199":{"start":{"line":200,"column":0},"end":{"line":200,"column":60}},"200":{"start":{"line":201,"column":0},"end":{"line":201,"column":20}},"201":{"start":{"line":202,"column":0},"end":{"line":202,"column":63}},"202":{"start":{"line":203,"column":0},"end":{"line":203,"column":58}},"203":{"start":{"line":204,"column":0},"end":{"line":204,"column":47}},"204":{"start":{"line":205,"column":0},"end":{"line":205,"column":89}},"205":{"start":{"line":206,"column":0},"end":{"line":206,"column":98}},"206":{"start":{"line":207,"column":0},"end":{"line":207,"column":143}},"207":{"start":{"line":208,"column":0},"end":{"line":208,"column":101}},"208":{"start":{"line":209,"column":0},"end":{"line":209,"column":114}},"209":{"start":{"line":210,"column":0},"end":{"line":210,"column":25}},"210":{"start":{"line":211,"column":0},"end":{"line":211,"column":83}},"211":{"start":{"line":212,"column":0},"end":{"line":212,"column":70}},"212":{"start":{"line":213,"column":0},"end":{"line":213,"column":44}},"213":{"start":{"line":214,"column":0},"end":{"line":214,"column":29}},"214":{"start":{"line":215,"column":0},"end":{"line":215,"column":76}},"215":{"start":{"line":216,"column":0},"end":{"line":216,"column":40}},"216":{"start":{"line":217,"column":0},"end":{"line":217,"column":26}},"217":{"start":{"line":218,"column":0},"end":{"line":218,"column":39}},"218":{"start":{"line":219,"column":0},"end":{"line":219,"column":21}},"219":{"start":{"line":220,"column":0},"end":{"line":220,"column":17}},"220":{"start":{"line":221,"column":0},"end":{"line":221,"column":13}},"221":{"start":{"line":222,"column":0},"end":{"line":222,"column":9}},"222":{"start":{"line":223,"column":0},"end":{"line":223,"column":5}},"223":{"start":{"line":224,"column":0},"end":{"line":224,"column":1}},"224":{"start":{"line":225,"column":0},"end":{"line":225,"column":0}},"225":{"start":{"line":226,"column":0},"end":{"line":226,"column":54}},"226":{"start":{"line":227,"column":0},"end":{"line":227,"column":3}},"227":{"start":{"line":228,"column":0},"end":{"line":228,"column":76}},"228":{"start":{"line":229,"column":0},"end":{"line":229,"column":3}},"229":{"start":{"line":230,"column":0},"end":{"line":230,"column":3}},"230":{"start":{"line":231,"column":0},"end":{"line":231,"column":62}},"231":{"start":{"line":232,"column":0},"end":{"line":232,"column":26}},"232":{"start":{"line":233,"column":0},"end":{"line":233,"column":44}},"233":{"start":{"line":234,"column":0},"end":{"line":234,"column":59}},"234":{"start":{"line":235,"column":0},"end":{"line":235,"column":52}},"235":{"start":{"line":236,"column":0},"end":{"line":236,"column":83}},"236":{"start":{"line":237,"column":0},"end":{"line":237,"column":17}},"237":{"start":{"line":238,"column":0},"end":{"line":238,"column":13}},"238":{"start":{"line":239,"column":0},"end":{"line":239,"column":9}},"239":{"start":{"line":240,"column":0},"end":{"line":240,"column":5}},"240":{"start":{"line":241,"column":0},"end":{"line":241,"column":1}},"241":{"start":{"line":242,"column":0},"end":{"line":242,"column":0}},"242":{"start":{"line":243,"column":0},"end":{"line":243,"column":54}},"243":{"start":{"line":244,"column":0},"end":{"line":244,"column":3}},"244":{"start":{"line":245,"column":0},"end":{"line":245,"column":90}},"245":{"start":{"line":246,"column":0},"end":{"line":246,"column":3}},"246":{"start":{"line":247,"column":0},"end":{"line":247,"column":3}},"247":{"start":{"line":248,"column":0},"end":{"line":248,"column":51}},"248":{"start":{"line":249,"column":0},"end":{"line":249,"column":26}},"249":{"start":{"line":250,"column":0},"end":{"line":250,"column":44}},"250":{"start":{"line":251,"column":0},"end":{"line":251,"column":59}},"251":{"start":{"line":252,"column":0},"end":{"line":252,"column":71}},"252":{"start":{"line":253,"column":0},"end":{"line":253,"column":110}},"253":{"start":{"line":254,"column":0},"end":{"line":254,"column":17}},"254":{"start":{"line":255,"column":0},"end":{"line":255,"column":13}},"255":{"start":{"line":256,"column":0},"end":{"line":256,"column":9}},"256":{"start":{"line":257,"column":0},"end":{"line":257,"column":5}},"257":{"start":{"line":258,"column":0},"end":{"line":258,"column":1}},"258":{"start":{"line":259,"column":0},"end":{"line":259,"column":0}},"259":{"start":{"line":260,"column":0},"end":{"line":260,"column":0}},"260":{"start":{"line":261,"column":0},"end":{"line":261,"column":3}},"261":{"start":{"line":262,"column":0},"end":{"line":262,"column":3}},"262":{"start":{"line":263,"column":0},"end":{"line":263,"column":87}},"263":{"start":{"line":264,"column":0},"end":{"line":264,"column":3}},"264":{"start":{"line":265,"column":0},"end":{"line":265,"column":3}},"265":{"start":{"line":266,"column":0},"end":{"line":266,"column":62}},"266":{"start":{"line":267,"column":0},"end":{"line":267,"column":26}},"267":{"start":{"line":268,"column":0},"end":{"line":268,"column":44}},"268":{"start":{"line":269,"column":0},"end":{"line":269,"column":59}},"269":{"start":{"line":270,"column":0},"end":{"line":270,"column":118}},"270":{"start":{"line":271,"column":0},"end":{"line":271,"column":60}},"271":{"start":{"line":272,"column":0},"end":{"line":272,"column":66}},"272":{"start":{"line":273,"column":0},"end":{"line":273,"column":58}},"273":{"start":{"line":274,"column":0},"end":{"line":274,"column":66}},"274":{"start":{"line":275,"column":0},"end":{"line":275,"column":39}},"275":{"start":{"line":276,"column":0},"end":{"line":276,"column":21}},"276":{"start":{"line":277,"column":0},"end":{"line":277,"column":17}},"277":{"start":{"line":278,"column":0},"end":{"line":278,"column":13}},"278":{"start":{"line":279,"column":0},"end":{"line":279,"column":9}},"279":{"start":{"line":280,"column":0},"end":{"line":280,"column":5}},"280":{"start":{"line":281,"column":0},"end":{"line":281,"column":1}},"281":{"start":{"line":282,"column":0},"end":{"line":282,"column":0}},"282":{"start":{"line":283,"column":0},"end":{"line":283,"column":0}},"283":{"start":{"line":284,"column":0},"end":{"line":284,"column":81}},"284":{"start":{"line":285,"column":0},"end":{"line":285,"column":29}},"285":{"start":{"line":286,"column":0},"end":{"line":286,"column":35}},"286":{"start":{"line":287,"column":0},"end":{"line":287,"column":39}},"287":{"start":{"line":288,"column":0},"end":{"line":288,"column":36}},"288":{"start":{"line":289,"column":0},"end":{"line":289,"column":67}},"289":{"start":{"line":290,"column":0},"end":{"line":290,"column":35}},"290":{"start":{"line":291,"column":0},"end":{"line":291,"column":40}},"291":{"start":{"line":292,"column":0},"end":{"line":292,"column":35}},"292":{"start":{"line":293,"column":0},"end":{"line":293,"column":24}},"293":{"start":{"line":294,"column":0},"end":{"line":294,"column":37}},"294":{"start":{"line":295,"column":0},"end":{"line":295,"column":30}},"295":{"start":{"line":296,"column":0},"end":{"line":296,"column":38}},"296":{"start":{"line":297,"column":0},"end":{"line":297,"column":45}},"297":{"start":{"line":298,"column":0},"end":{"line":298,"column":13}},"298":{"start":{"line":299,"column":0},"end":{"line":299,"column":4}},"299":{"start":{"line":300,"column":0},"end":{"line":300,"column":36}},"300":{"start":{"line":301,"column":0},"end":{"line":301,"column":45}},"301":{"start":{"line":302,"column":0},"end":{"line":302,"column":10}},"302":{"start":{"line":303,"column":0},"end":{"line":303,"column":5}},"303":{"start":{"line":304,"column":0},"end":{"line":304,"column":129}},"304":{"start":{"line":305,"column":0},"end":{"line":305,"column":1}},"305":{"start":{"line":306,"column":0},"end":{"line":306,"column":0}},"306":{"start":{"line":307,"column":0},"end":{"line":307,"column":62}},"307":{"start":{"line":308,"column":0},"end":{"line":308,"column":24}},"308":{"start":{"line":309,"column":0},"end":{"line":309,"column":13}},"309":{"start":{"line":310,"column":0},"end":{"line":310,"column":9}},"310":{"start":{"line":311,"column":0},"end":{"line":311,"column":12}},"311":{"start":{"line":312,"column":0},"end":{"line":312,"column":14}},"312":{"start":{"line":313,"column":0},"end":{"line":313,"column":28}},"313":{"start":{"line":314,"column":0},"end":{"line":314,"column":17}},"314":{"start":{"line":315,"column":0},"end":{"line":315,"column":28}},"315":{"start":{"line":316,"column":0},"end":{"line":316,"column":24}},"316":{"start":{"line":317,"column":0},"end":{"line":317,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":6,"9":6,"10":6,"11":6,"12":6,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":6,"21":6,"22":6,"23":1,"24":1,"25":1,"26":1,"27":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":6,"41":6,"42":4,"43":4,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":4,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":4,"60":4,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":4,"85":4,"86":1,"87":1,"88":1,"89":1,"90":1,"91":1,"92":1,"93":1,"94":1,"95":1,"96":1,"97":1,"98":1,"99":1,"100":1,"101":1,"102":1,"103":1,"104":1,"105":1,"106":1,"107":1,"108":1,"109":1,"110":1,"111":4,"112":6,"113":6,"114":1,"115":1,"116":1,"117":1,"118":1,"119":1,"120":1,"121":1,"122":1,"123":1,"124":1,"125":6,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":6,"157":1,"158":1,"159":1,"160":1,"161":1,"162":1,"163":1,"164":1,"165":1,"166":1,"167":1,"168":1,"169":1,"170":1,"171":6,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":6,"196":6,"197":6,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":6,"222":6,"223":6,"224":1,"225":1,"226":1,"227":1,"228":1,"229":1,"230":1,"231":6,"232":6,"233":6,"234":0,"235":0,"236":0,"237":0,"238":6,"239":6,"240":6,"241":1,"242":1,"243":1,"244":1,"245":1,"246":1,"247":1,"248":6,"249":6,"250":6,"251":0,"252":0,"253":0,"254":0,"255":6,"256":6,"257":6,"258":1,"259":1,"260":1,"261":1,"262":1,"263":1,"264":1,"265":1,"266":6,"267":6,"268":6,"269":0,"270":0,"271":0,"272":0,"273":0,"274":0,"275":0,"276":0,"277":0,"278":6,"279":6,"280":6,"281":1,"282":1,"283":1,"284":6,"285":6,"286":6,"287":0,"288":6,"289":0,"290":6,"291":4,"292":6,"293":0,"294":0,"295":0,"296":0,"297":0,"298":0,"299":0,"300":0,"301":0,"302":0,"303":6,"304":6,"305":1,"306":1,"307":1,"308":1,"309":1,"310":1,"311":1,"312":1,"313":1,"314":1,"315":1,"316":1},"branchMap":{"0":{"type":"branch","line":8,"loc":{"start":{"line":8,"column":24},"end":{"line":23,"column":1}},"locations":[{"start":{"line":8,"column":24},"end":{"line":23,"column":1}}]},"1":{"type":"branch","line":11,"loc":{"start":{"line":11,"column":62},"end":{"line":11,"column":68}},"locations":[{"start":{"line":11,"column":62},"end":{"line":11,"column":68}}]},"2":{"type":"branch","line":13,"loc":{"start":{"line":13,"column":27},"end":{"line":13,"column":58}},"locations":[{"start":{"line":13,"column":27},"end":{"line":13,"column":58}}]},"3":{"type":"branch","line":13,"loc":{"start":{"line":13,"column":60},"end":{"line":20,"column":5}},"locations":[{"start":{"line":13,"column":60},"end":{"line":20,"column":5}}]},"4":{"type":"branch","line":40,"loc":{"start":{"line":40,"column":20},"end":{"line":114,"column":1}},"locations":[{"start":{"line":40,"column":20},"end":{"line":114,"column":1}}]},"5":{"type":"branch","line":42,"loc":{"start":{"line":42,"column":22},"end":{"line":42,"column":48}},"locations":[{"start":{"line":42,"column":22},"end":{"line":42,"column":48}}]},"6":{"type":"branch","line":42,"loc":{"start":{"line":42,"column":50},"end":{"line":112,"column":5}},"locations":[{"start":{"line":42,"column":50},"end":{"line":112,"column":5}}]},"7":{"type":"branch","line":44,"loc":{"start":{"line":44,"column":50},"end":{"line":52,"column":15}},"locations":[{"start":{"line":44,"column":50},"end":{"line":52,"column":15}}]},"8":{"type":"branch","line":52,"loc":{"start":{"line":52,"column":47},"end":{"line":59,"column":9}},"locations":[{"start":{"line":52,"column":47},"end":{"line":59,"column":9}}]},"9":{"type":"branch","line":61,"loc":{"start":{"line":61,"column":96},"end":{"line":84,"column":10}},"locations":[{"start":{"line":61,"column":96},"end":{"line":84,"column":10}}]},"10":{"type":"branch","line":86,"loc":{"start":{"line":86,"column":27},"end":{"line":86,"column":67}},"locations":[{"start":{"line":86,"column":27},"end":{"line":86,"column":67}}]},"11":{"type":"branch","line":86,"loc":{"start":{"line":86,"column":69},"end":{"line":111,"column":9}},"locations":[{"start":{"line":86,"column":69},"end":{"line":111,"column":9}}]},"12":{"type":"branch","line":92,"loc":{"start":{"line":92,"column":31},"end":{"line":98,"column":13}},"locations":[{"start":{"line":92,"column":31},"end":{"line":98,"column":13}}]},"13":{"type":"branch","line":93,"loc":{"start":{"line":93,"column":48},"end":{"line":93,"column":75}},"locations":[{"start":{"line":93,"column":48},"end":{"line":93,"column":75}}]},"14":{"type":"branch","line":100,"loc":{"start":{"line":100,"column":46},"end":{"line":100,"column":69}},"locations":[{"start":{"line":100,"column":46},"end":{"line":100,"column":69}}]},"15":{"type":"branch","line":102,"loc":{"start":{"line":102,"column":27},"end":{"line":104,"column":13}},"locations":[{"start":{"line":102,"column":27},"end":{"line":104,"column":13}}]},"16":{"type":"branch","line":106,"loc":{"start":{"line":106,"column":32},"end":{"line":108,"column":13}},"locations":[{"start":{"line":106,"column":32},"end":{"line":108,"column":13}}]},"17":{"type":"branch","line":125,"loc":{"start":{"line":125,"column":24},"end":{"line":157,"column":1}},"locations":[{"start":{"line":125,"column":24},"end":{"line":157,"column":1}}]},"18":{"type":"branch","line":126,"loc":{"start":{"line":126,"column":57},"end":{"line":156,"column":5}},"locations":[{"start":{"line":126,"column":57},"end":{"line":156,"column":5}}]},"19":{"type":"branch","line":171,"loc":{"start":{"line":171,"column":25},"end":{"line":224,"column":1}},"locations":[{"start":{"line":171,"column":25},"end":{"line":224,"column":1}}]},"20":{"type":"branch","line":172,"loc":{"start":{"line":172,"column":40},"end":{"line":172,"column":59}},"locations":[{"start":{"line":172,"column":40},"end":{"line":172,"column":59}}]},"21":{"type":"branch","line":172,"loc":{"start":{"line":172,"column":59},"end":{"line":172,"column":84}},"locations":[{"start":{"line":172,"column":59},"end":{"line":172,"column":84}}]},"22":{"type":"branch","line":172,"loc":{"start":{"line":172,"column":86},"end":{"line":195,"column":5}},"locations":[{"start":{"line":172,"column":86},"end":{"line":195,"column":5}}]},"23":{"type":"branch","line":198,"loc":{"start":{"line":198,"column":58},"end":{"line":221,"column":13}},"locations":[{"start":{"line":198,"column":58},"end":{"line":221,"column":13}}]},"24":{"type":"branch","line":231,"loc":{"start":{"line":231,"column":39},"end":{"line":241,"column":1}},"locations":[{"start":{"line":231,"column":39},"end":{"line":241,"column":1}}]},"25":{"type":"branch","line":234,"loc":{"start":{"line":234,"column":58},"end":{"line":238,"column":13}},"locations":[{"start":{"line":234,"column":58},"end":{"line":238,"column":13}}]},"26":{"type":"branch","line":248,"loc":{"start":{"line":248,"column":28},"end":{"line":258,"column":1}},"locations":[{"start":{"line":248,"column":28},"end":{"line":258,"column":1}}]},"27":{"type":"branch","line":251,"loc":{"start":{"line":251,"column":58},"end":{"line":255,"column":13}},"locations":[{"start":{"line":251,"column":58},"end":{"line":255,"column":13}}]},"28":{"type":"branch","line":266,"loc":{"start":{"line":266,"column":39},"end":{"line":281,"column":1}},"locations":[{"start":{"line":266,"column":39},"end":{"line":281,"column":1}}]},"29":{"type":"branch","line":269,"loc":{"start":{"line":269,"column":58},"end":{"line":278,"column":13}},"locations":[{"start":{"line":269,"column":58},"end":{"line":278,"column":13}}]},"30":{"type":"branch","line":284,"loc":{"start":{"line":284,"column":36},"end":{"line":305,"column":1}},"locations":[{"start":{"line":284,"column":36},"end":{"line":305,"column":1}}]},"31":{"type":"branch","line":287,"loc":{"start":{"line":287,"column":16},"end":{"line":287,"column":36}},"locations":[{"start":{"line":287,"column":16},"end":{"line":287,"column":36}}]},"32":{"type":"branch","line":287,"loc":{"start":{"line":287,"column":38},"end":{"line":289,"column":11}},"locations":[{"start":{"line":287,"column":38},"end":{"line":289,"column":11}}]},"33":{"type":"branch","line":289,"loc":{"start":{"line":289,"column":31},"end":{"line":289,"column":64}},"locations":[{"start":{"line":289,"column":31},"end":{"line":289,"column":64}}]},"34":{"type":"branch","line":289,"loc":{"start":{"line":289,"column":66},"end":{"line":291,"column":6}},"locations":[{"start":{"line":289,"column":66},"end":{"line":291,"column":6}}]},"35":{"type":"branch","line":291,"loc":{"start":{"line":291,"column":39},"end":{"line":293,"column":6}},"locations":[{"start":{"line":291,"column":39},"end":{"line":293,"column":6}}]},"36":{"type":"branch","line":293,"loc":{"start":{"line":293,"column":23},"end":{"line":303,"column":5}},"locations":[{"start":{"line":293,"column":23},"end":{"line":303,"column":5}}]},"37":{"type":"branch","line":304,"loc":{"start":{"line":304,"column":64},"end":{"line":304,"column":76}},"locations":[{"start":{"line":304,"column":64},"end":{"line":304,"column":76}}]},"38":{"type":"branch","line":304,"loc":{"start":{"line":304,"column":78},"end":{"line":304,"column":129}},"locations":[{"start":{"line":304,"column":78},"end":{"line":304,"column":129}}]}},"b":{"0":[6],"1":[0],"2":[0],"3":[0],"4":[6],"5":[4],"6":[4],"7":[0],"8":[0],"9":[0],"10":[1],"11":[1],"12":[1],"13":[0],"14":[1],"15":[1],"16":[1],"17":[6],"18":[0],"19":[6],"20":[0],"21":[0],"22":[0],"23":[0],"24":[6],"25":[0],"26":[6],"27":[0],"28":[6],"29":[0],"30":[6],"31":[0],"32":[0],"33":[2],"34":[0],"35":[4],"36":[0],"37":[3],"38":[1]},"fnMap":{"0":{"name":"backprop","decl":{"start":{"line":8,"column":24},"end":{"line":23,"column":1}},"loc":{"start":{"line":8,"column":24},"end":{"line":23,"column":1}},"line":8},"1":{"name":"loop","decl":{"start":{"line":40,"column":20},"end":{"line":114,"column":1}},"loc":{"start":{"line":40,"column":20},"end":{"line":114,"column":1}},"line":40},"2":{"name":"node.__operator","decl":{"start":{"line":46,"column":30},"end":{"line":51,"column":13}},"loc":{"start":{"line":46,"column":30},"end":{"line":51,"column":13}},"line":46},"3":{"name":"node.__operator","decl":{"start":{"line":54,"column":30},"end":{"line":58,"column":13}},"loc":{"start":{"line":54,"column":30},"end":{"line":58,"column":13}},"line":54},"4":{"name":"node.__operator","decl":{"start":{"line":63,"column":31},"end":{"line":83,"column":13}},"loc":{"start":{"line":63,"column":31},"end":{"line":83,"column":13}},"line":63},"5":{"name":"node.__operator","decl":{"start":{"line":92,"column":31},"end":{"line":98,"column":13}},"loc":{"start":{"line":92,"column":31},"end":{"line":98,"column":13}},"line":92},"6":{"name":"onstart","decl":{"start":{"line":100,"column":46},"end":{"line":100,"column":69}},"loc":{"start":{"line":100,"column":46},"end":{"line":100,"column":69}},"line":100},"7":{"name":"ondelete","decl":{"start":{"line":102,"column":27},"end":{"line":104,"column":13}},"loc":{"start":{"line":102,"column":27},"end":{"line":104,"column":13}},"line":102},"8":{"name":"animate","decl":{"start":{"line":125,"column":24},"end":{"line":157,"column":1}},"loc":{"start":{"line":125,"column":24},"end":{"line":157,"column":1}},"line":125},"9":{"name":"node.__operator","decl":{"start":{"line":130,"column":30},"end":{"line":138,"column":13}},"loc":{"start":{"line":130,"column":30},"end":{"line":138,"column":13}},"line":130},"10":{"name":"onstart","decl":{"start":{"line":141,"column":26},"end":{"line":141,"column":91}},"loc":{"start":{"line":141,"column":26},"end":{"line":141,"column":91}},"line":141},"11":{"name":"ondelete","decl":{"start":{"line":151,"column":23},"end":{"line":153,"column":9}},"loc":{"start":{"line":151,"column":23},"end":{"line":153,"column":9}},"line":151},"12":{"name":"branching","decl":{"start":{"line":171,"column":25},"end":{"line":224,"column":1}},"loc":{"start":{"line":171,"column":25},"end":{"line":224,"column":1}},"line":171},"13":{"name":"node.__operator","decl":{"start":{"line":175,"column":27},"end":{"line":194,"column":9}},"loc":{"start":{"line":175,"column":27},"end":{"line":194,"column":9}},"line":175},"14":{"name":"node.__listeners.callback","decl":{"start":{"line":203,"column":48},"end":{"line":219,"column":21}},"loc":{"start":{"line":203,"column":48},"end":{"line":219,"column":21}},"line":203},"15":{"name":"triggerListenerOncreate","decl":{"start":{"line":231,"column":39},"end":{"line":241,"column":1}},"loc":{"start":{"line":231,"column":39},"end":{"line":241,"column":1}},"line":231},"16":{"name":"bindListener","decl":{"start":{"line":248,"column":28},"end":{"line":258,"column":1}},"loc":{"start":{"line":248,"column":28},"end":{"line":258,"column":1}},"line":248},"17":{"name":"transformListenerResult","decl":{"start":{"line":266,"column":39},"end":{"line":281,"column":1}},"loc":{"start":{"line":266,"column":39},"end":{"line":281,"column":1}},"line":266},"18":{"name":"node.__listeners.callback","decl":{"start":{"line":273,"column":48},"end":{"line":276,"column":21}},"loc":{"start":{"line":273,"column":48},"end":{"line":276,"column":21}},"line":273},"19":{"name":"substitute__operator","decl":{"start":{"line":284,"column":36},"end":{"line":305,"column":1}},"loc":{"start":{"line":284,"column":36},"end":{"line":305,"column":1}},"line":284}},"f":{"0":6,"1":6,"2":0,"3":0,"4":0,"5":1,"6":1,"7":1,"8":6,"9":0,"10":0,"11":0,"12":6,"13":0,"14":0,"15":6,"16":6,"17":6,"18":0,"19":6}} +,"/Users/garrettflynn/Documents/Github/graphscript/src/loaders/html/html.loader.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/src/loaders/html/html.loader.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":0}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":69}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":0}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":56}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":25}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":42}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":42}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":42}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":85}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":187}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":114}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":42}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":23}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":49}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":23}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":127}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":0}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":10}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":83}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":157}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":1}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":0}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":27}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":18}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":6}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":0}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":28}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":32}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":28}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":27}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":48}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":38}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":99}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":0}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":0}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":0}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":25}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":39}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":76}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":5}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":0}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":25}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":39}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":52}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":41}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":9}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":5}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":0}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":25}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":39}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":52}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":41}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":9}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":5}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":0}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":40}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":77}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":34}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":84}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":71}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":9}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":0}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":59}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":36}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":133}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":10}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":5}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":4}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":45}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":0}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":27}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":80}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":0}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":6}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":0}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":67}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":43}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":129}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":51}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":9}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":5}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":4}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":45}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":30}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":0}},"85":{"start":{"line":86,"column":0},"end":{"line":86,"column":32}},"86":{"start":{"line":87,"column":0},"end":{"line":87,"column":37}},"87":{"start":{"line":88,"column":0},"end":{"line":88,"column":74}},"88":{"start":{"line":89,"column":0},"end":{"line":89,"column":30}},"89":{"start":{"line":90,"column":0},"end":{"line":90,"column":95}},"90":{"start":{"line":91,"column":0},"end":{"line":91,"column":82}},"91":{"start":{"line":92,"column":0},"end":{"line":92,"column":98}},"92":{"start":{"line":93,"column":0},"end":{"line":93,"column":62}},"93":{"start":{"line":94,"column":0},"end":{"line":94,"column":57}},"94":{"start":{"line":95,"column":0},"end":{"line":95,"column":105}},"95":{"start":{"line":96,"column":0},"end":{"line":96,"column":82}},"96":{"start":{"line":97,"column":0},"end":{"line":97,"column":64}},"97":{"start":{"line":98,"column":0},"end":{"line":98,"column":59}},"98":{"start":{"line":99,"column":0},"end":{"line":99,"column":149}},"99":{"start":{"line":100,"column":0},"end":{"line":100,"column":8}},"100":{"start":{"line":101,"column":0},"end":{"line":101,"column":66}},"101":{"start":{"line":102,"column":0},"end":{"line":102,"column":105}},"102":{"start":{"line":103,"column":0},"end":{"line":103,"column":0}},"103":{"start":{"line":104,"column":0},"end":{"line":104,"column":11}},"104":{"start":{"line":105,"column":0},"end":{"line":105,"column":0}},"105":{"start":{"line":106,"column":0},"end":{"line":106,"column":40}},"106":{"start":{"line":107,"column":0},"end":{"line":107,"column":49}},"107":{"start":{"line":108,"column":0},"end":{"line":108,"column":0}},"108":{"start":{"line":109,"column":0},"end":{"line":109,"column":52}},"109":{"start":{"line":110,"column":0},"end":{"line":110,"column":39}},"110":{"start":{"line":111,"column":0},"end":{"line":111,"column":13}},"111":{"start":{"line":112,"column":0},"end":{"line":112,"column":0}},"112":{"start":{"line":113,"column":0},"end":{"line":113,"column":30}},"113":{"start":{"line":114,"column":0},"end":{"line":114,"column":67}},"114":{"start":{"line":115,"column":0},"end":{"line":115,"column":13}},"115":{"start":{"line":116,"column":0},"end":{"line":116,"column":11}},"116":{"start":{"line":117,"column":0},"end":{"line":117,"column":5}},"117":{"start":{"line":118,"column":0},"end":{"line":118,"column":0}},"118":{"start":{"line":119,"column":0},"end":{"line":119,"column":0}},"119":{"start":{"line":120,"column":0},"end":{"line":120,"column":1}},"120":{"start":{"line":121,"column":0},"end":{"line":121,"column":0}},"121":{"start":{"line":122,"column":0},"end":{"line":122,"column":25}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":1,"121":1},"branchMap":{},"b":{},"fnMap":{"0":{"name":"htmlloader","decl":{"start":{"line":23,"column":26},"end":{"line":120,"column":1}},"loc":{"start":{"line":23,"column":26},"end":{"line":120,"column":1}},"line":23}},"f":{"0":0}} +,"/Users/garrettflynn/Documents/Github/graphscript/tests/utils/index.ts": {"path":"/Users/garrettflynn/Documents/Github/graphscript/tests/utils/index.ts","all":false,"statementMap":{"0":{"start":{"line":1,"column":0},"end":{"line":1,"column":49}},"1":{"start":{"line":2,"column":0},"end":{"line":2,"column":0}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":44}},"3":{"start":{"line":4,"column":0},"end":{"line":4,"column":0}},"4":{"start":{"line":5,"column":0},"end":{"line":5,"column":36}},"5":{"start":{"line":6,"column":0},"end":{"line":6,"column":0}},"6":{"start":{"line":7,"column":0},"end":{"line":7,"column":36}},"7":{"start":{"line":8,"column":0},"end":{"line":8,"column":0}},"8":{"start":{"line":9,"column":0},"end":{"line":9,"column":14}},"9":{"start":{"line":10,"column":0},"end":{"line":10,"column":43}},"10":{"start":{"line":11,"column":0},"end":{"line":11,"column":16}},"11":{"start":{"line":12,"column":0},"end":{"line":12,"column":33}},"12":{"start":{"line":13,"column":0},"end":{"line":13,"column":0}},"13":{"start":{"line":14,"column":0},"end":{"line":14,"column":49}},"14":{"start":{"line":15,"column":0},"end":{"line":15,"column":23}},"15":{"start":{"line":16,"column":0},"end":{"line":16,"column":12}},"16":{"start":{"line":17,"column":0},"end":{"line":17,"column":31}},"17":{"start":{"line":18,"column":0},"end":{"line":18,"column":19}},"18":{"start":{"line":19,"column":0},"end":{"line":19,"column":21}},"19":{"start":{"line":20,"column":0},"end":{"line":20,"column":29}},"20":{"start":{"line":21,"column":0},"end":{"line":21,"column":22}},"21":{"start":{"line":22,"column":0},"end":{"line":22,"column":23}},"22":{"start":{"line":23,"column":0},"end":{"line":23,"column":55}},"23":{"start":{"line":24,"column":0},"end":{"line":24,"column":26}},"24":{"start":{"line":25,"column":0},"end":{"line":25,"column":29}},"25":{"start":{"line":26,"column":0},"end":{"line":26,"column":26}},"26":{"start":{"line":27,"column":0},"end":{"line":27,"column":9}},"27":{"start":{"line":28,"column":0},"end":{"line":28,"column":0}},"28":{"start":{"line":29,"column":0},"end":{"line":29,"column":12}},"29":{"start":{"line":30,"column":0},"end":{"line":30,"column":30}},"30":{"start":{"line":31,"column":0},"end":{"line":31,"column":9}},"31":{"start":{"line":32,"column":0},"end":{"line":32,"column":5}},"32":{"start":{"line":33,"column":0},"end":{"line":33,"column":36}},"33":{"start":{"line":34,"column":0},"end":{"line":34,"column":1}},"34":{"start":{"line":35,"column":0},"end":{"line":35,"column":0}},"35":{"start":{"line":36,"column":0},"end":{"line":36,"column":39}},"36":{"start":{"line":37,"column":0},"end":{"line":37,"column":20}},"37":{"start":{"line":38,"column":0},"end":{"line":38,"column":66}},"38":{"start":{"line":39,"column":0},"end":{"line":39,"column":29}},"39":{"start":{"line":40,"column":0},"end":{"line":40,"column":27}},"40":{"start":{"line":41,"column":0},"end":{"line":41,"column":50}},"41":{"start":{"line":42,"column":0},"end":{"line":42,"column":35}},"42":{"start":{"line":43,"column":0},"end":{"line":43,"column":41}},"43":{"start":{"line":44,"column":0},"end":{"line":44,"column":70}},"44":{"start":{"line":45,"column":0},"end":{"line":45,"column":6}},"45":{"start":{"line":46,"column":0},"end":{"line":46,"column":36}},"46":{"start":{"line":47,"column":0},"end":{"line":47,"column":0}},"47":{"start":{"line":48,"column":0},"end":{"line":48,"column":88}},"48":{"start":{"line":49,"column":0},"end":{"line":49,"column":27}},"49":{"start":{"line":50,"column":0},"end":{"line":50,"column":51}},"50":{"start":{"line":51,"column":0},"end":{"line":51,"column":35}},"51":{"start":{"line":52,"column":0},"end":{"line":52,"column":41}},"52":{"start":{"line":53,"column":0},"end":{"line":53,"column":41}},"53":{"start":{"line":54,"column":0},"end":{"line":54,"column":9}},"54":{"start":{"line":55,"column":0},"end":{"line":55,"column":6}},"55":{"start":{"line":56,"column":0},"end":{"line":56,"column":35}},"56":{"start":{"line":57,"column":0},"end":{"line":57,"column":88}},"57":{"start":{"line":58,"column":0},"end":{"line":58,"column":27}},"58":{"start":{"line":59,"column":0},"end":{"line":59,"column":50}},"59":{"start":{"line":60,"column":0},"end":{"line":60,"column":35}},"60":{"start":{"line":61,"column":0},"end":{"line":61,"column":41}},"61":{"start":{"line":62,"column":0},"end":{"line":62,"column":9}},"62":{"start":{"line":63,"column":0},"end":{"line":63,"column":6}},"63":{"start":{"line":64,"column":0},"end":{"line":64,"column":1}},"64":{"start":{"line":65,"column":0},"end":{"line":65,"column":0}},"65":{"start":{"line":66,"column":0},"end":{"line":66,"column":0}},"66":{"start":{"line":67,"column":0},"end":{"line":67,"column":42}},"67":{"start":{"line":68,"column":0},"end":{"line":68,"column":23}},"68":{"start":{"line":69,"column":0},"end":{"line":69,"column":18}},"69":{"start":{"line":70,"column":0},"end":{"line":70,"column":20}},"70":{"start":{"line":71,"column":0},"end":{"line":71,"column":20}},"71":{"start":{"line":72,"column":0},"end":{"line":72,"column":4}},"72":{"start":{"line":73,"column":0},"end":{"line":73,"column":0}},"73":{"start":{"line":74,"column":0},"end":{"line":74,"column":38}},"74":{"start":{"line":75,"column":0},"end":{"line":75,"column":37}},"75":{"start":{"line":76,"column":0},"end":{"line":76,"column":0}},"76":{"start":{"line":77,"column":0},"end":{"line":77,"column":0}},"77":{"start":{"line":78,"column":0},"end":{"line":78,"column":32}},"78":{"start":{"line":79,"column":0},"end":{"line":79,"column":32}},"79":{"start":{"line":80,"column":0},"end":{"line":80,"column":28}},"80":{"start":{"line":81,"column":0},"end":{"line":81,"column":25}},"81":{"start":{"line":82,"column":0},"end":{"line":82,"column":1}},"82":{"start":{"line":83,"column":0},"end":{"line":83,"column":0}},"83":{"start":{"line":84,"column":0},"end":{"line":84,"column":0}},"84":{"start":{"line":85,"column":0},"end":{"line":85,"column":32}},"85":{"start":{"line":86,"column":0},"end":{"line":86,"column":0}},"86":{"start":{"line":87,"column":0},"end":{"line":87,"column":35}},"87":{"start":{"line":88,"column":0},"end":{"line":88,"column":0}},"88":{"start":{"line":89,"column":0},"end":{"line":89,"column":13}},"89":{"start":{"line":90,"column":0},"end":{"line":90,"column":4}},"90":{"start":{"line":91,"column":0},"end":{"line":91,"column":12}},"91":{"start":{"line":92,"column":0},"end":{"line":92,"column":19}},"92":{"start":{"line":93,"column":0},"end":{"line":93,"column":23}},"93":{"start":{"line":94,"column":0},"end":{"line":94,"column":31}},"94":{"start":{"line":95,"column":0},"end":{"line":95,"column":5}},"95":{"start":{"line":96,"column":0},"end":{"line":96,"column":0}},"96":{"start":{"line":97,"column":0},"end":{"line":97,"column":26}},"97":{"start":{"line":98,"column":0},"end":{"line":98,"column":30}},"98":{"start":{"line":99,"column":0},"end":{"line":99,"column":61}},"99":{"start":{"line":100,"column":0},"end":{"line":100,"column":40}},"100":{"start":{"line":101,"column":0},"end":{"line":101,"column":5}},"101":{"start":{"line":102,"column":0},"end":{"line":102,"column":4}},"102":{"start":{"line":103,"column":0},"end":{"line":103,"column":35}},"103":{"start":{"line":104,"column":0},"end":{"line":104,"column":33}},"104":{"start":{"line":105,"column":0},"end":{"line":105,"column":19}},"105":{"start":{"line":106,"column":0},"end":{"line":106,"column":0}},"106":{"start":{"line":107,"column":0},"end":{"line":107,"column":22}},"107":{"start":{"line":108,"column":0},"end":{"line":108,"column":0}},"108":{"start":{"line":109,"column":0},"end":{"line":109,"column":47}},"109":{"start":{"line":110,"column":0},"end":{"line":110,"column":24}},"110":{"start":{"line":111,"column":0},"end":{"line":111,"column":43}},"111":{"start":{"line":112,"column":0},"end":{"line":112,"column":33}},"112":{"start":{"line":113,"column":0},"end":{"line":113,"column":47}},"113":{"start":{"line":114,"column":0},"end":{"line":114,"column":50}},"114":{"start":{"line":115,"column":0},"end":{"line":115,"column":12}},"115":{"start":{"line":116,"column":0},"end":{"line":116,"column":5}},"116":{"start":{"line":117,"column":0},"end":{"line":117,"column":0}},"117":{"start":{"line":118,"column":0},"end":{"line":118,"column":39}},"118":{"start":{"line":119,"column":0},"end":{"line":119,"column":61}},"119":{"start":{"line":120,"column":0},"end":{"line":120,"column":14}},"120":{"start":{"line":121,"column":0},"end":{"line":121,"column":62}},"121":{"start":{"line":122,"column":0},"end":{"line":122,"column":77}},"122":{"start":{"line":123,"column":0},"end":{"line":123,"column":59}},"123":{"start":{"line":124,"column":0},"end":{"line":124,"column":9}},"124":{"start":{"line":125,"column":0},"end":{"line":125,"column":5}},"125":{"start":{"line":126,"column":0},"end":{"line":126,"column":0}},"126":{"start":{"line":127,"column":0},"end":{"line":127,"column":0}},"127":{"start":{"line":128,"column":0},"end":{"line":128,"column":26}},"128":{"start":{"line":129,"column":0},"end":{"line":129,"column":65}},"129":{"start":{"line":130,"column":0},"end":{"line":130,"column":14}},"130":{"start":{"line":131,"column":0},"end":{"line":131,"column":31}},"131":{"start":{"line":132,"column":0},"end":{"line":132,"column":38}},"132":{"start":{"line":133,"column":0},"end":{"line":133,"column":70}},"133":{"start":{"line":134,"column":0},"end":{"line":134,"column":36}},"134":{"start":{"line":135,"column":0},"end":{"line":135,"column":13}},"135":{"start":{"line":136,"column":0},"end":{"line":136,"column":9}},"136":{"start":{"line":137,"column":0},"end":{"line":137,"column":5}},"137":{"start":{"line":138,"column":0},"end":{"line":138,"column":0}},"138":{"start":{"line":139,"column":0},"end":{"line":139,"column":25}},"139":{"start":{"line":140,"column":0},"end":{"line":140,"column":27}},"140":{"start":{"line":141,"column":0},"end":{"line":141,"column":32}},"141":{"start":{"line":142,"column":0},"end":{"line":142,"column":79}},"142":{"start":{"line":143,"column":0},"end":{"line":143,"column":9}},"143":{"start":{"line":144,"column":0},"end":{"line":144,"column":5}},"144":{"start":{"line":145,"column":0},"end":{"line":145,"column":0}},"145":{"start":{"line":146,"column":0},"end":{"line":146,"column":20}},"146":{"start":{"line":147,"column":0},"end":{"line":147,"column":28}},"147":{"start":{"line":148,"column":0},"end":{"line":148,"column":34}},"148":{"start":{"line":149,"column":0},"end":{"line":149,"column":5}},"149":{"start":{"line":150,"column":0},"end":{"line":150,"column":0}},"150":{"start":{"line":151,"column":0},"end":{"line":151,"column":18}},"151":{"start":{"line":152,"column":0},"end":{"line":152,"column":32}},"152":{"start":{"line":153,"column":0},"end":{"line":153,"column":5}},"153":{"start":{"line":154,"column":0},"end":{"line":154,"column":0}},"154":{"start":{"line":155,"column":0},"end":{"line":155,"column":52}},"155":{"start":{"line":156,"column":0},"end":{"line":156,"column":36}},"156":{"start":{"line":157,"column":0},"end":{"line":157,"column":5}},"157":{"start":{"line":158,"column":0},"end":{"line":158,"column":0}},"158":{"start":{"line":159,"column":0},"end":{"line":159,"column":0}},"159":{"start":{"line":160,"column":0},"end":{"line":160,"column":20}},"160":{"start":{"line":161,"column":0},"end":{"line":161,"column":40}},"161":{"start":{"line":162,"column":0},"end":{"line":162,"column":0}},"162":{"start":{"line":163,"column":0},"end":{"line":163,"column":31}},"163":{"start":{"line":164,"column":0},"end":{"line":164,"column":23}},"164":{"start":{"line":165,"column":0},"end":{"line":165,"column":9}},"165":{"start":{"line":166,"column":0},"end":{"line":166,"column":5}},"166":{"start":{"line":167,"column":0},"end":{"line":167,"column":0}},"167":{"start":{"line":168,"column":0},"end":{"line":168,"column":24}},"168":{"start":{"line":169,"column":0},"end":{"line":169,"column":39}},"169":{"start":{"line":170,"column":0},"end":{"line":170,"column":0}},"170":{"start":{"line":171,"column":0},"end":{"line":171,"column":54}},"171":{"start":{"line":172,"column":0},"end":{"line":172,"column":30}},"172":{"start":{"line":173,"column":0},"end":{"line":173,"column":30}},"173":{"start":{"line":174,"column":0},"end":{"line":174,"column":9}},"174":{"start":{"line":175,"column":0},"end":{"line":175,"column":0}},"175":{"start":{"line":176,"column":0},"end":{"line":176,"column":22}},"176":{"start":{"line":177,"column":0},"end":{"line":177,"column":38}},"177":{"start":{"line":178,"column":0},"end":{"line":178,"column":18}},"178":{"start":{"line":179,"column":0},"end":{"line":179,"column":65}},"179":{"start":{"line":180,"column":0},"end":{"line":180,"column":62}},"180":{"start":{"line":181,"column":0},"end":{"line":181,"column":50}},"181":{"start":{"line":182,"column":0},"end":{"line":182,"column":13}},"182":{"start":{"line":183,"column":0},"end":{"line":183,"column":9}},"183":{"start":{"line":184,"column":0},"end":{"line":184,"column":5}},"184":{"start":{"line":185,"column":0},"end":{"line":185,"column":0}},"185":{"start":{"line":186,"column":0},"end":{"line":186,"column":18}},"186":{"start":{"line":187,"column":0},"end":{"line":187,"column":56}},"187":{"start":{"line":188,"column":0},"end":{"line":188,"column":25}},"188":{"start":{"line":189,"column":0},"end":{"line":189,"column":18}},"189":{"start":{"line":190,"column":0},"end":{"line":190,"column":5}},"190":{"start":{"line":191,"column":0},"end":{"line":191,"column":1}}},"s":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":1,"35":1,"36":1,"37":1,"38":1,"39":16,"40":0,"41":0,"42":0,"43":16,"44":1,"45":1,"46":8,"47":8,"48":8,"49":0,"50":0,"51":0,"52":0,"53":0,"54":1,"55":1,"56":1,"57":1,"58":0,"59":0,"60":0,"61":0,"62":1,"63":1,"64":1,"65":1,"66":1,"67":1,"68":1,"69":1,"70":1,"71":1,"72":1,"73":1,"74":1,"75":1,"76":1,"77":1,"78":1,"79":1,"80":1,"81":1,"82":1,"83":1,"84":1,"85":1,"86":1,"87":1,"88":1,"89":1,"90":1,"91":1,"92":1,"93":8,"94":8,"95":1,"96":1,"97":8,"98":8,"99":8,"100":8,"101":1,"102":1,"103":1,"104":1,"105":1,"106":1,"107":1,"108":1,"109":1,"110":1,"111":1,"112":1,"113":1,"114":1,"115":1,"116":1,"117":1,"118":1,"119":1,"120":1,"121":1,"122":1,"123":1,"124":1,"125":1,"126":1,"127":1,"128":1,"129":1,"130":1,"131":1,"132":1,"133":1,"134":1,"135":1,"136":1,"137":1,"138":1,"139":1,"140":1,"141":1,"142":1,"143":1,"144":1,"145":1,"146":1,"147":1,"148":1,"149":1,"150":1,"151":1,"152":1,"153":1,"154":1,"155":1,"156":1,"157":1,"158":1,"159":1,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":1,"167":1,"168":8,"169":8,"170":8,"171":0,"172":0,"173":0,"174":8,"175":8,"176":8,"177":8,"178":8,"179":8,"180":8,"181":8,"182":8,"183":8,"184":1,"185":1,"186":8,"187":8,"188":8,"189":8,"190":1},"branchMap":{"0":{"type":"branch","line":9,"loc":{"start":{"line":9,"column":13},"end":{"line":34,"column":1}},"locations":[{"start":{"line":9,"column":13},"end":{"line":34,"column":1}}]},"1":{"type":"branch","line":38,"loc":{"start":{"line":38,"column":34},"end":{"line":38,"column":65}},"locations":[{"start":{"line":38,"column":34},"end":{"line":38,"column":65}}]},"2":{"type":"branch","line":39,"loc":{"start":{"line":39,"column":9},"end":{"line":45,"column":5}},"locations":[{"start":{"line":39,"column":9},"end":{"line":45,"column":5}}]},"3":{"type":"branch","line":40,"loc":{"start":{"line":40,"column":26},"end":{"line":44,"column":15}},"locations":[{"start":{"line":40,"column":26},"end":{"line":44,"column":15}}]},"4":{"type":"branch","line":44,"loc":{"start":{"line":44,"column":50},"end":{"line":44,"column":70}},"locations":[{"start":{"line":44,"column":50},"end":{"line":44,"column":70}}]},"5":{"type":"branch","line":46,"loc":{"start":{"line":46,"column":16},"end":{"line":55,"column":5}},"locations":[{"start":{"line":46,"column":16},"end":{"line":55,"column":5}}]},"6":{"type":"branch","line":48,"loc":{"start":{"line":48,"column":43},"end":{"line":48,"column":88}},"locations":[{"start":{"line":48,"column":43},"end":{"line":48,"column":88}}]},"7":{"type":"branch","line":49,"loc":{"start":{"line":49,"column":26},"end":{"line":54,"column":9}},"locations":[{"start":{"line":49,"column":26},"end":{"line":54,"column":9}}]},"8":{"type":"branch","line":56,"loc":{"start":{"line":56,"column":15},"end":{"line":63,"column":5}},"locations":[{"start":{"line":56,"column":15},"end":{"line":63,"column":5}}]},"9":{"type":"branch","line":57,"loc":{"start":{"line":57,"column":43},"end":{"line":57,"column":88}},"locations":[{"start":{"line":57,"column":43},"end":{"line":57,"column":88}}]},"10":{"type":"branch","line":58,"loc":{"start":{"line":58,"column":26},"end":{"line":62,"column":9}},"locations":[{"start":{"line":58,"column":26},"end":{"line":62,"column":9}}]},"11":{"type":"branch","line":93,"loc":{"start":{"line":93,"column":4},"end":{"line":95,"column":5}},"locations":[{"start":{"line":93,"column":4},"end":{"line":95,"column":5}}]},"12":{"type":"branch","line":97,"loc":{"start":{"line":97,"column":4},"end":{"line":101,"column":5}},"locations":[{"start":{"line":97,"column":4},"end":{"line":101,"column":5}}]},"13":{"type":"branch","line":100,"loc":{"start":{"line":100,"column":29},"end":{"line":100,"column":40}},"locations":[{"start":{"line":100,"column":29},"end":{"line":100,"column":40}}]},"14":{"type":"branch","line":109,"loc":{"start":{"line":109,"column":4},"end":{"line":116,"column":5}},"locations":[{"start":{"line":109,"column":4},"end":{"line":116,"column":5}}]},"15":{"type":"branch","line":128,"loc":{"start":{"line":128,"column":12},"end":{"line":137,"column":5}},"locations":[{"start":{"line":128,"column":12},"end":{"line":137,"column":5}}]},"16":{"type":"branch","line":129,"loc":{"start":{"line":129,"column":26},"end":{"line":129,"column":47}},"locations":[{"start":{"line":129,"column":26},"end":{"line":129,"column":47}}]},"17":{"type":"branch","line":139,"loc":{"start":{"line":139,"column":11},"end":{"line":144,"column":5}},"locations":[{"start":{"line":139,"column":11},"end":{"line":144,"column":5}}]},"18":{"type":"branch","line":168,"loc":{"start":{"line":168,"column":10},"end":{"line":184,"column":5}},"locations":[{"start":{"line":168,"column":10},"end":{"line":184,"column":5}}]},"19":{"type":"branch","line":169,"loc":{"start":{"line":169,"column":27},"end":{"line":169,"column":39}},"locations":[{"start":{"line":169,"column":27},"end":{"line":169,"column":39}}]},"20":{"type":"branch","line":171,"loc":{"start":{"line":171,"column":43},"end":{"line":174,"column":9}},"locations":[{"start":{"line":171,"column":43},"end":{"line":174,"column":9}}]},"21":{"type":"branch","line":177,"loc":{"start":{"line":177,"column":32},"end":{"line":177,"column":38}},"locations":[{"start":{"line":177,"column":32},"end":{"line":177,"column":38}}]},"22":{"type":"branch","line":179,"loc":{"start":{"line":179,"column":36},"end":{"line":179,"column":65}},"locations":[{"start":{"line":179,"column":36},"end":{"line":179,"column":65}}]},"23":{"type":"branch","line":186,"loc":{"start":{"line":186,"column":11},"end":{"line":190,"column":5}},"locations":[{"start":{"line":186,"column":11},"end":{"line":190,"column":5}}]},"24":{"type":"branch","line":118,"loc":{"start":{"line":118,"column":4},"end":{"line":125,"column":5}},"locations":[{"start":{"line":118,"column":4},"end":{"line":125,"column":5}}]},"25":{"type":"branch","line":119,"loc":{"start":{"line":119,"column":35},"end":{"line":119,"column":61}},"locations":[{"start":{"line":119,"column":35},"end":{"line":119,"column":61}}]},"26":{"type":"branch","line":146,"loc":{"start":{"line":146,"column":4},"end":{"line":149,"column":5}},"locations":[{"start":{"line":146,"column":4},"end":{"line":149,"column":5}}]},"27":{"type":"branch","line":151,"loc":{"start":{"line":151,"column":4},"end":{"line":153,"column":5}},"locations":[{"start":{"line":151,"column":4},"end":{"line":153,"column":5}}]},"28":{"type":"branch","line":155,"loc":{"start":{"line":155,"column":4},"end":{"line":157,"column":5}},"locations":[{"start":{"line":155,"column":4},"end":{"line":157,"column":5}}]}},"b":{"0":[0],"1":[0],"2":[16],"3":[0],"4":[0],"5":[8],"6":[0],"7":[0],"8":[1],"9":[0],"10":[0],"11":[8],"12":[8],"13":[0],"14":[1],"15":[1],"16":[0],"17":[1],"18":[8],"19":[0],"20":[0],"21":[0],"22":[0],"23":[8],"24":[1],"25":[0],"26":[1],"27":[1],"28":[1]},"fnMap":{"0":{"name":"add","decl":{"start":{"line":39,"column":9},"end":{"line":45,"column":5}},"loc":{"start":{"line":39,"column":9},"end":{"line":45,"column":5}},"line":39},"1":{"name":"addCommand","decl":{"start":{"line":46,"column":16},"end":{"line":55,"column":5}},"loc":{"start":{"line":46,"column":16},"end":{"line":55,"column":5}},"line":46},"2":{"name":"addHeader","decl":{"start":{"line":56,"column":15},"end":{"line":63,"column":5}},"loc":{"start":{"line":56,"column":15},"end":{"line":63,"column":5}},"line":56},"3":{"name":"get iterations","decl":{"start":{"line":93,"column":4},"end":{"line":95,"column":5}},"loc":{"start":{"line":93,"column":4},"end":{"line":95,"column":5}},"line":93},"4":{"name":"set iterations","decl":{"start":{"line":97,"column":4},"end":{"line":101,"column":5}},"loc":{"start":{"line":97,"column":4},"end":{"line":101,"column":5}},"line":97},"5":{"name":"OperationsManager","decl":{"start":{"line":109,"column":4},"end":{"line":116,"column":5}},"loc":{"start":{"line":109,"column":4},"end":{"line":116,"column":5}},"line":109},"6":{"name":"OperationsManager.start","decl":{"start":{"line":128,"column":12},"end":{"line":137,"column":5}},"loc":{"start":{"line":128,"column":12},"end":{"line":137,"column":5}},"line":128},"7":{"name":"OperationsManager.stop","decl":{"start":{"line":139,"column":11},"end":{"line":144,"column":5}},"loc":{"start":{"line":139,"column":11},"end":{"line":144,"column":5}},"line":139},"8":{"name":"OperationsManager.runAll","decl":{"start":{"line":160,"column":13},"end":{"line":166,"column":5}},"loc":{"start":{"line":160,"column":13},"end":{"line":166,"column":5}},"line":160},"9":{"name":"OperationsManager.run","decl":{"start":{"line":168,"column":10},"end":{"line":184,"column":5}},"loc":{"start":{"line":168,"column":10},"end":{"line":184,"column":5}},"line":168},"10":{"name":"OperationsManager.next","decl":{"start":{"line":186,"column":11},"end":{"line":190,"column":5}},"loc":{"start":{"line":186,"column":11},"end":{"line":190,"column":5}},"line":186},"11":{"name":"set","decl":{"start":{"line":118,"column":4},"end":{"line":125,"column":5}},"loc":{"start":{"line":118,"column":4},"end":{"line":125,"column":5}},"line":118},"12":{"name":"setStart","decl":{"start":{"line":146,"column":4},"end":{"line":149,"column":5}},"loc":{"start":{"line":146,"column":4},"end":{"line":149,"column":5}},"line":146},"13":{"name":"setStop","decl":{"start":{"line":151,"column":4},"end":{"line":153,"column":5}},"loc":{"start":{"line":151,"column":4},"end":{"line":153,"column":5}},"line":151},"14":{"name":"setOperations","decl":{"start":{"line":155,"column":4},"end":{"line":157,"column":5}},"loc":{"start":{"line":155,"column":4},"end":{"line":157,"column":5}},"line":155}},"f":{"0":16,"1":8,"2":1,"3":8,"4":8,"5":1,"6":1,"7":1,"8":0,"9":8,"10":8,"11":1,"12":1,"13":1,"14":1}} +} diff --git a/coverage/lcov-report/base.css b/coverage/lcov-report/base.css new file mode 100644 index 00000000..f418035b --- /dev/null +++ b/coverage/lcov-report/base.css @@ -0,0 +1,224 @@ +body, html { + margin:0; padding: 0; + height: 100%; +} +body { + font-family: Helvetica Neue, Helvetica, Arial; + font-size: 14px; + color:#333; +} +.small { font-size: 12px; } +*, *:after, *:before { + -webkit-box-sizing:border-box; + -moz-box-sizing:border-box; + box-sizing:border-box; + } +h1 { font-size: 20px; margin: 0;} +h2 { font-size: 14px; } +pre { + font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace; + margin: 0; + padding: 0; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} +a { color:#0074D9; text-decoration:none; } +a:hover { text-decoration:underline; } +.strong { font-weight: bold; } +.space-top1 { padding: 10px 0 0 0; } +.pad2y { padding: 20px 0; } +.pad1y { padding: 10px 0; } +.pad2x { padding: 0 20px; } +.pad2 { padding: 20px; } +.pad1 { padding: 10px; } +.space-left2 { padding-left:55px; } +.space-right2 { padding-right:20px; } +.center { text-align:center; } +.clearfix { display:block; } +.clearfix:after { + content:''; + display:block; + height:0; + clear:both; + visibility:hidden; + } +.fl { float: left; } +@media only screen and (max-width:640px) { + .col3 { width:100%; max-width:100%; } + .hide-mobile { display:none!important; } +} + +.quiet { + color: #7f7f7f; + color: rgba(0,0,0,0.5); +} +.quiet a { opacity: 0.7; } + +.fraction { + font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 10px; + color: #555; + background: #E8E8E8; + padding: 4px 5px; + border-radius: 3px; + vertical-align: middle; +} + +div.path a:link, div.path a:visited { color: #333; } +table.coverage { + border-collapse: collapse; + margin: 10px 0 0 0; + padding: 0; +} + +table.coverage td { + margin: 0; + padding: 0; + vertical-align: top; +} +table.coverage td.line-count { + text-align: right; + padding: 0 5px 0 20px; +} +table.coverage td.line-coverage { + text-align: right; + padding-right: 10px; + min-width:20px; +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 100%; +} +.missing-if-branch { + display: inline-block; + margin-right: 5px; + border-radius: 3px; + position: relative; + padding: 0 4px; + background: #333; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} +.coverage-summary { + border-collapse: collapse; + width: 100%; +} +.coverage-summary tr { border-bottom: 1px solid #bbb; } +.keyline-all { border: 1px solid #ddd; } +.coverage-summary td, .coverage-summary th { padding: 10px; } +.coverage-summary tbody { border: 1px solid #bbb; } +.coverage-summary td { border-right: 1px solid #bbb; } +.coverage-summary td:last-child { border-right: none; } +.coverage-summary th { + text-align: left; + font-weight: normal; + white-space: nowrap; +} +.coverage-summary th.file { border-right: none !important; } +.coverage-summary th.pct { } +.coverage-summary th.pic, +.coverage-summary th.abs, +.coverage-summary td.pct, +.coverage-summary td.abs { text-align: right; } +.coverage-summary td.file { white-space: nowrap; } +.coverage-summary td.pic { min-width: 120px !important; } +.coverage-summary tfoot td { } + +.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} +.status-line { height: 10px; } +/* yellow */ +.cbranch-no { background: yellow !important; color: #111; } +/* dark red */ +.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 } +.low .chart { border:1px solid #C21F39 } +.highlighted, +.highlighted .cstat-no, .highlighted .fstat-no, .highlighted .cbranch-no{ + background: #C21F39 !important; +} +/* medium red */ +.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE } +/* light red */ +.low, .cline-no { background:#FCE1E5 } +/* light green */ +.high, .cline-yes { background:rgb(230,245,208) } +/* medium green */ +.cstat-yes { background:rgb(161,215,106) } +/* dark green */ +.status-line.high, .high .cover-fill { background:rgb(77,146,33) } +.high .chart { border:1px solid rgb(77,146,33) } +/* dark yellow (gold) */ +.status-line.medium, .medium .cover-fill { background: #f9cd0b; } +.medium .chart { border:1px solid #f9cd0b; } +/* light yellow */ +.medium { background: #fff4c2; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +span.cline-neutral { background: #eaeaea; } + +.coverage-summary td.empty { + opacity: .5; + padding-top: 4px; + padding-bottom: 4px; + line-height: 1; + color: #888; +} + +.cover-fill, .cover-empty { + display:inline-block; + height: 12px; +} +.chart { + line-height: 0; +} +.cover-empty { + background: white; +} +.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } + +.wrapper { + min-height: 100%; + height: auto !important; + height: 100%; + margin: 0 auto -48px; +} +.footer, .push { + height: 48px; +} diff --git a/coverage/lcov-report/block-navigation.js b/coverage/lcov-report/block-navigation.js new file mode 100644 index 00000000..cc121302 --- /dev/null +++ b/coverage/lcov-report/block-navigation.js @@ -0,0 +1,87 @@ +/* eslint-disable */ +var jumpToCode = (function init() { + // Classes of code we would like to highlight in the file view + var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no']; + + // Elements to highlight in the file listing view + var fileListingElements = ['td.pct.low']; + + // We don't want to select elements that are direct descendants of another match + var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > ` + + // Selecter that finds elements on the page to which we can jump + var selector = + fileListingElements.join(', ') + + ', ' + + notSelector + + missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b` + + // The NodeList of matching elements + var missingCoverageElements = document.querySelectorAll(selector); + + var currentIndex; + + function toggleClass(index) { + missingCoverageElements + .item(currentIndex) + .classList.remove('highlighted'); + missingCoverageElements.item(index).classList.add('highlighted'); + } + + function makeCurrent(index) { + toggleClass(index); + currentIndex = index; + missingCoverageElements.item(index).scrollIntoView({ + behavior: 'smooth', + block: 'center', + inline: 'center' + }); + } + + function goToPrevious() { + var nextIndex = 0; + if (typeof currentIndex !== 'number' || currentIndex === 0) { + nextIndex = missingCoverageElements.length - 1; + } else if (missingCoverageElements.length > 1) { + nextIndex = currentIndex - 1; + } + + makeCurrent(nextIndex); + } + + function goToNext() { + var nextIndex = 0; + + if ( + typeof currentIndex === 'number' && + currentIndex < missingCoverageElements.length - 1 + ) { + nextIndex = currentIndex + 1; + } + + makeCurrent(nextIndex); + } + + return function jump(event) { + if ( + document.getElementById('fileSearch') === document.activeElement && + document.activeElement != null + ) { + // if we're currently focused on the search input, we don't want to navigate + return; + } + + switch (event.which) { + case 78: // n + case 74: // j + goToNext(); + break; + case 66: // b + case 75: // k + case 80: // p + goToPrevious(); + break; + } + }; +})(); +window.addEventListener('keydown', jumpToCode); diff --git a/coverage/lcov-report/favicon.png b/coverage/lcov-report/favicon.png new file mode 100644 index 00000000..c1525b81 Binary files /dev/null and b/coverage/lcov-report/favicon.png differ diff --git a/coverage/lcov-report/index.html b/coverage/lcov-report/index.html new file mode 100644 index 00000000..13f5f198 --- /dev/null +++ b/coverage/lcov-report/index.html @@ -0,0 +1,326 @@ + + + + + + Code coverage report for All files + + + + + + + + + +
+
+

All files

+
+ +
+ 67.85% + Statements + 1461/2153 +
+ + +
+ 61.7% + Branches + 174/282 +
+ + +
+ 68.96% + Functions + 100/145 +
+ + +
+ 67.85% + Lines + 1461/2153 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
examples/graph +
+
84.64%226/26791.3%21/2360.71%17/2884.64%226/267
examples/graph/nodes +
+
100%34/34100%5/5100%3/3100%34/34
src/core +
+
66.45%410/61769.01%49/7167.56%25/3766.45%410/617
src/core/loaders +
+
100%17/17100%0/0100%0/0100%17/17
src/core/loaders/graphscript-children-loader +
+
86.76%59/6845%9/2066.66%2/386.76%59/68
src/core/loaders/graphscript-default-loader +
+
33.33%6/1833.33%1/350%1/233.33%6/18
src/core/loaders/graphscript-listeners-loader +
+
76.52%176/23059.57%28/4780%12/1576.52%176/230
src/core/loaders/graphscript-operator-loader +
+
78.66%59/7562.5%10/1683.33%5/678.66%59/75
src/core/loaders/graphscript-parent-loader +
+
65.71%23/3580%4/550%1/265.71%23/35
src/core/loaders/graphscript-props-loader +
+
36%18/5066.66%2/350%2/436%18/50
src/core/loaders/graphscript-root-loader +
+
92.53%62/6750%7/14100%5/592.53%62/67
src/core/parsers +
+
73.33%33/4557.14%4/750%2/473.33%33/45
src/loaders +
+
52.99%168/31751.28%20/3955%11/2052.99%168/317
src/loaders/html +
+
20.49%25/122100%0/00%0/120.49%25/122
tests/utils +
+
75.91%145/19148.27%14/2993.33%14/1575.91%145/191
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/coverage/lcov-report/prettify.css b/coverage/lcov-report/prettify.css new file mode 100644 index 00000000..b317a7cd --- /dev/null +++ b/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/coverage/lcov-report/prettify.js b/coverage/lcov-report/prettify.js new file mode 100644 index 00000000..b3225238 --- /dev/null +++ b/coverage/lcov-report/prettify.js @@ -0,0 +1,2 @@ +/* eslint-disable */ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/coverage/lcov-report/sort-arrow-sprite.png b/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 00000000..6ed68316 Binary files /dev/null and b/coverage/lcov-report/sort-arrow-sprite.png differ diff --git a/coverage/lcov-report/sorter.js b/coverage/lcov-report/sorter.js new file mode 100644 index 00000000..2bb296a8 --- /dev/null +++ b/coverage/lcov-report/sorter.js @@ -0,0 +1,196 @@ +/* eslint-disable */ +var addSorting = (function() { + 'use strict'; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { + return document.querySelector('.coverage-summary'); + } + // returns the thead element of the summary table + function getTableHeader() { + return getTable().querySelector('thead tr'); + } + // returns the tbody element of the summary table + function getTableBody() { + return getTable().querySelector('tbody'); + } + // returns the th element for nth column + function getNthColumn(n) { + return getTableHeader().querySelectorAll('th')[n]; + } + + function onFilterInput() { + const searchValue = document.getElementById('fileSearch').value; + const rows = document.getElementsByTagName('tbody')[0].children; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if ( + row.textContent + .toLowerCase() + .includes(searchValue.toLowerCase()) + ) { + row.style.display = ''; + } else { + row.style.display = 'none'; + } + } + } + + // loads the search box + function addSearchBox() { + var template = document.getElementById('filterTemplate'); + var templateClone = template.content.cloneNode(true); + templateClone.getElementById('fileSearch').oninput = onFilterInput; + template.parentElement.appendChild(templateClone); + } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = + colNode.innerHTML + ''; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function(a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function(a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc + ? ' sorted-desc' + : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function() { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i = 0; i < cols.length; i += 1) { + if (cols[i].sortable) { + // add the click event handler on the th so users + // dont have to click on those tiny arrows + el = getNthColumn(i).querySelector('.sorter').parentElement; + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function() { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(); + addSearchBox(); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/coverage/lcov.info b/coverage/lcov.info new file mode 100644 index 00000000..10d2ea02 --- /dev/null +++ b/coverage/lcov.info @@ -0,0 +1,2896 @@ +TN: +SF:examples/graph/operations.ts +FN:22,start +FN:33,get +FN:62,stop +FN:69,function +FN:73,function +FN:80,function +FN:88,function +FN:96,function +FN:100,function +FN:108,function +FN:115,function +FN:122,function +FN:129,function +FN:137,function +FN:144,function +FN:152,function +FN:159,function +FN:166,function +FN:170,function +FNF:19 +FNH:11 +FNDA:1,start +FNDA:6,get +FNDA:1,stop +FNDA:1,function +FNDA:1,function +FNDA:1,function +FNDA:1,function +FNDA:1,function +FNDA:1,function +FNDA:1,function +FNDA:1,function +FNDA:0,function +FNDA:0,function +FNDA:0,function +FNDA:0,function +FNDA:0,function +FNDA:0,function +FNDA:0,function +FNDA:0,function +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,1 +DA:13,1 +DA:14,1 +DA:15,1 +DA:16,1 +DA:17,1 +DA:18,1 +DA:19,1 +DA:20,1 +DA:21,1 +DA:22,1 +DA:23,1 +DA:24,1 +DA:25,1 +DA:26,1 +DA:27,1 +DA:28,1 +DA:29,1 +DA:30,1 +DA:31,1 +DA:32,1 +DA:33,1 +DA:34,6 +DA:35,6 +DA:36,6 +DA:37,1 +DA:38,1 +DA:39,1 +DA:40,1 +DA:41,1 +DA:42,1 +DA:43,1 +DA:44,1 +DA:45,1 +DA:46,1 +DA:47,1 +DA:48,1 +DA:49,1 +DA:50,1 +DA:51,6 +DA:52,6 +DA:53,1 +DA:54,1 +DA:55,1 +DA:56,1 +DA:57,1 +DA:58,1 +DA:59,1 +DA:60,1 +DA:61,1 +DA:62,1 +DA:63,1 +DA:64,1 +DA:65,1 +DA:66,1 +DA:67,1 +DA:68,1 +DA:69,1 +DA:70,1 +DA:71,1 +DA:72,1 +DA:73,1 +DA:74,1 +DA:75,1 +DA:76,1 +DA:77,1 +DA:78,1 +DA:79,1 +DA:80,1 +DA:81,1 +DA:82,1 +DA:83,1 +DA:84,1 +DA:85,1 +DA:86,1 +DA:87,1 +DA:88,1 +DA:89,1 +DA:90,1 +DA:91,1 +DA:92,1 +DA:93,1 +DA:94,1 +DA:95,1 +DA:96,1 +DA:97,1 +DA:98,1 +DA:99,1 +DA:100,1 +DA:101,1 +DA:102,1 +DA:103,1 +DA:104,1 +DA:105,1 +DA:106,1 +DA:107,1 +DA:108,1 +DA:109,1 +DA:110,1 +DA:111,1 +DA:112,1 +DA:113,1 +DA:114,1 +DA:115,1 +DA:116,1 +DA:117,1 +DA:118,1 +DA:119,1 +DA:120,1 +DA:121,1 +DA:122,1 +DA:123,0 +DA:124,0 +DA:125,0 +DA:126,1 +DA:127,1 +DA:128,1 +DA:129,1 +DA:130,0 +DA:131,0 +DA:132,0 +DA:133,0 +DA:134,1 +DA:135,1 +DA:136,1 +DA:137,1 +DA:138,0 +DA:139,0 +DA:140,0 +DA:141,1 +DA:142,1 +DA:143,1 +DA:144,1 +DA:145,0 +DA:146,0 +DA:147,0 +DA:148,0 +DA:149,1 +DA:150,1 +DA:151,1 +DA:152,1 +DA:153,0 +DA:154,0 +DA:155,0 +DA:156,1 +DA:157,1 +DA:158,1 +DA:159,1 +DA:160,0 +DA:161,0 +DA:162,0 +DA:163,1 +DA:164,1 +DA:165,1 +DA:166,1 +DA:167,1 +DA:168,1 +DA:169,1 +DA:170,1 +DA:171,0 +DA:172,0 +DA:173,0 +DA:174,0 +DA:175,0 +DA:176,0 +DA:177,0 +DA:178,1 +DA:179,1 +DA:180,1 +DA:181,1 +DA:182,1 +LF:182 +LH:155 +BRDA:22,0,0,1 +BRDA:28,1,0,0 +BRDA:33,2,0,6 +BRDA:35,3,0,5 +BRDA:35,4,0,1 +BRDA:50,5,0,6 +BRDA:62,6,0,1 +BRDA:69,7,0,1 +BRDA:73,8,0,1 +BRDA:80,9,0,1 +BRDA:88,10,0,1 +BRDA:96,11,0,1 +BRDA:100,12,0,1 +BRDA:108,13,0,1 +BRDA:115,14,0,1 +BRF:15 +BRH:14 +end_of_record +TN: +SF:examples/graph/tree.js +FN:5, +FN:5,__operator +FN:26,__operator +FN:33,nodeA.x +FN:38,nodeA.jump +FN:49,nodeD +FN:53,__operator +FN:72,__onconnected +FN:78,__ondisconnected +FNF:9 +FNH:6 +FNDA:1, +FNDA:1,__operator +FNDA:1,__operator +FNDA:2,nodeA.x +FNDA:4,nodeA.jump +FNDA:0,nodeD +FNDA:1,__operator +FNDA:0,__onconnected +FNDA:0,__ondisconnected +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,1 +DA:13,1 +DA:14,1 +DA:15,1 +DA:16,1 +DA:17,1 +DA:18,1 +DA:19,1 +DA:20,1 +DA:21,1 +DA:22,1 +DA:23,1 +DA:24,1 +DA:25,1 +DA:26,1 +DA:27,1 +DA:28,1 +DA:29,1 +DA:30,1 +DA:31,1 +DA:32,1 +DA:33,1 +DA:34,2 +DA:35,2 +DA:36,2 +DA:37,1 +DA:38,1 +DA:39,4 +DA:40,4 +DA:41,4 +DA:42,4 +DA:43,1 +DA:44,1 +DA:45,1 +DA:46,1 +DA:47,1 +DA:48,1 +DA:49,1 +DA:50,1 +DA:51,1 +DA:52,1 +DA:53,1 +DA:54,1 +DA:55,1 +DA:56,1 +DA:57,1 +DA:58,1 +DA:59,1 +DA:60,1 +DA:61,1 +DA:62,1 +DA:63,1 +DA:64,1 +DA:65,1 +DA:66,1 +DA:67,1 +DA:68,1 +DA:69,1 +DA:70,0 +DA:71,0 +DA:72,0 +DA:73,0 +DA:74,0 +DA:75,0 +DA:76,0 +DA:77,0 +DA:78,0 +DA:79,0 +DA:80,0 +DA:81,0 +DA:82,0 +DA:83,0 +DA:84,1 +DA:85,1 +LF:85 +LH:71 +BRDA:1,0,0,1 +BRDA:69,1,0,0 +BRDA:5,2,0,1 +BRDA:5,3,0,1 +BRDA:26,4,0,1 +BRDA:33,5,0,2 +BRDA:38,6,0,4 +BRDA:53,7,0,1 +BRF:8 +BRH:7 +end_of_record +TN: +SF:examples/graph/nodes/nodeA.js +FN:7,jump +FN:23,nodeB.nodeC +FN:28,nodeB.nodeC.z +FNF:3 +FNH:3 +FNDA:4,jump +FNDA:1,nodeB.nodeC +FNDA:2,nodeB.nodeC.z +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,4 +DA:9,4 +DA:10,4 +DA:11,4 +DA:12,4 +DA:13,4 +DA:14,4 +DA:15,1 +DA:16,1 +DA:17,1 +DA:18,1 +DA:19,1 +DA:20,1 +DA:21,1 +DA:22,1 +DA:23,1 +DA:24,1 +DA:25,1 +DA:26,1 +DA:27,1 +DA:28,1 +DA:29,2 +DA:30,2 +DA:31,2 +DA:32,1 +DA:33,1 +DA:34,1 +LF:34 +LH:34 +BRDA:1,0,0,1 +BRDA:7,1,0,4 +BRDA:12,2,0,2 +BRDA:23,3,0,1 +BRDA:28,4,0,2 +BRF:5 +BRH:5 +end_of_record +TN: +SF:src/core/EventHandler.ts +FN:9,EventHandler +FN:11,EventHandler.setState +FN:16,EventHandler.setValue +FN:20,EventHandler.triggerEvent +FN:23,EventHandler.subscribeEvent +FN:29,get +FN:32,set +FN:51,EventHandler.unsubscribeEvent +FN:78,EventHandler.subscribeEventOnce +FN:87,EventHandler.getEvent +FN:92,EventHandler.getSnapshot +FNF:11 +FNH:7 +FNDA:1,EventHandler +FNDA:0,EventHandler.setState +FNDA:2,EventHandler.setValue +FNDA:11,EventHandler.triggerEvent +FNDA:6,EventHandler.subscribeEvent +FNDA:5,get +FNDA:0,set +FNDA:2,EventHandler.unsubscribeEvent +FNDA:0,EventHandler.subscribeEventOnce +FNDA:6,EventHandler.getEvent +FNDA:0,EventHandler.getSnapshot +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,0 +DA:13,0 +DA:14,0 +DA:15,0 +DA:16,1 +DA:17,2 +DA:18,2 +DA:19,2 +DA:20,1 +DA:21,11 +DA:22,11 +DA:23,1 +DA:24,6 +DA:25,6 +DA:26,6 +DA:27,4 +DA:28,4 +DA:29,4 +DA:30,5 +DA:31,4 +DA:32,4 +DA:33,0 +DA:34,4 +DA:35,4 +DA:36,4 +DA:37,4 +DA:38,4 +DA:39,6 +DA:40,6 +DA:41,6 +DA:42,6 +DA:43,6 +DA:44,6 +DA:45,6 +DA:46,6 +DA:47,6 +DA:48,6 +DA:49,6 +DA:50,6 +DA:51,1 +DA:52,2 +DA:53,2 +DA:54,1 +DA:55,1 +DA:56,1 +DA:57,1 +DA:58,0 +DA:59,0 +DA:60,0 +DA:61,0 +DA:62,0 +DA:63,0 +DA:64,0 +DA:65,0 +DA:66,0 +DA:67,0 +DA:68,0 +DA:69,0 +DA:70,0 +DA:71,0 +DA:72,0 +DA:73,0 +DA:74,0 +DA:75,0 +DA:76,1 +DA:77,2 +DA:78,1 +DA:79,0 +DA:80,0 +DA:81,0 +DA:82,0 +DA:83,0 +DA:84,0 +DA:85,0 +DA:86,0 +DA:87,1 +DA:88,6 +DA:89,6 +DA:90,6 +DA:91,0 +DA:92,1 +DA:93,0 +DA:94,0 +DA:95,0 +DA:96,0 +DA:97,0 +DA:98,1 +DA:99,1 +LF:99 +LH:62 +BRDA:9,0,0,1 +BRDA:9,1,0,0 +BRDA:16,2,0,2 +BRDA:20,3,0,11 +BRDA:21,4,0,11 +BRDA:23,5,0,6 +BRDA:26,6,0,4 +BRDA:26,7,0,4 +BRDA:49,8,0,0 +BRDA:29,9,0,5 +BRDA:51,10,0,2 +BRDA:53,11,0,1 +BRDA:58,12,0,0 +BRDA:87,13,0,6 +BRDA:91,14,0,0 +BRF:15 +BRH:11 +end_of_record +TN: +SF:src/core/Graph.ts +FN:88,GraphNode +FN:123,get +FN:124,set +FN:164,Graph +FN:170,Graph.init +FN:178,Graph.load +FN:208,Graph.setLoaders +FN:215,Graph.runLoaders +FN:226,Graph.add +FN:263,Graph.remove +FN:278,recursiveRemove +FN:316,Graph.run +FN:329,Graph.clearListeners +FN:362,Graph.get +FN:363,Graph.set +FN:364,Graph.delete +FN:366,Graph.getProps +FN:385,Graph.subscribe +FN:405,callback +FN:413,ondelete +FN:423,ondelete +FN:444,Graph.unsubscribe +FN:451,Graph.setState +FN:458,recursivelyAssign +FN:486,getAllProperties +FN:510,instanceObject +FNF:26 +FNH:18 +FNDA:6,GraphNode +FNDA:138,get +FNDA:5,set +FNDA:1,Graph +FNDA:1,Graph.init +FNDA:1,Graph.load +FNDA:0,Graph.setLoaders +FNDA:6,Graph.runLoaders +FNDA:0,Graph.add +FNDA:1,Graph.remove +FNDA:0,recursiveRemove +FNDA:3,Graph.run +FNDA:1,Graph.clearListeners +FNDA:47,Graph.get +FNDA:6,Graph.set +FNDA:1,Graph.delete +FNDA:0,Graph.getProps +FNDA:6,Graph.subscribe +FNDA:2,callback +FNDA:1,ondelete +FNDA:0,ondelete +FNDA:1,Graph.unsubscribe +FNDA:0,Graph.setState +FNDA:13,recursivelyAssign +FNDA:0,getAllProperties +FNDA:0,instanceObject +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,1 +DA:13,1 +DA:14,1 +DA:15,1 +DA:16,1 +DA:17,1 +DA:18,1 +DA:19,1 +DA:20,1 +DA:21,1 +DA:22,1 +DA:23,1 +DA:24,1 +DA:25,1 +DA:26,1 +DA:27,1 +DA:28,1 +DA:29,1 +DA:30,1 +DA:31,1 +DA:32,1 +DA:33,1 +DA:34,1 +DA:35,1 +DA:36,1 +DA:37,1 +DA:38,1 +DA:39,1 +DA:40,1 +DA:41,1 +DA:42,1 +DA:43,1 +DA:44,1 +DA:45,1 +DA:46,1 +DA:47,1 +DA:48,1 +DA:49,1 +DA:50,1 +DA:51,1 +DA:52,1 +DA:53,1 +DA:54,1 +DA:55,1 +DA:56,1 +DA:57,1 +DA:58,1 +DA:59,1 +DA:60,1 +DA:61,1 +DA:62,1 +DA:63,1 +DA:64,1 +DA:65,1 +DA:66,1 +DA:67,1 +DA:68,1 +DA:69,1 +DA:70,1 +DA:71,1 +DA:72,1 +DA:73,1 +DA:74,1 +DA:75,1 +DA:76,1 +DA:77,1 +DA:78,1 +DA:79,1 +DA:80,1 +DA:81,1 +DA:82,1 +DA:83,1 +DA:84,1 +DA:85,1 +DA:86,1 +DA:87,1 +DA:88,1 +DA:89,6 +DA:90,6 +DA:91,6 +DA:92,6 +DA:93,6 +DA:94,6 +DA:95,6 +DA:96,6 +DA:97,6 +DA:98,6 +DA:99,6 +DA:100,6 +DA:101,6 +DA:102,6 +DA:103,6 +DA:104,6 +DA:105,6 +DA:106,6 +DA:107,6 +DA:108,6 +DA:109,6 +DA:110,6 +DA:111,6 +DA:112,6 +DA:113,39 +DA:114,39 +DA:115,39 +DA:116,39 +DA:117,31 +DA:118,31 +DA:119,31 +DA:120,39 +DA:121,39 +DA:122,39 +DA:123,39 +DA:124,39 +DA:125,39 +DA:126,39 +DA:127,39 +DA:128,6 +DA:129,6 +DA:130,6 +DA:131,6 +DA:132,6 +DA:133,6 +DA:134,6 +DA:135,6 +DA:136,6 +DA:137,1 +DA:138,1 +DA:139,1 +DA:140,1 +DA:141,1 +DA:142,1 +DA:143,1 +DA:144,1 +DA:145,1 +DA:146,1 +DA:147,1 +DA:148,1 +DA:149,1 +DA:150,1 +DA:151,1 +DA:152,1 +DA:153,1 +DA:154,1 +DA:155,1 +DA:156,1 +DA:157,1 +DA:158,1 +DA:159,1 +DA:160,1 +DA:161,1 +DA:162,1 +DA:163,1 +DA:164,1 +DA:165,1 +DA:166,1 +DA:167,1 +DA:168,1 +DA:169,1 +DA:170,1 +DA:171,1 +DA:172,1 +DA:173,1 +DA:174,1 +DA:175,1 +DA:176,1 +DA:177,1 +DA:178,1 +DA:179,1 +DA:180,1 +DA:181,1 +DA:182,1 +DA:183,1 +DA:184,1 +DA:185,1 +DA:186,1 +DA:187,1 +DA:188,1 +DA:189,0 +DA:190,0 +DA:191,0 +DA:192,0 +DA:193,0 +DA:194,0 +DA:195,1 +DA:196,1 +DA:197,1 +DA:198,5 +DA:199,5 +DA:200,5 +DA:201,5 +DA:202,5 +DA:203,1 +DA:204,1 +DA:205,1 +DA:206,1 +DA:207,1 +DA:208,1 +DA:209,0 +DA:210,0 +DA:211,0 +DA:212,0 +DA:213,0 +DA:214,1 +DA:215,1 +DA:216,6 +DA:217,48 +DA:218,48 +DA:219,48 +DA:220,0 +DA:221,0 +DA:222,0 +DA:223,6 +DA:224,6 +DA:225,1 +DA:226,1 +DA:227,0 +DA:228,0 +DA:229,0 +DA:230,0 +DA:231,0 +DA:232,0 +DA:233,0 +DA:234,0 +DA:235,0 +DA:236,0 +DA:237,0 +DA:238,0 +DA:239,0 +DA:240,0 +DA:241,0 +DA:242,0 +DA:243,0 +DA:244,0 +DA:245,0 +DA:246,0 +DA:247,0 +DA:248,0 +DA:249,0 +DA:250,0 +DA:251,0 +DA:252,0 +DA:253,0 +DA:254,0 +DA:255,0 +DA:256,0 +DA:257,0 +DA:258,0 +DA:259,0 +DA:260,0 +DA:261,0 +DA:262,1 +DA:263,1 +DA:264,1 +DA:265,1 +DA:266,1 +DA:267,1 +DA:268,1 +DA:269,1 +DA:270,1 +DA:271,1 +DA:272,1 +DA:273,1 +DA:274,1 +DA:275,1 +DA:276,1 +DA:277,1 +DA:278,1 +DA:279,0 +DA:280,0 +DA:281,0 +DA:282,0 +DA:283,0 +DA:284,0 +DA:285,0 +DA:286,0 +DA:287,0 +DA:288,0 +DA:289,0 +DA:290,0 +DA:291,0 +DA:292,0 +DA:293,0 +DA:294,0 +DA:295,0 +DA:296,0 +DA:297,0 +DA:298,0 +DA:299,0 +DA:300,0 +DA:301,0 +DA:302,1 +DA:303,1 +DA:304,0 +DA:305,0 +DA:306,1 +DA:307,1 +DA:308,1 +DA:309,1 +DA:310,1 +DA:311,1 +DA:312,1 +DA:313,1 +DA:314,1 +DA:315,1 +DA:316,1 +DA:317,3 +DA:318,3 +DA:319,3 +DA:320,1 +DA:321,1 +DA:322,3 +DA:323,3 +DA:324,3 +DA:325,0 +DA:326,0 +DA:327,3 +DA:328,1 +DA:329,1 +DA:330,1 +DA:331,1 +DA:332,1 +DA:333,1 +DA:334,1 +DA:335,0 +DA:336,0 +DA:337,0 +DA:338,0 +DA:339,0 +DA:340,0 +DA:341,0 +DA:342,0 +DA:343,0 +DA:344,0 +DA:345,0 +DA:346,0 +DA:347,0 +DA:348,0 +DA:349,0 +DA:350,0 +DA:351,0 +DA:352,0 +DA:353,0 +DA:354,0 +DA:355,0 +DA:356,0 +DA:357,0 +DA:358,0 +DA:359,1 +DA:360,1 +DA:361,1 +DA:362,1 +DA:363,1 +DA:364,1 +DA:365,1 +DA:366,1 +DA:367,0 +DA:368,0 +DA:369,0 +DA:370,0 +DA:371,0 +DA:372,0 +DA:373,0 +DA:374,0 +DA:375,0 +DA:376,0 +DA:377,0 +DA:378,0 +DA:379,0 +DA:380,0 +DA:381,0 +DA:382,0 +DA:383,0 +DA:384,1 +DA:385,1 +DA:386,6 +DA:387,6 +DA:388,6 +DA:389,6 +DA:390,6 +DA:391,6 +DA:392,6 +DA:393,6 +DA:394,6 +DA:395,6 +DA:396,6 +DA:397,6 +DA:398,6 +DA:399,6 +DA:400,2 +DA:401,2 +DA:402,2 +DA:403,2 +DA:404,2 +DA:405,2 +DA:406,2 +DA:407,2 +DA:408,2 +DA:409,6 +DA:410,6 +DA:411,6 +DA:412,6 +DA:413,6 +DA:414,1 +DA:415,1 +DA:416,6 +DA:417,6 +DA:418,6 +DA:419,6 +DA:420,0 +DA:421,0 +DA:422,0 +DA:423,0 +DA:424,0 +DA:425,0 +DA:426,0 +DA:427,0 +DA:428,0 +DA:429,0 +DA:430,0 +DA:431,0 +DA:432,0 +DA:433,0 +DA:434,0 +DA:435,0 +DA:436,0 +DA:437,0 +DA:438,0 +DA:439,0 +DA:440,0 +DA:441,6 +DA:442,6 +DA:443,1 +DA:444,1 +DA:445,1 +DA:446,0 +DA:447,0 +DA:448,1 +DA:449,1 +DA:450,1 +DA:451,1 +DA:452,0 +DA:453,0 +DA:454,1 +DA:455,1 +DA:456,1 +DA:457,1 +DA:458,13 +DA:459,13 +DA:460,42 +DA:461,12 +DA:462,12 +DA:463,42 +DA:464,42 +DA:465,13 +DA:466,13 +DA:467,13 +DA:468,1 +DA:469,1 +DA:470,1 +DA:471,1 +DA:472,1 +DA:473,1 +DA:474,1 +DA:475,1 +DA:476,1 +DA:477,1 +DA:478,1 +DA:479,1 +DA:480,1 +DA:481,1 +DA:482,1 +DA:483,1 +DA:484,1 +DA:485,1 +DA:486,1 +DA:487,0 +DA:488,0 +DA:489,0 +DA:490,0 +DA:491,0 +DA:492,0 +DA:493,0 +DA:494,0 +DA:495,0 +DA:496,0 +DA:497,0 +DA:498,0 +DA:499,0 +DA:500,0 +DA:501,0 +DA:502,0 +DA:503,0 +DA:504,0 +DA:505,0 +DA:506,0 +DA:507,0 +DA:508,0 +DA:509,1 +DA:510,1 +DA:511,0 +DA:512,0 +DA:513,0 +DA:514,0 +DA:515,0 +DA:516,0 +DA:517,1 +DA:518,1 +LF:518 +LH:348 +BRDA:88,0,0,6 +BRDA:91,1,0,0 +BRDA:92,2,0,0 +BRDA:106,3,0,0 +BRDA:112,4,0,39 +BRDA:116,5,0,31 +BRDA:118,6,0,5 +BRDA:125,7,0,31 +BRDA:125,8,0,8 +BRDA:130,9,0,0 +BRDA:123,10,0,138 +BRDA:124,11,0,5 +BRDA:164,12,0,1 +BRDA:170,13,0,1 +BRDA:178,14,0,1 +BRDA:180,15,0,0 +BRDA:183,16,0,0 +BRDA:188,17,0,0 +BRDA:195,18,0,0 +BRDA:197,19,0,5 +BRDA:215,20,0,6 +BRDA:216,21,0,48 +BRDA:219,22,0,0 +BRDA:263,23,0,1 +BRDA:303,24,0,0 +BRDA:316,25,0,3 +BRDA:319,26,0,1 +BRDA:319,27,0,1 +BRDA:322,28,0,2 +BRDA:324,29,0,0 +BRDA:324,30,0,0 +BRDA:329,31,0,1 +BRDA:330,32,0,0 +BRDA:334,33,0,0 +BRDA:362,34,0,47 +BRDA:363,35,0,6 +BRDA:364,36,0,1 +BRDA:385,37,0,6 +BRDA:395,38,0,0 +BRDA:399,39,0,2 +BRDA:407,40,0,0 +BRDA:419,41,0,0 +BRDA:405,42,0,2 +BRDA:413,43,0,1 +BRDA:444,44,0,1 +BRDA:445,45,0,0 +BRDA:458,46,0,13 +BRDA:459,47,0,42 +BRDA:460,48,0,38 +BRDA:460,49,0,12 +BRDA:460,50,0,12 +BRDA:461,51,0,1 +BRDA:461,52,0,1 +BRDA:461,53,0,1 +BRDA:462,54,0,11 +BRDA:463,55,0,30 +BRF:56 +BRH:38 +end_of_record +TN: +SF:src/core/loaders/index.ts +FNF:0 +FNH:0 +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,1 +DA:13,1 +DA:14,1 +DA:15,1 +DA:16,1 +DA:17,1 +LF:17 +LH:17 +BRF:0 +BRH:0 +end_of_record +TN: +SF:src/core/loaders/graphscript-children-loader/index.ts +FN:5,default +FN:22,recursiveSet +FN:57,ondelete +FNF:3 +FNH:2 +FNDA:6,default +FNDA:2,recursiveSet +FNDA:0,ondelete +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,6 +DA:7,6 +DA:8,6 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,6 +DA:13,6 +DA:14,6 +DA:15,6 +DA:16,6 +DA:17,6 +DA:18,6 +DA:19,6 +DA:20,6 +DA:21,1 +DA:22,1 +DA:23,2 +DA:24,2 +DA:25,6 +DA:26,6 +DA:27,6 +DA:28,6 +DA:29,6 +DA:30,2 +DA:31,1 +DA:32,1 +DA:33,1 +DA:34,6 +DA:35,0 +DA:36,0 +DA:37,4 +DA:38,0 +DA:39,0 +DA:40,0 +DA:41,6 +DA:42,6 +DA:43,6 +DA:44,6 +DA:45,6 +DA:46,6 +DA:47,6 +DA:48,6 +DA:49,6 +DA:50,6 +DA:51,6 +DA:52,6 +DA:53,0 +DA:54,6 +DA:55,6 +DA:56,0 +DA:57,0 +DA:58,0 +DA:59,6 +DA:60,6 +DA:61,6 +DA:62,6 +DA:63,6 +DA:64,6 +DA:65,6 +DA:66,6 +DA:67,6 +DA:68,2 +LF:68 +LH:59 +BRDA:5,0,0,6 +BRDA:8,1,0,1 +BRDA:16,2,0,1 +BRDA:22,3,0,2 +BRDA:24,4,0,6 +BRDA:25,5,0,0 +BRDA:27,6,0,0 +BRDA:29,7,0,2 +BRDA:30,8,0,1 +BRDA:32,9,0,0 +BRDA:34,10,0,4 +BRDA:34,11,0,0 +BRDA:37,12,0,0 +BRDA:47,13,0,5 +BRDA:50,14,0,0 +BRDA:50,15,0,0 +BRDA:52,16,0,0 +BRDA:55,17,0,0 +BRDA:55,18,0,0 +BRDA:55,19,0,0 +BRF:20 +BRH:9 +end_of_record +TN: +SF:src/core/loaders/graphscript-default-loader/index.ts +FN:1,default +FN:5,defaultFunction +FNF:2 +FNH:1 +FNDA:6,default +FNDA:0,defaultFunction +DA:1,1 +DA:2,6 +DA:3,6 +DA:4,0 +DA:5,0 +DA:6,0 +DA:7,0 +DA:8,0 +DA:9,0 +DA:10,0 +DA:11,0 +DA:12,0 +DA:13,0 +DA:14,0 +DA:15,0 +DA:16,6 +DA:17,6 +DA:18,6 +LF:18 +LH:6 +BRDA:1,0,0,6 +BRDA:3,1,0,0 +BRDA:3,2,0,0 +BRF:3 +BRH:1 +end_of_record +TN: +SF:src/core/loaders/graphscript-listeners-loader/index.ts +FN:3,setListeners +FN:60,default +FN:69,set +FN:98,subscribe +FN:100,subscribeToFunction +FN:100,setTarget +FN:113,subscribeToGraph +FN:164,unsubscribe +FN:169,addLocalState +FN:175,initState +FN:180,props. +FN:194,get +FN:195,set +FN:202,get +FN:203,set +FNF:15 +FNH:12 +FNDA:2,setListeners +FNDA:6,default +FNDA:2,set +FNDA:6,subscribe +FNDA:6,subscribeToFunction +FNDA:6,setTarget +FNDA:0,subscribeToGraph +FNDA:2,unsubscribe +FNDA:4,addLocalState +FNDA:4,initState +FNDA:4,props. +FNDA:0,get +FNDA:0,set +FNDA:14,get +FNDA:5,set +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,2 +DA:5,2 +DA:6,2 +DA:7,2 +DA:8,2 +DA:9,2 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,0 +DA:14,0 +DA:15,0 +DA:16,0 +DA:17,0 +DA:18,0 +DA:19,0 +DA:20,0 +DA:21,0 +DA:22,0 +DA:23,0 +DA:24,0 +DA:25,0 +DA:26,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:30,0 +DA:31,0 +DA:32,0 +DA:33,0 +DA:34,0 +DA:35,0 +DA:36,0 +DA:37,6 +DA:38,6 +DA:39,6 +DA:40,6 +DA:41,4 +DA:42,4 +DA:43,4 +DA:44,4 +DA:45,4 +DA:46,4 +DA:47,4 +DA:48,6 +DA:49,2 +DA:50,2 +DA:51,2 +DA:52,2 +DA:53,6 +DA:54,6 +DA:55,6 +DA:56,2 +DA:57,2 +DA:58,2 +DA:59,1 +DA:60,1 +DA:61,6 +DA:62,6 +DA:63,6 +DA:64,6 +DA:65,6 +DA:66,6 +DA:67,6 +DA:68,6 +DA:69,6 +DA:70,2 +DA:71,2 +DA:72,6 +DA:73,6 +DA:74,6 +DA:75,6 +DA:76,6 +DA:77,6 +DA:78,6 +DA:79,6 +DA:80,6 +DA:81,6 +DA:82,6 +DA:83,6 +DA:84,6 +DA:85,6 +DA:86,6 +DA:87,6 +DA:88,6 +DA:89,6 +DA:90,6 +DA:91,6 +DA:92,6 +DA:93,6 +DA:94,1 +DA:95,1 +DA:96,1 +DA:97,1 +DA:98,1 +DA:99,6 +DA:100,6 +DA:101,6 +DA:102,6 +DA:103,6 +DA:104,6 +DA:105,6 +DA:106,6 +DA:107,6 +DA:108,6 +DA:109,6 +DA:110,6 +DA:111,6 +DA:112,6 +DA:113,6 +DA:114,0 +DA:115,0 +DA:116,0 +DA:117,0 +DA:118,0 +DA:119,0 +DA:120,0 +DA:121,0 +DA:122,6 +DA:123,6 +DA:124,4 +DA:125,4 +DA:126,4 +DA:127,4 +DA:128,0 +DA:129,0 +DA:130,0 +DA:131,4 +DA:132,4 +DA:133,4 +DA:134,4 +DA:135,4 +DA:136,0 +DA:137,0 +DA:138,0 +DA:139,0 +DA:140,4 +DA:141,4 +DA:142,4 +DA:143,2 +DA:144,2 +DA:145,2 +DA:146,2 +DA:147,0 +DA:148,0 +DA:149,0 +DA:150,2 +DA:151,2 +DA:152,2 +DA:153,2 +DA:154,0 +DA:155,0 +DA:156,0 +DA:157,0 +DA:158,2 +DA:159,2 +DA:160,2 +DA:161,6 +DA:162,1 +DA:163,1 +DA:164,1 +DA:165,2 +DA:166,2 +DA:167,2 +DA:168,1 +DA:169,1 +DA:170,4 +DA:171,4 +DA:172,3 +DA:173,3 +DA:174,4 +DA:175,4 +DA:176,4 +DA:177,4 +DA:178,4 +DA:179,1 +DA:180,1 +DA:181,4 +DA:182,4 +DA:183,4 +DA:184,4 +DA:185,0 +DA:186,4 +DA:187,4 +DA:188,4 +DA:189,4 +DA:190,4 +DA:191,4 +DA:192,3 +DA:193,3 +DA:194,0 +DA:195,0 +DA:196,0 +DA:197,0 +DA:198,0 +DA:199,0 +DA:200,3 +DA:201,3 +DA:202,3 +DA:203,3 +DA:204,5 +DA:205,5 +DA:206,5 +DA:207,3 +DA:208,3 +DA:209,3 +DA:210,3 +DA:211,3 +DA:212,3 +DA:213,3 +DA:214,3 +DA:215,3 +DA:216,3 +DA:217,3 +DA:218,3 +DA:219,3 +DA:220,3 +DA:221,3 +DA:222,3 +DA:223,3 +DA:224,3 +DA:225,3 +DA:226,4 +DA:227,4 +DA:228,4 +DA:229,0 +DA:230,4 +LF:230 +LH:176 +BRDA:3,0,0,2 +BRDA:9,1,0,6 +BRDA:13,2,0,0 +BRDA:38,3,0,0 +BRDA:39,4,0,4 +BRDA:40,5,0,4 +BRDA:45,6,0,0 +BRDA:48,7,0,2 +BRDA:50,8,0,0 +BRDA:60,9,0,6 +BRDA:79,10,0,4 +BRDA:85,11,0,2 +BRDA:69,12,0,2 +BRDA:70,13,0,0 +BRDA:87,14,0,6 +BRDA:89,15,0,2 +BRDA:98,16,0,6 +BRDA:123,17,0,4 +BRDA:125,18,0,1 +BRDA:127,19,0,0 +BRDA:133,20,0,0 +BRDA:136,21,0,0 +BRDA:143,22,0,2 +BRDA:146,23,0,0 +BRDA:152,24,0,0 +BRDA:154,25,0,0 +BRDA:100,26,0,6 +BRDA:106,27,0,4 +BRDA:100,28,0,6 +BRDA:164,29,0,2 +BRDA:165,30,0,0 +BRDA:166,31,0,0 +BRDA:169,32,0,4 +BRDA:170,33,0,0 +BRDA:171,34,0,3 +BRDA:229,35,0,0 +BRDA:175,36,0,4 +BRDA:178,37,0,1 +BRDA:178,38,0,1 +BRDA:191,39,0,3 +BRDA:193,40,0,0 +BRDA:193,41,0,0 +BRDA:180,42,0,4 +BRDA:181,43,0,0 +BRDA:184,44,0,0 +BRDA:202,45,0,14 +BRDA:203,46,0,5 +BRF:47 +BRH:28 +end_of_record +TN: +SF:src/core/loaders/graphscript-operator-loader/index.ts +FN:4,checkIfSubscribed +FN:12,ondelete +FN:21,default +FN:34,get +FN:35,set +FN:40,value +FNF:6 +FNH:5 +FNDA:5,checkIfSubscribed +FNDA:0,ondelete +FNDA:6,default +FNDA:29,get +FNDA:5,set +FNDA:4,value +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,5 +DA:6,5 +DA:7,5 +DA:8,5 +DA:9,5 +DA:10,5 +DA:11,0 +DA:12,0 +DA:13,0 +DA:14,0 +DA:15,0 +DA:16,0 +DA:17,0 +DA:18,5 +DA:19,5 +DA:20,1 +DA:21,1 +DA:22,6 +DA:23,6 +DA:24,6 +DA:25,6 +DA:26,6 +DA:27,6 +DA:28,6 +DA:29,6 +DA:30,6 +DA:31,6 +DA:32,6 +DA:33,6 +DA:34,6 +DA:35,6 +DA:36,5 +DA:37,5 +DA:38,5 +DA:39,5 +DA:40,5 +DA:41,4 +DA:42,4 +DA:43,4 +DA:44,3 +DA:45,0 +DA:46,3 +DA:47,3 +DA:48,4 +DA:49,5 +DA:50,5 +DA:51,5 +DA:52,5 +DA:53,5 +DA:54,5 +DA:55,0 +DA:56,0 +DA:57,6 +DA:58,6 +DA:59,6 +DA:60,6 +DA:61,4 +DA:62,4 +DA:63,0 +DA:64,0 +DA:65,0 +DA:66,0 +DA:67,0 +DA:68,0 +DA:69,4 +DA:70,4 +DA:71,4 +DA:72,4 +DA:73,6 +DA:74,6 +DA:75,6 +LF:75 +LH:59 +BRDA:4,0,0,5 +BRDA:9,1,0,0 +BRDA:10,2,0,1 +BRDA:10,3,0,0 +BRDA:21,4,0,6 +BRDA:60,5,0,4 +BRDA:62,6,0,0 +BRDA:34,7,0,29 +BRDA:35,8,0,5 +BRDA:54,9,0,0 +BRDA:40,10,0,4 +BRDA:41,11,0,0 +BRDA:43,12,0,3 +BRDA:44,13,0,2 +BRDA:44,14,0,0 +BRDA:46,15,0,2 +BRF:16 +BRH:10 +end_of_record +TN: +SF:src/core/loaders/graphscript-parent-loader/index.ts +FN:3,default +FN:27,ondelete +FNF:2 +FNH:1 +FNDA:6,default +FNDA:0,ondelete +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,6 +DA:5,6 +DA:6,6 +DA:7,6 +DA:8,6 +DA:9,6 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,6 +DA:14,6 +DA:15,6 +DA:16,6 +DA:17,6 +DA:18,6 +DA:19,6 +DA:20,0 +DA:21,0 +DA:22,0 +DA:23,0 +DA:24,0 +DA:25,0 +DA:26,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:30,0 +DA:31,0 +DA:32,6 +DA:33,6 +DA:34,6 +DA:35,6 +LF:35 +LH:23 +BRDA:3,0,0,6 +BRDA:8,1,0,1 +BRDA:9,2,0,1 +BRDA:19,3,0,5 +BRDA:19,4,0,0 +BRF:5 +BRH:4 +end_of_record +TN: +SF:src/core/loaders/graphscript-props-loader/index.ts +FN:4,proxyFunction +FN:8,default +FN:13,get +FN:15,set +FNF:4 +FNH:2 +FNDA:0,proxyFunction +FNDA:6,default +FNDA:3,get +FNDA:0,set +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,0 +DA:6,0 +DA:7,0 +DA:8,1 +DA:9,6 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,6 +DA:14,6 +DA:15,6 +DA:16,0 +DA:17,0 +DA:18,0 +DA:19,0 +DA:20,0 +DA:21,0 +DA:22,0 +DA:23,0 +DA:24,0 +DA:25,0 +DA:26,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:30,0 +DA:31,0 +DA:32,0 +DA:33,0 +DA:34,0 +DA:35,0 +DA:36,0 +DA:37,0 +DA:38,0 +DA:39,0 +DA:40,0 +DA:41,0 +DA:42,6 +DA:43,6 +DA:44,6 +DA:45,0 +DA:46,0 +DA:47,0 +DA:48,6 +DA:49,6 +DA:50,6 +LF:50 +LH:18 +BRDA:8,0,0,6 +BRDA:44,1,0,0 +BRDA:13,2,0,3 +BRF:3 +BRH:2 +end_of_record +TN: +SF:src/core/loaders/graphscript-root-loader/index.ts +FN:2,addOnConnected +FN:6,addOnDisconnected +FN:10,callConnected +FN:15,callDisconnected +FN:20,default +FNF:5 +FNH:5 +FNDA:8,addOnConnected +FNDA:7,addOnDisconnected +FNDA:6,callConnected +FNDA:1,callDisconnected +FNDA:6,default +DA:1,1 +DA:2,8 +DA:3,8 +DA:4,8 +DA:5,1 +DA:6,7 +DA:7,7 +DA:8,7 +DA:9,1 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,6 +DA:14,1 +DA:15,1 +DA:16,1 +DA:17,1 +DA:18,1 +DA:19,1 +DA:20,1 +DA:21,6 +DA:22,6 +DA:23,6 +DA:24,0 +DA:25,0 +DA:26,6 +DA:27,6 +DA:28,6 +DA:29,6 +DA:30,6 +DA:31,6 +DA:32,6 +DA:33,6 +DA:34,6 +DA:35,6 +DA:36,6 +DA:37,6 +DA:38,6 +DA:39,6 +DA:40,6 +DA:41,6 +DA:42,6 +DA:43,6 +DA:44,6 +DA:45,6 +DA:46,6 +DA:47,6 +DA:48,6 +DA:49,6 +DA:50,6 +DA:51,6 +DA:52,6 +DA:53,6 +DA:54,6 +DA:55,6 +DA:56,6 +DA:57,6 +DA:58,6 +DA:59,6 +DA:60,6 +DA:61,6 +DA:62,0 +DA:63,0 +DA:64,0 +DA:65,6 +DA:66,6 +DA:67,6 +LF:67 +LH:62 +BRDA:2,0,0,8 +BRDA:6,1,0,7 +BRDA:10,2,0,6 +BRDA:12,3,0,8 +BRDA:15,4,0,1 +BRDA:17,5,0,2 +BRDA:20,6,0,6 +BRDA:23,7,0,0 +BRDA:27,8,0,0 +BRDA:28,9,0,0 +BRDA:50,10,0,0 +BRDA:51,11,0,0 +BRDA:58,12,0,0 +BRDA:61,13,0,0 +BRF:14 +BRH:7 +end_of_record +TN: +SF:src/core/parsers/function.ts +FN:6,isNativeClass +FN:11,isFunction +FN:25,default +FNF:3 +FNH:2 +FNDA:2,isNativeClass +FNDA:2,isFunction +FNDA:0,default +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,2 +DA:8,2 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,2 +DA:13,2 +DA:14,2 +DA:15,1 +DA:16,1 +DA:17,2 +DA:18,1 +DA:19,1 +DA:20,2 +DA:21,2 +DA:22,2 +DA:23,2 +DA:24,1 +DA:25,1 +DA:26,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:30,0 +DA:31,0 +DA:32,0 +DA:33,0 +DA:34,0 +LF:34 +LH:25 +BRDA:6,0,0,2 +BRDA:11,1,0,2 +BRDA:14,2,0,1 +BRDA:15,3,0,0 +BRDA:17,4,0,1 +BRDA:18,5,0,0 +BRDA:20,6,0,0 +BRF:7 +BRH:4 +end_of_record +TN: +SF:src/core/parsers/index.ts +FNF:0 +FNH:0 +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +LF:7 +LH:7 +BRF:0 +BRH:0 +end_of_record +TN: +SF:src/core/parsers/string.ts +FN:1,default +FNF:1 +FNH:0 +FNDA:0,default +DA:1,1 +DA:2,0 +DA:3,0 +DA:4,0 +LF:4 +LH:1 +BRF:0 +BRH:0 +end_of_record +TN: +SF:src/loaders/index.ts +FN:8,backprop +FN:40,loop +FN:46,node.__operator +FN:54,node.__operator +FN:63,node.__operator +FN:92,node.__operator +FN:100,onstart +FN:102,ondelete +FN:125,animate +FN:130,node.__operator +FN:141,onstart +FN:151,ondelete +FN:171,branching +FN:175,node.__operator +FN:203,node.__listeners.callback +FN:231,triggerListenerOncreate +FN:248,bindListener +FN:266,transformListenerResult +FN:273,node.__listeners.callback +FN:284,substitute__operator +FNF:20 +FNH:11 +FNDA:6,backprop +FNDA:6,loop +FNDA:0,node.__operator +FNDA:0,node.__operator +FNDA:0,node.__operator +FNDA:1,node.__operator +FNDA:1,onstart +FNDA:1,ondelete +FNDA:6,animate +FNDA:0,node.__operator +FNDA:0,onstart +FNDA:0,ondelete +FNDA:6,branching +FNDA:0,node.__operator +FNDA:0,node.__listeners.callback +FNDA:6,triggerListenerOncreate +FNDA:6,bindListener +FNDA:6,transformListenerResult +FNDA:0,node.__listeners.callback +FNDA:6,substitute__operator +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,6 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,6 +DA:14,0 +DA:15,0 +DA:16,0 +DA:17,0 +DA:18,0 +DA:19,0 +DA:20,0 +DA:21,6 +DA:22,6 +DA:23,6 +DA:24,1 +DA:25,1 +DA:26,1 +DA:27,1 +DA:28,1 +DA:29,1 +DA:30,1 +DA:31,1 +DA:32,1 +DA:33,1 +DA:34,1 +DA:35,1 +DA:36,1 +DA:37,1 +DA:38,1 +DA:39,1 +DA:40,1 +DA:41,6 +DA:42,6 +DA:43,4 +DA:44,4 +DA:45,0 +DA:46,0 +DA:47,0 +DA:48,0 +DA:49,0 +DA:50,0 +DA:51,0 +DA:52,4 +DA:53,0 +DA:54,0 +DA:55,0 +DA:56,0 +DA:57,0 +DA:58,0 +DA:59,0 +DA:60,4 +DA:61,4 +DA:62,0 +DA:63,0 +DA:64,0 +DA:65,0 +DA:66,0 +DA:67,0 +DA:68,0 +DA:69,0 +DA:70,0 +DA:71,0 +DA:72,0 +DA:73,0 +DA:74,0 +DA:75,0 +DA:76,0 +DA:77,0 +DA:78,0 +DA:79,0 +DA:80,0 +DA:81,0 +DA:82,0 +DA:83,0 +DA:84,0 +DA:85,4 +DA:86,4 +DA:87,1 +DA:88,1 +DA:89,1 +DA:90,1 +DA:91,1 +DA:92,1 +DA:93,1 +DA:94,1 +DA:95,1 +DA:96,1 +DA:97,1 +DA:98,1 +DA:99,1 +DA:100,1 +DA:101,1 +DA:102,1 +DA:103,1 +DA:104,1 +DA:105,1 +DA:106,1 +DA:107,1 +DA:108,1 +DA:109,1 +DA:110,1 +DA:111,1 +DA:112,4 +DA:113,6 +DA:114,6 +DA:115,1 +DA:116,1 +DA:117,1 +DA:118,1 +DA:119,1 +DA:120,1 +DA:121,1 +DA:122,1 +DA:123,1 +DA:124,1 +DA:125,1 +DA:126,6 +DA:127,0 +DA:128,0 +DA:129,0 +DA:130,0 +DA:131,0 +DA:132,0 +DA:133,0 +DA:134,0 +DA:135,0 +DA:136,0 +DA:137,0 +DA:138,0 +DA:139,0 +DA:140,0 +DA:141,0 +DA:142,0 +DA:143,0 +DA:144,0 +DA:145,0 +DA:146,0 +DA:147,0 +DA:148,0 +DA:149,0 +DA:150,0 +DA:151,0 +DA:152,0 +DA:153,0 +DA:154,0 +DA:155,0 +DA:156,0 +DA:157,6 +DA:158,1 +DA:159,1 +DA:160,1 +DA:161,1 +DA:162,1 +DA:163,1 +DA:164,1 +DA:165,1 +DA:166,1 +DA:167,1 +DA:168,1 +DA:169,1 +DA:170,1 +DA:171,1 +DA:172,6 +DA:173,0 +DA:174,0 +DA:175,0 +DA:176,0 +DA:177,0 +DA:178,0 +DA:179,0 +DA:180,0 +DA:181,0 +DA:182,0 +DA:183,0 +DA:184,0 +DA:185,0 +DA:186,0 +DA:187,0 +DA:188,0 +DA:189,0 +DA:190,0 +DA:191,0 +DA:192,0 +DA:193,0 +DA:194,0 +DA:195,0 +DA:196,6 +DA:197,6 +DA:198,6 +DA:199,0 +DA:200,0 +DA:201,0 +DA:202,0 +DA:203,0 +DA:204,0 +DA:205,0 +DA:206,0 +DA:207,0 +DA:208,0 +DA:209,0 +DA:210,0 +DA:211,0 +DA:212,0 +DA:213,0 +DA:214,0 +DA:215,0 +DA:216,0 +DA:217,0 +DA:218,0 +DA:219,0 +DA:220,0 +DA:221,0 +DA:222,6 +DA:223,6 +DA:224,6 +DA:225,1 +DA:226,1 +DA:227,1 +DA:228,1 +DA:229,1 +DA:230,1 +DA:231,1 +DA:232,6 +DA:233,6 +DA:234,6 +DA:235,0 +DA:236,0 +DA:237,0 +DA:238,0 +DA:239,6 +DA:240,6 +DA:241,6 +DA:242,1 +DA:243,1 +DA:244,1 +DA:245,1 +DA:246,1 +DA:247,1 +DA:248,1 +DA:249,6 +DA:250,6 +DA:251,6 +DA:252,0 +DA:253,0 +DA:254,0 +DA:255,0 +DA:256,6 +DA:257,6 +DA:258,6 +DA:259,1 +DA:260,1 +DA:261,1 +DA:262,1 +DA:263,1 +DA:264,1 +DA:265,1 +DA:266,1 +DA:267,6 +DA:268,6 +DA:269,6 +DA:270,0 +DA:271,0 +DA:272,0 +DA:273,0 +DA:274,0 +DA:275,0 +DA:276,0 +DA:277,0 +DA:278,0 +DA:279,6 +DA:280,6 +DA:281,6 +DA:282,1 +DA:283,1 +DA:284,1 +DA:285,6 +DA:286,6 +DA:287,6 +DA:288,0 +DA:289,6 +DA:290,0 +DA:291,6 +DA:292,4 +DA:293,6 +DA:294,0 +DA:295,0 +DA:296,0 +DA:297,0 +DA:298,0 +DA:299,0 +DA:300,0 +DA:301,0 +DA:302,0 +DA:303,0 +DA:304,6 +DA:305,6 +DA:306,1 +DA:307,1 +DA:308,1 +DA:309,1 +DA:310,1 +DA:311,1 +DA:312,1 +DA:313,1 +DA:314,1 +DA:315,1 +DA:316,1 +DA:317,1 +LF:317 +LH:168 +BRDA:8,0,0,6 +BRDA:11,1,0,0 +BRDA:13,2,0,0 +BRDA:13,3,0,0 +BRDA:40,4,0,6 +BRDA:42,5,0,4 +BRDA:42,6,0,4 +BRDA:44,7,0,0 +BRDA:52,8,0,0 +BRDA:61,9,0,0 +BRDA:86,10,0,1 +BRDA:86,11,0,1 +BRDA:92,12,0,1 +BRDA:93,13,0,0 +BRDA:100,14,0,1 +BRDA:102,15,0,1 +BRDA:106,16,0,1 +BRDA:125,17,0,6 +BRDA:126,18,0,0 +BRDA:171,19,0,6 +BRDA:172,20,0,0 +BRDA:172,21,0,0 +BRDA:172,22,0,0 +BRDA:198,23,0,0 +BRDA:231,24,0,6 +BRDA:234,25,0,0 +BRDA:248,26,0,6 +BRDA:251,27,0,0 +BRDA:266,28,0,6 +BRDA:269,29,0,0 +BRDA:284,30,0,6 +BRDA:287,31,0,0 +BRDA:287,32,0,0 +BRDA:289,33,0,2 +BRDA:289,34,0,0 +BRDA:291,35,0,4 +BRDA:293,36,0,0 +BRDA:304,37,0,3 +BRDA:304,38,0,1 +BRF:39 +BRH:20 +end_of_record +TN: +SF:src/loaders/html/html.loader.ts +FN:23,htmlloader +FNF:1 +FNH:0 +FNDA:0,htmlloader +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,1 +DA:13,1 +DA:14,1 +DA:15,1 +DA:16,1 +DA:17,1 +DA:18,1 +DA:19,1 +DA:20,1 +DA:21,1 +DA:22,1 +DA:23,1 +DA:24,0 +DA:25,0 +DA:26,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:30,0 +DA:31,0 +DA:32,0 +DA:33,0 +DA:34,0 +DA:35,0 +DA:36,0 +DA:37,0 +DA:38,0 +DA:39,0 +DA:40,0 +DA:41,0 +DA:42,0 +DA:43,0 +DA:44,0 +DA:45,0 +DA:46,0 +DA:47,0 +DA:48,0 +DA:49,0 +DA:50,0 +DA:51,0 +DA:52,0 +DA:53,0 +DA:54,0 +DA:55,0 +DA:56,0 +DA:57,0 +DA:58,0 +DA:59,0 +DA:60,0 +DA:61,0 +DA:62,0 +DA:63,0 +DA:64,0 +DA:65,0 +DA:66,0 +DA:67,0 +DA:68,0 +DA:69,0 +DA:70,0 +DA:71,0 +DA:72,0 +DA:73,0 +DA:74,0 +DA:75,0 +DA:76,0 +DA:77,0 +DA:78,0 +DA:79,0 +DA:80,0 +DA:81,0 +DA:82,0 +DA:83,0 +DA:84,0 +DA:85,0 +DA:86,0 +DA:87,0 +DA:88,0 +DA:89,0 +DA:90,0 +DA:91,0 +DA:92,0 +DA:93,0 +DA:94,0 +DA:95,0 +DA:96,0 +DA:97,0 +DA:98,0 +DA:99,0 +DA:100,0 +DA:101,0 +DA:102,0 +DA:103,0 +DA:104,0 +DA:105,0 +DA:106,0 +DA:107,0 +DA:108,0 +DA:109,0 +DA:110,0 +DA:111,0 +DA:112,0 +DA:113,0 +DA:114,0 +DA:115,0 +DA:116,0 +DA:117,0 +DA:118,0 +DA:119,0 +DA:120,0 +DA:121,1 +DA:122,1 +LF:122 +LH:25 +BRF:0 +BRH:0 +end_of_record +TN: +SF:tests/utils/index.ts +FN:39,add +FN:46,addCommand +FN:56,addHeader +FN:93,get iterations +FN:97,set iterations +FN:109,OperationsManager +FN:128,OperationsManager.start +FN:139,OperationsManager.stop +FN:160,OperationsManager.runAll +FN:168,OperationsManager.run +FN:186,OperationsManager.next +FN:118,set +FN:146,setStart +FN:151,setStop +FN:155,setOperations +FNF:15 +FNH:14 +FNDA:16,add +FNDA:8,addCommand +FNDA:1,addHeader +FNDA:8,get iterations +FNDA:8,set iterations +FNDA:1,OperationsManager +FNDA:1,OperationsManager.start +FNDA:1,OperationsManager.stop +FNDA:0,OperationsManager.runAll +FNDA:8,OperationsManager.run +FNDA:8,OperationsManager.next +FNDA:1,set +FNDA:1,setStart +FNDA:1,setStop +FNDA:1,setOperations +DA:1,1 +DA:2,1 +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:10,0 +DA:11,0 +DA:12,0 +DA:13,0 +DA:14,0 +DA:15,0 +DA:16,0 +DA:17,0 +DA:18,0 +DA:19,0 +DA:20,0 +DA:21,0 +DA:22,0 +DA:23,0 +DA:24,0 +DA:25,0 +DA:26,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:30,0 +DA:31,0 +DA:32,0 +DA:33,0 +DA:34,0 +DA:35,1 +DA:36,1 +DA:37,1 +DA:38,1 +DA:39,1 +DA:40,16 +DA:41,0 +DA:42,0 +DA:43,0 +DA:44,16 +DA:45,1 +DA:46,1 +DA:47,8 +DA:48,8 +DA:49,8 +DA:50,0 +DA:51,0 +DA:52,0 +DA:53,0 +DA:54,0 +DA:55,1 +DA:56,1 +DA:57,1 +DA:58,1 +DA:59,0 +DA:60,0 +DA:61,0 +DA:62,0 +DA:63,1 +DA:64,1 +DA:65,1 +DA:66,1 +DA:67,1 +DA:68,1 +DA:69,1 +DA:70,1 +DA:71,1 +DA:72,1 +DA:73,1 +DA:74,1 +DA:75,1 +DA:76,1 +DA:77,1 +DA:78,1 +DA:79,1 +DA:80,1 +DA:81,1 +DA:82,1 +DA:83,1 +DA:84,1 +DA:85,1 +DA:86,1 +DA:87,1 +DA:88,1 +DA:89,1 +DA:90,1 +DA:91,1 +DA:92,1 +DA:93,1 +DA:94,8 +DA:95,8 +DA:96,1 +DA:97,1 +DA:98,8 +DA:99,8 +DA:100,8 +DA:101,8 +DA:102,1 +DA:103,1 +DA:104,1 +DA:105,1 +DA:106,1 +DA:107,1 +DA:108,1 +DA:109,1 +DA:110,1 +DA:111,1 +DA:112,1 +DA:113,1 +DA:114,1 +DA:115,1 +DA:116,1 +DA:117,1 +DA:118,1 +DA:119,1 +DA:120,1 +DA:121,1 +DA:122,1 +DA:123,1 +DA:124,1 +DA:125,1 +DA:126,1 +DA:127,1 +DA:128,1 +DA:129,1 +DA:130,1 +DA:131,1 +DA:132,1 +DA:133,1 +DA:134,1 +DA:135,1 +DA:136,1 +DA:137,1 +DA:138,1 +DA:139,1 +DA:140,1 +DA:141,1 +DA:142,1 +DA:143,1 +DA:144,1 +DA:145,1 +DA:146,1 +DA:147,1 +DA:148,1 +DA:149,1 +DA:150,1 +DA:151,1 +DA:152,1 +DA:153,1 +DA:154,1 +DA:155,1 +DA:156,1 +DA:157,1 +DA:158,1 +DA:159,1 +DA:160,1 +DA:161,0 +DA:162,0 +DA:163,0 +DA:164,0 +DA:165,0 +DA:166,0 +DA:167,1 +DA:168,1 +DA:169,8 +DA:170,8 +DA:171,8 +DA:172,0 +DA:173,0 +DA:174,0 +DA:175,8 +DA:176,8 +DA:177,8 +DA:178,8 +DA:179,8 +DA:180,8 +DA:181,8 +DA:182,8 +DA:183,8 +DA:184,8 +DA:185,1 +DA:186,1 +DA:187,8 +DA:188,8 +DA:189,8 +DA:190,8 +DA:191,1 +LF:191 +LH:145 +BRDA:9,0,0,0 +BRDA:38,1,0,0 +BRDA:39,2,0,16 +BRDA:40,3,0,0 +BRDA:44,4,0,0 +BRDA:46,5,0,8 +BRDA:48,6,0,0 +BRDA:49,7,0,0 +BRDA:56,8,0,1 +BRDA:57,9,0,0 +BRDA:58,10,0,0 +BRDA:93,11,0,8 +BRDA:97,12,0,8 +BRDA:100,13,0,0 +BRDA:109,14,0,1 +BRDA:128,15,0,1 +BRDA:129,16,0,0 +BRDA:139,17,0,1 +BRDA:168,18,0,8 +BRDA:169,19,0,0 +BRDA:171,20,0,0 +BRDA:177,21,0,0 +BRDA:179,22,0,0 +BRDA:186,23,0,8 +BRDA:118,24,0,1 +BRDA:119,25,0,0 +BRDA:146,26,0,1 +BRDA:151,27,0,1 +BRDA:155,28,0,1 +BRF:29 +BRH:14 +end_of_record diff --git a/dist/index.core.d.ts b/dist/index.core.d.ts deleted file mode 100644 index b1cd8270..00000000 --- a/dist/index.core.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './src/core/Graph'; -export * from './src/core/EventHandler'; -export * from './src/loaders'; diff --git a/dist/index.core.esm.js b/dist/index.core.esm.js deleted file mode 100644 index d8e31763..00000000 --- a/dist/index.core.esm.js +++ /dev/null @@ -1 +0,0 @@ -var x=class{data={};triggers={};ctr=0;constructor(e){typeof e=="object"&&(this.data=e)}setState=e=>{Object.assign(this.data,e);let t=Object.getOwnPropertyNames(e);for(let n of t)this.triggerEvent(n,this.data[n]);if(this.triggers[G]){let n=s=>{s(e)},i=this.triggers[G].length;for(let s=i-1;s>=0;s--)n(this.triggers[G][s].onchange)}return this.data};setValue=(e,t)=>{this.data[e]=t,this.triggerEvent(e,t)};triggerEvent=(e,t)=>{if(this.triggers[e]){let n=s=>{s.onchange(t)},i=this.triggers[e].length;for(let s=i-1;s>=0;s--)n(this.triggers[e][s])}};subscribeState=e=>this.subscribeEvent(G,e);unsubscribeState=e=>this.unsubscribeEvent(G,e);subscribeEvent=(e,t,n,i)=>{if(e){n&&i&&!this.triggers[e]&&Object.defineProperty(this.data,e,{get:()=>n[i],set:r=>{n[i]=r},enumerable:!0,configurable:!0}),this.triggers[e]||(this.triggers[e]=[]);let s=this.ctr;return this.ctr++,this.triggers[e].push({sub:s,onchange:t}),s}else return};unsubscribeEvent=(e,t)=>{let n=this.triggers[e];if(n)if(t===void 0)delete this.triggers[e],delete this.data[e];else{let i,s=n.find((r,o)=>{if(r.sub===t)return i=o,!0});return s&&n.splice(i,1),Object.keys(n).length===0&&(delete this.triggers[e],delete this.data[e]),this.onRemoved&&this.onRemoved(s),!0}};subscribeEventOnce=(e,t)=>{let n,i=s=>{t(s),this.unsubscribeEvent(e,n)};return n=this.subscribeEvent(e,i),n};getEvent=(e,t)=>{if(typeof t!="number")return this.triggers[e];for(let n in this.triggers[e])if(this.triggers[e][n].sub===t)return this.triggers[e][n]};getSnapshot=()=>{let e={};for(let t in this.data)e[t]=this.data[t]};onRemoved},G="*s";var F=new x,w=class extends Function{__bound;__call;constructor(){return super("return this.__bound.__call.apply(this.__bound, arguments)"),this.__bound=this.bind(this),this.__bound}},p=class _{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state:F};__children;__parent;__operator;__listeners;__props;__args;constructor(e,t,n){if(this.__setProperties(e,t,n),typeof e=="function"||e?.__callable){let i=new w;i.__call=(...r)=>this.__operator(...r);let s=new Proxy(i,{get:(r,o,l)=>Reflect.has(this,o)?Reflect.get(this,o,l):Reflect.get(r,o,l),set:(r,o,l,f)=>Reflect.has(this,o)?Reflect.set(this,o,l,f):Reflect.set(r,o,l,f)});return Object.setPrototypeOf(s,this),s}}get __graph(){return this.__node?.graph}set __graph(e){this.__node.graph=e}__setProperties=(e,t,n)=>{if((()=>{let s=e;typeof e=="function"?P(e)?e=new e:e={__operator:e,__node:{forward:!0,tag:e.name}}:typeof e=="string"&&n?.get(e)&&(e=n.get(e)),"__node"in e||(e.__node={}),e.__node.initial||(e.__node.initial=s)})(),typeof e=="object"){let s=()=>{e.__node?.state?this.__node.state=e.__node.state:n&&(e.__node.state=n.__node.state)},r=()=>{e.__props&&(typeof e.__props=="function"&&(e.__props=new e.__props),typeof e.__props=="object"&&this.__proxyObject(e.__props))},o=()=>{e.__node.tag||(e.__operator?.name?e.__node.tag=e.__operator.name:e.__node.tag=`node${Math.floor(Math.random()*1e15)}`)},l=()=>{typeof e.__node=="string"?n?.get(e.__node.tag)?e=n.get(e.__node.tag):e.__node={}:e.__node||(e.__node={}),n&&(e.__node.graph=n),e instanceof y&&(e.__node.source=e)},f=()=>{if(!e.__parent&&t&&(e.__parent=t),t?.__node&&!(t instanceof y||e instanceof y)&&(e.__node.tag=t.__node.tag+"."+e.__node.tag),t instanceof y&&e instanceof y&&(e.__node.loaders&&Object.assign(t.__node.loaders?t.__node.loaders:{},e.__node.loaders),t.__node.mapGraphs)){e.__node.nodes.forEach(h=>{t.set(e.__node.tag+"."+h.__node.tag,h)});let u=()=>{e.__node.nodes.forEach(h=>{t.__node.nodes.delete(e.__node.tag+"."+h.__node.tag)})};this.__addOndisconnected(u)}},a=()=>{if(typeof e.default=="function"&&!e.__operator&&(e.__operator=e.default),e.__operator){if(typeof e.__operator=="string"&&n){let u=n.get(e.__operator);u&&(e.__operator=u.__operator),!e.__node.tag&&e.__operator.name&&(e.__node.tag=e.__operator.name)}typeof e.__operator=="function"&&(e.__operator=this.__setOperator(e.__operator)),e.default&&(e.default=e.__operator)}},d=()=>{e.__node=Object.assign(this.__node,e.__node);let u=Object.getOwnPropertyNames(e).filter(h=>{if(!O[h])return!0});for(let h of u)h in e&&h!=="name"&&(this[h]=e[h])},c=()=>{this.__onconnected&&(typeof this.__onconnected=="function"?this.__onconnected=this.__onconnected.bind(this):Array.isArray(this.__onconnected)&&(this.__onconnected=this.__onconnected.map(u=>u.bind(this))),typeof this.__ondisconnected=="function"?this.__ondisconnected=this.__ondisconnected.bind(this):Array.isArray(this.__ondisconnected)&&(this.__ondisconnected=this.__ondisconnected.map(u=>u.bind(this))))};s(),o(),r(),l(),f(),d(),c(),a()}};__subscribe=(e,t,n,i,s,r,o)=>{let l=(a,d=(u,h)=>h||u,c=e)=>{let u;if(r){let b=A(c,r,this.__node.graph);c=b.__callback,u=b.__args}let h=this.__node.state.subscribeEvent(a,c,this,t),g=this.__node.state.getEvent(a,h);return this.__listeners||(this.__listeners={}),this.__listeners[a]=this.__node.state.triggers[a],g&&(g.source=this.__node.tag,t&&(g.key=t),g.target=d(e,i),s&&(g.tkey=s),n&&(g.subInput=n),r&&(g.arguments=u,g.__args=r),o&&(g.__callback=o),g.node=this,g.graph=this.__node.graph),h},f=a=>{let d=this.__node.graph.get(a);if(!d&&a.includes(".")){i=a.substring(0,a.lastIndexOf("."));let c=this.__node.graph.get(a.substring(0,i));s=a.lastIndexOf(".")+1,c&&typeof c[t]=="function"&&(a=(...u)=>c[s](...u))}else d.__operator&&(a=d.__operator,s="__operator");return a};if(t){if((!this.__node.localState||!this.__node.localState[t])&&this.__addLocalState(this,t),typeof e=="string"){if(o=this.__node.tag+"."+e,s=e,i){if(this.__node.graph?.get(i)){let c=this.__node.graph?.get(i);if(typeof c[e]=="function"){let u=c[e];e=(...h)=>{u(...h)}}else{let u=e;e=g=>{c[u]=g}}}}else if(typeof this[e]=="function"){let c=this[e];e=(...u)=>{c(...u)}}else this.__node.graph?.get(e)&&(e=f(e));if(typeof e!="function")return}let a,d=n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}else{if(typeof e=="string"&&(o=e,i||(i=e),this.__node.graph.get(e)&&(e=this.__node.graph.get(e)),s="__operator",typeof e!="object"))return;let a,d=n?this.__node.unique+"input":this.__node.unique;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}};__unsubscribe=(e,t,n)=>t?this.__node.state.unsubscribeEvent(n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t,e):this.__node.state.unsubscribeEvent(n?this.__node.unique+"input":this.__node.unique,e);__setOperator=e=>{e=e.bind(this),this.__args&&this.__node.graph&&(e=A(e,this.__args,this.__node.graph).__callback);let t=`${this.__node.unique}input`;if(this.__operator=(...n)=>{this.__node.state.triggers[t]&&this.__node.state.setValue(t,n);let i=e(...n);return this.__node.state.triggers[this.__node.unique]&&(typeof i?.then=="function"?i.then(s=>{s!==void 0&&this.__node.state.setValue(this.__node.unique,s)}).catch(console.error):i!==void 0&&this.__node.state.setValue(this.__node.unique,i)),i},this.__parent instanceof _&&!this.__subscribedToParent&&this.__parent.__operator){let n=this.__parent.__subscribe(this),i=()=>{this.__parent?.__unsubscribe(n),delete this.__subscribedToParent};this.__addOndisconnected(i),this.__subscribedToParent=!0}return this.__operator};__addLocalState=(e,t)=>{if(!e)return;this.__node.localState||(this.__node.localState={});let n=this.__node.localState,i=(s,r)=>{let o=this.__node.unique+"."+r,l=`${o}input`,f,a,d,c;if(typeof s[r]=="function"&&r!=="__operator")this.__props?.[r]?d=this.__props:d=n,f=()=>d[r],a=u=>{this.__props?.[r]||(u=u.bind(this)),d[r]=(...h)=>{this.__node.state.triggers[l]&&this.__node.state.setValue(l,h);let g=u(...h);return this.__node.state.triggers[o]&&(typeof g?.then=="function"?g.then(b=>{this.__node.state.triggerEvent(o,b)}).catch(console.error):this.__node.state.triggerEvent(o,g)),g}},n[r]=s[r].bind(this),c={get:f,set:a,enumerable:!0,configurable:!0};else if(r!=="__graph"){let u,h,g;this.__props?.[r]?g=this.__props:g=n,u=()=>g[r],h=b=>{g[r]=b,this.__node.state.triggers[o]&&this.__node.state.triggerEvent(o,b)},n[r]=s[r],c={get:u,set:h,enumerable:!0,configurable:!0}}if(Object.defineProperty(s,r,c),typeof this.__node.initial=="object"){let u=Object.getOwnPropertyDescriptor(this.__node.initial,r);(u===void 0||u?.configurable)&&Object.defineProperty(this.__node.initial,r,c)}};if(t)i(e,t);else for(let s in e)i(e,s)};__proxyObject=e=>{let t=q(e);for(let n of t){let i={get:()=>e[n],set:s=>{e[n]=s},enumerable:!0,configurable:!0};if(Object.defineProperty(this,n,i),typeof this.__node.initial=="object"){let s=Object.getOwnPropertyDescriptor(this.__node.initial,n);(s===void 0||s?.configurable)&&Object.defineProperty(this.__node.initial,n,i)}}};__addOnconnected(e){e=e.bind(this),Array.isArray(this.__onconnected)?this.__onconnected.push(e):typeof this.__onconnected=="function"?this.__onconnected=[e,this.__onconnected]:this.__onconnected=e}__addOndisconnected(e){e=e.bind(this),Array.isArray(this.__ondisconnected)?this.__ondisconnected.push(e):typeof this.__ondisconnected=="function"?this.__ondisconnected=[e,this.__ondisconnected]:this.__ondisconnected=e}__callConnected(e=this){if(typeof this.__onconnected=="function")this.__onconnected(this);else if(Array.isArray(this.__onconnected)){let t=n=>{n(this)};this.__onconnected.forEach(t)}}__callDisconnected(e=this){if(typeof this.__ondisconnected=="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let t=n=>{n(this)};this.__ondisconnected.forEach(t)}}},y=class _{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state:F,roots:{}};constructor(e){this.init(e)}init=e=>{if(e){let t=Object.assign({},e);delete t.roots,N(this.__node,t),e.roots&&this.load(e.roots)}};load=(e,t=!1)=>{function n(r,o,l=!0,f=!0){if(f){r||(r={});for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=o[a],o[a]?.__children&&n({},o[a].__children,!1,!1)):typeof o[a]=="function"&&(r[a]=o[a]);n(r,o,!0,!1)}else if(o?.__children&&!l)o.__children?.constructor.name==="Object"?r.__children?.constructor.name==="Object"?r.__children=n(r.__children,o.__children,!0,!1):r.__children=n({},o.__children,!0,!1):r.__children=o.__children;else if(l)for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=Object.assign({},o[a]),o[a]?.__children&&(r[a].__children=n({},o[a].__children,!1,!1))):typeof o[a]=="function"&&(r[a]=o[a]);return r}this.__node.roots=n(this.__node.roots?this.__node.roots:{},e);let i=Object.assign({},e);i.__node&&delete i.__node;let s=this.recursiveSet(i,this,void 0,e,t);if(e.__node){if(!e.__node.tag)e.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(e.__node.tag)){let r=new p(e,this,this);this.set(r.__node.tag,r),this.runLoaders(r,this,e,e.__node.tag),r.__listeners&&(s[r.__node.tag]=r.__listeners)}}else e.__listeners&&this.setListeners(e.__listeners);return this.setListeners(s),i};setLoaders=(e,t)=>(t?this.__node.loaders=e:Object.assign(this.__node.loaders,e),this.__node.loaders);runLoaders=(e,t,n,i)=>{for(let s in this.__node.loaders)typeof this.__node.loaders[s]=="object"?(this.__node.loaders[s].init&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i),this.__node.loaders[s].connected&&e.__addOnconnected(this.__node.loaders[s].connect),this.__node.loaders[s].disconnected&&e.__addOndisconnected(this.__node.loaders[s].disconnect)):typeof this.__node.loaders[s]=="function"&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i)};add=(e,t,n=!0)=>{let i={};typeof t=="string"&&(t=this.get(t));let s;if(typeof e=="function"?P(e)?e.prototype instanceof p?(e=e.prototype.constructor(e,t,this),s=!0):e=new e:e={__operator:e,__callable:!0}:typeof e=="string"&&(e=this.__node.roots[e]),!e)return;if(!s){let l=Object.getOwnPropertyNames(e),f=Object.getOwnPropertyNames(Object.getPrototypeOf(e));l.push(...f),l=l.filter(d=>!O.includes(d));let a={};for(let d of l)a[d]=e[d];e=a}if(e.__node||(e.__node={}),e.__node.initial=e,typeof e=="object"&&this.get(e.__node.tag))if(n)this.remove(e.__node.tag,!0);else return;else if(e.__node.tag&&this.get(e.__node.tag))return this.get(e.__node.tag);let r,o=N({},e,2);if(s?r=e:r=new p(e,t,this),this.set(r.__node.tag,r),this.runLoaders(r,t,e,r.__node.tag),this.__node.roots[r.__node.tag]=o,r.__children&&(r.__children=Object.assign({},r.__children),this.recursiveSet(r.__children,r,i,r.__children)),r.__listeners){i[r.__node.tag]=Object.assign({},r.__listeners);for(let l in r.__listeners){let f=r.__listeners[l];r[l]&&(delete i[r.__node.tag][l],i[r.__node.tag][r.__node.tag+"."+l]=f),typeof f=="string"&&(r.__children?.[f]?i[r.__node.tag][l]=r.__node.tag+"."+f:t instanceof p&&(t.__node.tag===f||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===f)&&(i[r.__node.tag][l]=t.__node.tag))}}return this.setListeners(i),r.__callConnected(),r};recursiveSet=(e,t,n={},i,s=!1)=>{let r=Object.getOwnPropertyNames(i).filter(l=>!O.includes(l)),o=Object.getOwnPropertyNames(Object.getPrototypeOf(i)).filter(l=>!O.includes(l));r.push(...o);for(let l of r){if(l.includes("__"))continue;let f=i[l];if(Array.isArray(f))continue;let a;if(typeof f=="function"?P(f)?(f=new f,f instanceof p&&(f=f.prototype.constructor(f,t,this),a=!0)):f={__operator:f,__callable:!0}:typeof f=="string"?this.__node.nodes.get(f)?f=this.__node.nodes.get(f):f=this.__node.roots[f]:typeof f=="boolean"&&(this.__node.nodes.get(l)?f=this.__node.nodes.get(l):f=this.__node.roots[l]),f&&typeof f=="object"){if(!a&&!(f instanceof p)){let h=Object.getOwnPropertyNames(f).filter(m=>!O.includes(m)),g=Object.getOwnPropertyNames(Object.getPrototypeOf(f)).filter(m=>!O.includes(m));g.splice(g.indexOf("constructor"),1),h.push(...g);let b={};for(let m of h)b[m]=f[m];f=b}if(f.__node||(f.__node={}),f.__node.tag||(f.__node.tag=l),f.__node.initial||(f.__node.initial=e[l]),s&&this.get(f.__node.tag))this.remove(f.__node.tag,!0);else if(this.get(f.__node.tag)&&!(!(t instanceof _)&&t?.__node)||t?.__node&&this.get(t.__node.tag+"."+f.__node.tag))continue;let d,c=!1,u=N({},f,2);if(a||f instanceof p?d=f:(d=new p(f,t,this),c=!0),!c&&f instanceof p&&!a&&t instanceof p){let h=this.subscribe(t.__node.tag,d.__node.tag),g=b=>{this.unsubscribe(t.__node.tag,h)};d.__addOndisconnected(g)}else if(d){if(this.set(d.__node.tag,d),this.runLoaders(d,t,e[l],l),e[l]=d,this.__node.roots[d.__node.tag]=u,d.__children&&(d.__children=Object.assign({},d.__children),this.recursiveSet(d.__children,d,n,d.__children)),d.__listeners){n[d.__node.tag]=Object.assign({},d.__listeners);for(let h in d.__listeners){let g=d.__listeners[h],b=h;d[h]&&(delete n[d.__node.tag][h],b=d.__node.tag+"."+h,n[d.__node.tag][b]=g),typeof g=="string"&&(d.__children?.[g]?n[d.__node.tag][b]=d.__node.tag+"."+g:t instanceof p&&(t.__node.tag===g||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===g)&&(n[d.__node.tag][b]=t.__node.tag))}}d.__callConnected()}}}return n};remove=(e,t=!0)=>{if(this.unsubscribe(e),typeof e=="string"&&(e=this.get(e)),e instanceof p){this.delete(e.__node.tag),delete this.__node.roots[e.__node.tag],t&&this.clearListeners(e),e.__callDisconnected();let n=i=>{for(let s in i)this.unsubscribe(i[s]),this.delete(i[s].__node.tag),delete this.__node.roots[i[s].__node.tag],this.delete(s),delete this.__node.roots[s],i[s].__node.tag=i[s].__node.tag.substring(i[s].__node.tag.lastIndexOf(".")+1),t&&this.clearListeners(i[s]),i[s].__callDisconnected(),i[s].__children&&n(i[s].__children)};e.__children&&n(e.__children)}return e?.__node.tag&&e?.__parent&&(delete e?.__parent,e.__node.tag=e.__node.tag.substring(e.__node.tag.indexOf(".")+1)),e?.__node.graph&&(e.__node.graph=void 0),e};run=(e,...t)=>{if(typeof e=="string"){let n=this.get(e);if(!n&&e.includes(".")){if(n=this.get(e.substring(0,e.lastIndexOf("."))),typeof n?.[e.substring(e.lastIndexOf(".")+1)]=="function")return n[e.substring(e.lastIndexOf(".")+1)](...t)}else if(n?.__operator)return n.__operator(...t)}if(e?.__operator)return e?.__operator(...t)};setListeners=e=>{for(let t in e){let n=this.get(t);if(typeof e[t]=="object")for(let i in e[t]){let s=this.get(i),r;if(typeof e[t][i]!="object")e[t][i]={__callback:e[t][i]};else if(!e[t][i].__callback)for(let o in e[t][i]){typeof e[t][i][o]!="object"&&(e[t][i][o]={__callback:e[t][i][o]},n.__operator&&(e[t][i][o].__callback===!0||typeof e[t][i][o].__callback>"u")&&(e[t][i][o].__callback=n.__operator));let l=this.get(o);if(l)r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,void 0,e[t][i][o].subInput,t);else{let f=i.substring(0,i.lastIndexOf("."));if(l=this.get(f),l){let a=i.substring(i.lastIndexOf(".")+1);r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,a,e[t][i][o].subInput,t)}}}if("__callback"in e[t][i])if(n&&((e[t][i].__callback===!0||typeof e[t][i].__callback>"u")&&(e[t][i].__callback=n.__operator),typeof e[t][i].__callback=="function"&&(e[t][i].__callback=e[t][i].__callback.bind(n))),s)r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,void 0,e[t][i].subInput,t);else{let o=i.substring(0,i.lastIndexOf("."));s=this.get(o),s&&(r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,i.substring(i.lastIndexOf(".")+1),e[t][i].subInput,t))}}}};clearListeners=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e?.__listeners)for(let n in e.__listeners){if(t&&n!==t||typeof e.__listeners[n]?.sub!="number")continue;let i=this.get(n);if(i)if(typeof!e.__listeners[n]?.__callback=="number")for(let s in e.__listeners[n])e.__listeners[n][s]?.sub&&(this.unsubscribe(i,e.__listeners[n][s].sub,void 0,e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,void 0,e.__listeners[n].subInput),e.__listeners[n].sub=void 0);else if(i=this.get(n.substring(0,n.lastIndexOf("."))),i)if(typeof e.__listeners[n]=="object"&&!e.__listeners[n]?.__callback)for(let s in e.__listeners[n])typeof e.__listeners[n][s]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n][s].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n].subInput),e.__listeners[n].sub=void 0)}};get=e=>this.__node.nodes.get(e);getByUnique=e=>Array.from(this.__node.nodes.values()).find(t=>{if(t.__node.unique===e)return!0});set=(e,t)=>this.__node.nodes.set(e,t);delete=e=>this.__node.nodes.delete(e);list=()=>Array.from(this.__node.nodes.keys());getListener=(e,t,n)=>{let i=this.get(e);if(i){let s=i.__node.unique;return t&&(s+="."+t),this.__node.state.getEvent(s,n)}};getProps=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e instanceof p){let n;if(t)n=Object.assign({},this.__node.roots[e.__node.tag]);else{n=Object.assign({},e);for(let i in n)i.includes("__")&&delete n[i]}}};subscribe=(e,t,n,i,s,r,o)=>{let l=e;typeof e=="string"&&(l=this.get(e),!l&&e.includes(".")&&(l=this.get(e.substring(0,e.lastIndexOf("."))),i=e.substring(e.lastIndexOf(".")+1))),r instanceof p&&(r=r.__node.tag);let f;if(typeof t=="string"){f=t;let d=c=>{if(this.get(c)?.__operator){let u=this.get(c);r=c,c=function(...h){return u.__operator(...h)}}else if(c.includes(".")){r=c.substring(0,c.lastIndexOf("."));let u=this.get(r),h=c.substring(c.lastIndexOf(".")+1);o=h,typeof u[h]=="function"?u[h]instanceof p?c=u[h]:c=function(...g){return u[h](...g)}:c=function(g){return u[h]=g,u[h]}}return c};if(r){let c=this.get(r);typeof c?.[t]=="function"?(o=t,t=function(...u){return c[i](...u)}):c?.[i]?(o=i,c[i]instanceof p?t=c[i]:t=function(u){return c[i]=u,c[i]}):t=d(t)}else t=d(t)}let a;if(l instanceof p){let d=()=>{a=l.__subscribe(t,i,s,r,o,n,f);let c=()=>{a!==void 0&&l.__unsubscribe(a,i,s),a=void 0};l.__addOndisconnected(()=>{c(),l.__addOnconnected(()=>{a===void 0&&l.__node.graph.__node.tag===this.__node.tag&&d()})}),typeof t=="string"&&this.get(t)&&(t=this.get(t)),t instanceof p&&t.__addOndisconnected(()=>{c()})};d()}else if(typeof e=="string"){let d=this.get(e);if(d){if(t instanceof p&&t.__operator){let c=()=>{a=d.__subscribe(t.__operator,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s)};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),t.__addOndisconnected(u)};c()}else if(typeof t=="function"||typeof t=="string"){let c=()=>{a=d.__subscribe(t,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s),a=void 0};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),typeof t=="string"&&this.get(t)&&this.get(t).__addOndisconnected(u)};c()}}else typeof t=="string"&&(t=this.__node.nodes.get(t).__operator),typeof t=="function"&&!t?.__node&&(a=this.__node.state.subscribeEvent(e,t))}return a};unsubscribe=(e,t,n,i)=>e instanceof p?e.__unsubscribe(t,n,i):this.get(e)?.__unsubscribe(t,n,i);setState=e=>{this.__node.state.setState(e)}};function N(_,e,t=1/0,n=0){for(let i in e)e[i]?.constructor.name==="Object"&&n{if(e.get(_)?.__operator){let t=e.get(_);return(...n)=>{t.__operator(...n)}}else if(_.includes(".")){let t=_.split("."),n=t.pop(),i=t.join("."),s=e.get(i);return typeof e.get(i)?.[n]=="function"?(...r)=>s[n](...r):()=>s[n]}else if(e.get(_)){let t=e.get(_);return()=>t}else{let t=_;return()=>t}},A=(_,e,t)=>{let n=[],i=(r,o)=>{if(r==="__output"||r==="__input"||r==="__callback")n[o]={__callback:l=>l,__args:void 0,idx:o};else if(typeof r=="string")n[o]={__callback:j(r,t),__args:void 0,idx:o};else if(typeof r=="function"){let l=r;n[o]={__callback:(...f)=>l(...f),__args:void 0,idx:o}}else if(typeof r=="object"&&(r.__input||r.__callback)){let l=function(f){let a=f.__input?f.__input:f.__callback;if(typeof f.__input=="string"&&(a={__callback:j(f.__input,t),__args:void 0,idx:o}),f.__args){let d=A(a,f.__args,t);a={__callback:d.__callback,__args:d.__args,idx:o}}else a={__callback:a,__args:void 0,idx:o};if(f.__output){let d=f.__output;if(typeof f.__output=="string"?d={__callback:j(d,t),__args:void 0,idx:o}:typeof r.__output=="object"&&(d=l(d)),typeof d?.__callback=="function"){let c=a.__callback,u=d.__callback;a={__callback:(...h)=>u(c(...h)),__args:d.__args,idx:o}}}return a};n[o]=l(r)}else{let l=r;n[o]={__callback:()=>l,__args:void 0,idx:o}}};e.forEach(i),typeof _=="string"&&(_={__callback:j(_,t),__args:void 0});let s=typeof _=="function"?_:_.__callback;return _=function(...r){let o=f=>f.__callback(...r);return s(...n.map(o))},{__callback:_,__args:n}},O=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var S=(_,e,t)=>{_.__node.backward&&e instanceof p&&t.setListeners({[e.__node.tag]:{[_.__node.tag]:e}})},I=(_,e,t)=>{if(_.__operator){let n=Math.random();if(_.__node.loops||(_.__node.loops={}),typeof _.__node.delay=="number"){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=setTimeout(async()=>{r(await i(...s))},_.__node.delay)}))}else if(_.__node.frame===!0){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=requestAnimationFrame(async()=>{r(await i(...s))})}))}if(typeof _.__node.repeat=="number"||typeof _.__node.recursive=="number"){let i=_.__operator;_.__setOperator(async(...s)=>{let r=_.__node.repeat?_.__node.repeat:_.__node.recursive,o,l=async(f,...a)=>{for(;f>0;){if(_.__node.delay||_.__node.frame){i(...a).then(async d=>{_.__node.recursive?await l(f,d):await l(f,...a)});break}else o=await i(...s);f--}};return await l(r,...s),o})}if(_.__node.loop&&typeof _.__node.loop=="number"){let i=_.__operator,s=_.__node.loop;_.__setOperator((...o)=>{if("looping"in _.__node||(_.__node.looping=!0),_.__node.looping){let l=performance.now();i(...o),_.__node.loops[n]=setTimeout(()=>{let a=performance.now()-l-_.__node.loop;a>0?s=_.__node.loop-a:s=_.__node.loop,s<=0&&(s=_.__node.loop),_.__operator(...o)},s)}}),_.__node.looping&&_.__operator();let r=o=>{o.__node.looping&&(o.__node.looping=!1),o.__node.loops[n]&&(clearTimeout(o.__node.loops[n]),cancelAnimationFrame(o.__node.loops[n]))};_.__addOndisconnected(r)}}},v=(_,e,t)=>{if(_.__node.animate===!0||_.__animation){let n=_.__operator;_.__setOperator((...s)=>{"animating"in _.__node||(_.__node.animating=!0),_.__node.animating&&(typeof _.__animation=="function"?_.__animation(...s):n(...s),_.__node.animationFrame=requestAnimationFrame(()=>{_.__operator(...s)}))}),(_.__node.animating||(!("animating"in _.__node)||_.__node.animating)&&_.__animation)&&setTimeout(()=>{_.__node.animationFrame=requestAnimationFrame(_.__operator)},10);let i=s=>{s.__node.animating&&(s.__node.animating=!1),s.__node.animationFrame&&cancelAnimationFrame(s.__node.animationFrame)};_.__addOndisconnected(i)}},M=(_,e,t)=>{if(typeof _.__branch=="object"&&_.__operator&&!_.__branchApplied){let n=_.__operator;_.__branchApplied=!0,_.__operator=(...i)=>{let s=n(...i);for(let r in _.__branch){let o=()=>{typeof _.__branch[r].then=="function"?_.__branch[r].then(s):_.__branch[r].then instanceof p&&_.__branch[r].then.__operator?_.__branch[r].then.__operator(s):s=_.__branch[r].then};typeof _.__branch[r].if=="function"?_.__branch[r].if(s)==!0&&o():_.__branch[r].if===s&&o()}return s}}if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&_.__listeners[n].branch&&!_.__listeners[n].branchApplied){let i=_.__listeners[n].callback;_.__listeners[n].branchApplied=!0,_.__listeners.callback=s=>{let r=()=>{typeof _.__listeners[n].branch.then=="function"?s=_.__listeners[n].branch.then(s):_.__listeners[n].branch.then instanceof p&&_.__listeners[n].branch.then.__operator?s=_.__listeners[n].branch.then.__operator(s):s=_.__listeners[n].branch.then};return typeof _.__listeners[n].branch.if=="function"?_.__listeners[n].branch.if(s)&&r():_.__listeners[n].branch.if===s&&r(),i(s)}}}},R=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&_.__listeners[n].oncreate&&_.__listeners[n].callback(_.__listeners[n].oncreate)},T=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].binding=="object"&&(_.__listeners.callback=_.__listeners.callback.bind(_.__listeners[n].binding))},$=(_,e,t)=>{if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].transform=="function"&&!_.__listeners[n].transformApplied){let i=_.__listeners[n].callback;_.__listeners[n].transformApplied=!0,_.__listeners.callback=s=>(s=_.__listeners[n].transform(s),i(s))}}},C=(_,e,t)=>{_.post&&!_.__operator?_.__setOperator(_.post):!_.__operator&&typeof _.get=="function"&&_.__setOperator(_.get),!_.get&&_.__operator,_.aliases&&_.aliases.forEach(n=>{t.set(n,_);let i=s=>{t.__node.nodes.delete(n)};_.__addOndisconnected(i)}),typeof t.__node.roots?.[_.__node.tag]=="object"&&_.get&&(t.__node.roots[_.__node.tag].get=_.get)},J={backprop:S,loop:I,animate:v,branching:M,triggerListenerOncreate:R,bindListener:T,transformListenerResult:$,substitute__operator:C};export{w as Callable,x as EventHandler,y as Graph,p as GraphNode,v as animate,S as backprop,T as bindListener,M as branching,q as getAllProperties,j as getCallbackFromString,W as instanceObject,L as isFunction,P as isNativeClass,J as loaders,I as loop,F as state,C as substitute__operator,$ as transformListenerResult,R as triggerListenerOncreate,A as wrapArgs}; diff --git a/dist/index.core.js b/dist/index.core.js deleted file mode 100644 index e2031152..00000000 --- a/dist/index.core.js +++ /dev/null @@ -1 +0,0 @@ -(()=>{var x=class{data={};triggers={};ctr=0;constructor(e){typeof e=="object"&&(this.data=e)}setState=e=>{Object.assign(this.data,e);let t=Object.getOwnPropertyNames(e);for(let n of t)this.triggerEvent(n,this.data[n]);if(this.triggers[G]){let n=s=>{s(e)},i=this.triggers[G].length;for(let s=i-1;s>=0;s--)n(this.triggers[G][s].onchange)}return this.data};setValue=(e,t)=>{this.data[e]=t,this.triggerEvent(e,t)};triggerEvent=(e,t)=>{if(this.triggers[e]){let n=s=>{s.onchange(t)},i=this.triggers[e].length;for(let s=i-1;s>=0;s--)n(this.triggers[e][s])}};subscribeState=e=>this.subscribeEvent(G,e);unsubscribeState=e=>this.unsubscribeEvent(G,e);subscribeEvent=(e,t,n,i)=>{if(e){n&&i&&!this.triggers[e]&&Object.defineProperty(this.data,e,{get:()=>n[i],set:r=>{n[i]=r},enumerable:!0,configurable:!0}),this.triggers[e]||(this.triggers[e]=[]);let s=this.ctr;return this.ctr++,this.triggers[e].push({sub:s,onchange:t}),s}else return};unsubscribeEvent=(e,t)=>{let n=this.triggers[e];if(n)if(t===void 0)delete this.triggers[e],delete this.data[e];else{let i,s=n.find((r,o)=>{if(r.sub===t)return i=o,!0});return s&&n.splice(i,1),Object.keys(n).length===0&&(delete this.triggers[e],delete this.data[e]),this.onRemoved&&this.onRemoved(s),!0}};subscribeEventOnce=(e,t)=>{let n,i=s=>{t(s),this.unsubscribeEvent(e,n)};return n=this.subscribeEvent(e,i),n};getEvent=(e,t)=>{if(typeof t!="number")return this.triggers[e];for(let n in this.triggers[e])if(this.triggers[e][n].sub===t)return this.triggers[e][n]};getSnapshot=()=>{let e={};for(let t in this.data)e[t]=this.data[t]};onRemoved},G="*s";var F=new x,w=class extends Function{__bound;__call;constructor(){return super("return this.__bound.__call.apply(this.__bound, arguments)"),this.__bound=this.bind(this),this.__bound}},p=class _{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state:F};__children;__parent;__operator;__listeners;__props;__args;constructor(e,t,n){if(this.__setProperties(e,t,n),typeof e=="function"||e?.__callable){let i=new w;i.__call=(...r)=>this.__operator(...r);let s=new Proxy(i,{get:(r,o,l)=>Reflect.has(this,o)?Reflect.get(this,o,l):Reflect.get(r,o,l),set:(r,o,l,f)=>Reflect.has(this,o)?Reflect.set(this,o,l,f):Reflect.set(r,o,l,f)});return Object.setPrototypeOf(s,this),s}}get __graph(){return this.__node?.graph}set __graph(e){this.__node.graph=e}__setProperties=(e,t,n)=>{if((()=>{let s=e;typeof e=="function"?P(e)?e=new e:e={__operator:e,__node:{forward:!0,tag:e.name}}:typeof e=="string"&&n?.get(e)&&(e=n.get(e)),"__node"in e||(e.__node={}),e.__node.initial||(e.__node.initial=s)})(),typeof e=="object"){let s=()=>{e.__node?.state?this.__node.state=e.__node.state:n&&(e.__node.state=n.__node.state)},r=()=>{e.__props&&(typeof e.__props=="function"&&(e.__props=new e.__props),typeof e.__props=="object"&&this.__proxyObject(e.__props))},o=()=>{e.__node.tag||(e.__operator?.name?e.__node.tag=e.__operator.name:e.__node.tag=`node${Math.floor(Math.random()*1e15)}`)},l=()=>{typeof e.__node=="string"?n?.get(e.__node.tag)?e=n.get(e.__node.tag):e.__node={}:e.__node||(e.__node={}),n&&(e.__node.graph=n),e instanceof y&&(e.__node.source=e)},f=()=>{if(!e.__parent&&t&&(e.__parent=t),t?.__node&&!(t instanceof y||e instanceof y)&&(e.__node.tag=t.__node.tag+"."+e.__node.tag),t instanceof y&&e instanceof y&&(e.__node.loaders&&Object.assign(t.__node.loaders?t.__node.loaders:{},e.__node.loaders),t.__node.mapGraphs)){e.__node.nodes.forEach(h=>{t.set(e.__node.tag+"."+h.__node.tag,h)});let u=()=>{e.__node.nodes.forEach(h=>{t.__node.nodes.delete(e.__node.tag+"."+h.__node.tag)})};this.__addOndisconnected(u)}},a=()=>{if(typeof e.default=="function"&&!e.__operator&&(e.__operator=e.default),e.__operator){if(typeof e.__operator=="string"&&n){let u=n.get(e.__operator);u&&(e.__operator=u.__operator),!e.__node.tag&&e.__operator.name&&(e.__node.tag=e.__operator.name)}typeof e.__operator=="function"&&(e.__operator=this.__setOperator(e.__operator)),e.default&&(e.default=e.__operator)}},d=()=>{e.__node=Object.assign(this.__node,e.__node);let u=Object.getOwnPropertyNames(e).filter(h=>{if(!O[h])return!0});for(let h of u)h in e&&h!=="name"&&(this[h]=e[h])},c=()=>{this.__onconnected&&(typeof this.__onconnected=="function"?this.__onconnected=this.__onconnected.bind(this):Array.isArray(this.__onconnected)&&(this.__onconnected=this.__onconnected.map(u=>u.bind(this))),typeof this.__ondisconnected=="function"?this.__ondisconnected=this.__ondisconnected.bind(this):Array.isArray(this.__ondisconnected)&&(this.__ondisconnected=this.__ondisconnected.map(u=>u.bind(this))))};s(),o(),r(),l(),f(),d(),c(),a()}};__subscribe=(e,t,n,i,s,r,o)=>{let l=(a,d=(u,h)=>h||u,c=e)=>{let u;if(r){let b=A(c,r,this.__node.graph);c=b.__callback,u=b.__args}let h=this.__node.state.subscribeEvent(a,c,this,t),g=this.__node.state.getEvent(a,h);return this.__listeners||(this.__listeners={}),this.__listeners[a]=this.__node.state.triggers[a],g&&(g.source=this.__node.tag,t&&(g.key=t),g.target=d(e,i),s&&(g.tkey=s),n&&(g.subInput=n),r&&(g.arguments=u,g.__args=r),o&&(g.__callback=o),g.node=this,g.graph=this.__node.graph),h},f=a=>{let d=this.__node.graph.get(a);if(!d&&a.includes(".")){i=a.substring(0,a.lastIndexOf("."));let c=this.__node.graph.get(a.substring(0,i));s=a.lastIndexOf(".")+1,c&&typeof c[t]=="function"&&(a=(...u)=>c[s](...u))}else d.__operator&&(a=d.__operator,s="__operator");return a};if(t){if((!this.__node.localState||!this.__node.localState[t])&&this.__addLocalState(this,t),typeof e=="string"){if(o=this.__node.tag+"."+e,s=e,i){if(this.__node.graph?.get(i)){let c=this.__node.graph?.get(i);if(typeof c[e]=="function"){let u=c[e];e=(...h)=>{u(...h)}}else{let u=e;e=g=>{c[u]=g}}}}else if(typeof this[e]=="function"){let c=this[e];e=(...u)=>{c(...u)}}else this.__node.graph?.get(e)&&(e=f(e));if(typeof e!="function")return}let a,d=n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}else{if(typeof e=="string"&&(o=e,i||(i=e),this.__node.graph.get(e)&&(e=this.__node.graph.get(e)),s="__operator",typeof e!="object"))return;let a,d=n?this.__node.unique+"input":this.__node.unique;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}};__unsubscribe=(e,t,n)=>t?this.__node.state.unsubscribeEvent(n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t,e):this.__node.state.unsubscribeEvent(n?this.__node.unique+"input":this.__node.unique,e);__setOperator=e=>{e=e.bind(this),this.__args&&this.__node.graph&&(e=A(e,this.__args,this.__node.graph).__callback);let t=`${this.__node.unique}input`;if(this.__operator=(...n)=>{this.__node.state.triggers[t]&&this.__node.state.setValue(t,n);let i=e(...n);return this.__node.state.triggers[this.__node.unique]&&(typeof i?.then=="function"?i.then(s=>{s!==void 0&&this.__node.state.setValue(this.__node.unique,s)}).catch(console.error):i!==void 0&&this.__node.state.setValue(this.__node.unique,i)),i},this.__parent instanceof _&&!this.__subscribedToParent&&this.__parent.__operator){let n=this.__parent.__subscribe(this),i=()=>{this.__parent?.__unsubscribe(n),delete this.__subscribedToParent};this.__addOndisconnected(i),this.__subscribedToParent=!0}return this.__operator};__addLocalState=(e,t)=>{if(!e)return;this.__node.localState||(this.__node.localState={});let n=this.__node.localState,i=(s,r)=>{let o=this.__node.unique+"."+r,l=`${o}input`,f,a,d,c;if(typeof s[r]=="function"&&r!=="__operator")this.__props?.[r]?d=this.__props:d=n,f=()=>d[r],a=u=>{this.__props?.[r]||(u=u.bind(this)),d[r]=(...h)=>{this.__node.state.triggers[l]&&this.__node.state.setValue(l,h);let g=u(...h);return this.__node.state.triggers[o]&&(typeof g?.then=="function"?g.then(b=>{this.__node.state.triggerEvent(o,b)}).catch(console.error):this.__node.state.triggerEvent(o,g)),g}},n[r]=s[r].bind(this),c={get:f,set:a,enumerable:!0,configurable:!0};else if(r!=="__graph"){let u,h,g;this.__props?.[r]?g=this.__props:g=n,u=()=>g[r],h=b=>{g[r]=b,this.__node.state.triggers[o]&&this.__node.state.triggerEvent(o,b)},n[r]=s[r],c={get:u,set:h,enumerable:!0,configurable:!0}}if(Object.defineProperty(s,r,c),typeof this.__node.initial=="object"){let u=Object.getOwnPropertyDescriptor(this.__node.initial,r);(u===void 0||u?.configurable)&&Object.defineProperty(this.__node.initial,r,c)}};if(t)i(e,t);else for(let s in e)i(e,s)};__proxyObject=e=>{let t=q(e);for(let n of t){let i={get:()=>e[n],set:s=>{e[n]=s},enumerable:!0,configurable:!0};if(Object.defineProperty(this,n,i),typeof this.__node.initial=="object"){let s=Object.getOwnPropertyDescriptor(this.__node.initial,n);(s===void 0||s?.configurable)&&Object.defineProperty(this.__node.initial,n,i)}}};__addOnconnected(e){e=e.bind(this),Array.isArray(this.__onconnected)?this.__onconnected.push(e):typeof this.__onconnected=="function"?this.__onconnected=[e,this.__onconnected]:this.__onconnected=e}__addOndisconnected(e){e=e.bind(this),Array.isArray(this.__ondisconnected)?this.__ondisconnected.push(e):typeof this.__ondisconnected=="function"?this.__ondisconnected=[e,this.__ondisconnected]:this.__ondisconnected=e}__callConnected(e=this){if(typeof this.__onconnected=="function")this.__onconnected(this);else if(Array.isArray(this.__onconnected)){let t=n=>{n(this)};this.__onconnected.forEach(t)}}__callDisconnected(e=this){if(typeof this.__ondisconnected=="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let t=n=>{n(this)};this.__ondisconnected.forEach(t)}}},y=class _{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state:F,roots:{}};constructor(e){this.init(e)}init=e=>{if(e){let t=Object.assign({},e);delete t.roots,N(this.__node,t),e.roots&&this.load(e.roots)}};load=(e,t=!1)=>{function n(r,o,l=!0,f=!0){if(f){r||(r={});for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=o[a],o[a]?.__children&&n({},o[a].__children,!1,!1)):typeof o[a]=="function"&&(r[a]=o[a]);n(r,o,!0,!1)}else if(o?.__children&&!l)o.__children?.constructor.name==="Object"?r.__children?.constructor.name==="Object"?r.__children=n(r.__children,o.__children,!0,!1):r.__children=n({},o.__children,!0,!1):r.__children=o.__children;else if(l)for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=Object.assign({},o[a]),o[a]?.__children&&(r[a].__children=n({},o[a].__children,!1,!1))):typeof o[a]=="function"&&(r[a]=o[a]);return r}this.__node.roots=n(this.__node.roots?this.__node.roots:{},e);let i=Object.assign({},e);i.__node&&delete i.__node;let s=this.recursiveSet(i,this,void 0,e,t);if(e.__node){if(!e.__node.tag)e.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(e.__node.tag)){let r=new p(e,this,this);this.set(r.__node.tag,r),this.runLoaders(r,this,e,e.__node.tag),r.__listeners&&(s[r.__node.tag]=r.__listeners)}}else e.__listeners&&this.setListeners(e.__listeners);return this.setListeners(s),i};setLoaders=(e,t)=>(t?this.__node.loaders=e:Object.assign(this.__node.loaders,e),this.__node.loaders);runLoaders=(e,t,n,i)=>{for(let s in this.__node.loaders)typeof this.__node.loaders[s]=="object"?(this.__node.loaders[s].init&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i),this.__node.loaders[s].connected&&e.__addOnconnected(this.__node.loaders[s].connect),this.__node.loaders[s].disconnected&&e.__addOndisconnected(this.__node.loaders[s].disconnect)):typeof this.__node.loaders[s]=="function"&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i)};add=(e,t,n=!0)=>{let i={};typeof t=="string"&&(t=this.get(t));let s;if(typeof e=="function"?P(e)?e.prototype instanceof p?(e=e.prototype.constructor(e,t,this),s=!0):e=new e:e={__operator:e,__callable:!0}:typeof e=="string"&&(e=this.__node.roots[e]),!e)return;if(!s){let l=Object.getOwnPropertyNames(e),f=Object.getOwnPropertyNames(Object.getPrototypeOf(e));l.push(...f),l=l.filter(d=>!O.includes(d));let a={};for(let d of l)a[d]=e[d];e=a}if(e.__node||(e.__node={}),e.__node.initial=e,typeof e=="object"&&this.get(e.__node.tag))if(n)this.remove(e.__node.tag,!0);else return;else if(e.__node.tag&&this.get(e.__node.tag))return this.get(e.__node.tag);let r,o=N({},e,2);if(s?r=e:r=new p(e,t,this),this.set(r.__node.tag,r),this.runLoaders(r,t,e,r.__node.tag),this.__node.roots[r.__node.tag]=o,r.__children&&(r.__children=Object.assign({},r.__children),this.recursiveSet(r.__children,r,i,r.__children)),r.__listeners){i[r.__node.tag]=Object.assign({},r.__listeners);for(let l in r.__listeners){let f=r.__listeners[l];r[l]&&(delete i[r.__node.tag][l],i[r.__node.tag][r.__node.tag+"."+l]=f),typeof f=="string"&&(r.__children?.[f]?i[r.__node.tag][l]=r.__node.tag+"."+f:t instanceof p&&(t.__node.tag===f||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===f)&&(i[r.__node.tag][l]=t.__node.tag))}}return this.setListeners(i),r.__callConnected(),r};recursiveSet=(e,t,n={},i,s=!1)=>{let r=Object.getOwnPropertyNames(i).filter(l=>!O.includes(l)),o=Object.getOwnPropertyNames(Object.getPrototypeOf(i)).filter(l=>!O.includes(l));r.push(...o);for(let l of r){if(l.includes("__"))continue;let f=i[l];if(Array.isArray(f))continue;let a;if(typeof f=="function"?P(f)?(f=new f,f instanceof p&&(f=f.prototype.constructor(f,t,this),a=!0)):f={__operator:f,__callable:!0}:typeof f=="string"?this.__node.nodes.get(f)?f=this.__node.nodes.get(f):f=this.__node.roots[f]:typeof f=="boolean"&&(this.__node.nodes.get(l)?f=this.__node.nodes.get(l):f=this.__node.roots[l]),f&&typeof f=="object"){if(!a&&!(f instanceof p)){let h=Object.getOwnPropertyNames(f).filter(m=>!O.includes(m)),g=Object.getOwnPropertyNames(Object.getPrototypeOf(f)).filter(m=>!O.includes(m));g.splice(g.indexOf("constructor"),1),h.push(...g);let b={};for(let m of h)b[m]=f[m];f=b}if(f.__node||(f.__node={}),f.__node.tag||(f.__node.tag=l),f.__node.initial||(f.__node.initial=e[l]),s&&this.get(f.__node.tag))this.remove(f.__node.tag,!0);else if(this.get(f.__node.tag)&&!(!(t instanceof _)&&t?.__node)||t?.__node&&this.get(t.__node.tag+"."+f.__node.tag))continue;let d,c=!1,u=N({},f,2);if(a||f instanceof p?d=f:(d=new p(f,t,this),c=!0),!c&&f instanceof p&&!a&&t instanceof p){let h=this.subscribe(t.__node.tag,d.__node.tag),g=b=>{this.unsubscribe(t.__node.tag,h)};d.__addOndisconnected(g)}else if(d){if(this.set(d.__node.tag,d),this.runLoaders(d,t,e[l],l),e[l]=d,this.__node.roots[d.__node.tag]=u,d.__children&&(d.__children=Object.assign({},d.__children),this.recursiveSet(d.__children,d,n,d.__children)),d.__listeners){n[d.__node.tag]=Object.assign({},d.__listeners);for(let h in d.__listeners){let g=d.__listeners[h],b=h;d[h]&&(delete n[d.__node.tag][h],b=d.__node.tag+"."+h,n[d.__node.tag][b]=g),typeof g=="string"&&(d.__children?.[g]?n[d.__node.tag][b]=d.__node.tag+"."+g:t instanceof p&&(t.__node.tag===g||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===g)&&(n[d.__node.tag][b]=t.__node.tag))}}d.__callConnected()}}}return n};remove=(e,t=!0)=>{if(this.unsubscribe(e),typeof e=="string"&&(e=this.get(e)),e instanceof p){this.delete(e.__node.tag),delete this.__node.roots[e.__node.tag],t&&this.clearListeners(e),e.__callDisconnected();let n=i=>{for(let s in i)this.unsubscribe(i[s]),this.delete(i[s].__node.tag),delete this.__node.roots[i[s].__node.tag],this.delete(s),delete this.__node.roots[s],i[s].__node.tag=i[s].__node.tag.substring(i[s].__node.tag.lastIndexOf(".")+1),t&&this.clearListeners(i[s]),i[s].__callDisconnected(),i[s].__children&&n(i[s].__children)};e.__children&&n(e.__children)}return e?.__node.tag&&e?.__parent&&(delete e?.__parent,e.__node.tag=e.__node.tag.substring(e.__node.tag.indexOf(".")+1)),e?.__node.graph&&(e.__node.graph=void 0),e};run=(e,...t)=>{if(typeof e=="string"){let n=this.get(e);if(!n&&e.includes(".")){if(n=this.get(e.substring(0,e.lastIndexOf("."))),typeof n?.[e.substring(e.lastIndexOf(".")+1)]=="function")return n[e.substring(e.lastIndexOf(".")+1)](...t)}else if(n?.__operator)return n.__operator(...t)}if(e?.__operator)return e?.__operator(...t)};setListeners=e=>{for(let t in e){let n=this.get(t);if(typeof e[t]=="object")for(let i in e[t]){let s=this.get(i),r;if(typeof e[t][i]!="object")e[t][i]={__callback:e[t][i]};else if(!e[t][i].__callback)for(let o in e[t][i]){typeof e[t][i][o]!="object"&&(e[t][i][o]={__callback:e[t][i][o]},n.__operator&&(e[t][i][o].__callback===!0||typeof e[t][i][o].__callback>"u")&&(e[t][i][o].__callback=n.__operator));let l=this.get(o);if(l)r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,void 0,e[t][i][o].subInput,t);else{let f=i.substring(0,i.lastIndexOf("."));if(l=this.get(f),l){let a=i.substring(i.lastIndexOf(".")+1);r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,a,e[t][i][o].subInput,t)}}}if("__callback"in e[t][i])if(n&&((e[t][i].__callback===!0||typeof e[t][i].__callback>"u")&&(e[t][i].__callback=n.__operator),typeof e[t][i].__callback=="function"&&(e[t][i].__callback=e[t][i].__callback.bind(n))),s)r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,void 0,e[t][i].subInput,t);else{let o=i.substring(0,i.lastIndexOf("."));s=this.get(o),s&&(r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,i.substring(i.lastIndexOf(".")+1),e[t][i].subInput,t))}}}};clearListeners=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e?.__listeners)for(let n in e.__listeners){if(t&&n!==t||typeof e.__listeners[n]?.sub!="number")continue;let i=this.get(n);if(i)if(typeof!e.__listeners[n]?.__callback=="number")for(let s in e.__listeners[n])e.__listeners[n][s]?.sub&&(this.unsubscribe(i,e.__listeners[n][s].sub,void 0,e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,void 0,e.__listeners[n].subInput),e.__listeners[n].sub=void 0);else if(i=this.get(n.substring(0,n.lastIndexOf("."))),i)if(typeof e.__listeners[n]=="object"&&!e.__listeners[n]?.__callback)for(let s in e.__listeners[n])typeof e.__listeners[n][s]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n][s].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n].subInput),e.__listeners[n].sub=void 0)}};get=e=>this.__node.nodes.get(e);getByUnique=e=>Array.from(this.__node.nodes.values()).find(t=>{if(t.__node.unique===e)return!0});set=(e,t)=>this.__node.nodes.set(e,t);delete=e=>this.__node.nodes.delete(e);list=()=>Array.from(this.__node.nodes.keys());getListener=(e,t,n)=>{let i=this.get(e);if(i){let s=i.__node.unique;return t&&(s+="."+t),this.__node.state.getEvent(s,n)}};getProps=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e instanceof p){let n;if(t)n=Object.assign({},this.__node.roots[e.__node.tag]);else{n=Object.assign({},e);for(let i in n)i.includes("__")&&delete n[i]}}};subscribe=(e,t,n,i,s,r,o)=>{let l=e;typeof e=="string"&&(l=this.get(e),!l&&e.includes(".")&&(l=this.get(e.substring(0,e.lastIndexOf("."))),i=e.substring(e.lastIndexOf(".")+1))),r instanceof p&&(r=r.__node.tag);let f;if(typeof t=="string"){f=t;let d=c=>{if(this.get(c)?.__operator){let u=this.get(c);r=c,c=function(...h){return u.__operator(...h)}}else if(c.includes(".")){r=c.substring(0,c.lastIndexOf("."));let u=this.get(r),h=c.substring(c.lastIndexOf(".")+1);o=h,typeof u[h]=="function"?u[h]instanceof p?c=u[h]:c=function(...g){return u[h](...g)}:c=function(g){return u[h]=g,u[h]}}return c};if(r){let c=this.get(r);typeof c?.[t]=="function"?(o=t,t=function(...u){return c[i](...u)}):c?.[i]?(o=i,c[i]instanceof p?t=c[i]:t=function(u){return c[i]=u,c[i]}):t=d(t)}else t=d(t)}let a;if(l instanceof p){let d=()=>{a=l.__subscribe(t,i,s,r,o,n,f);let c=()=>{a!==void 0&&l.__unsubscribe(a,i,s),a=void 0};l.__addOndisconnected(()=>{c(),l.__addOnconnected(()=>{a===void 0&&l.__node.graph.__node.tag===this.__node.tag&&d()})}),typeof t=="string"&&this.get(t)&&(t=this.get(t)),t instanceof p&&t.__addOndisconnected(()=>{c()})};d()}else if(typeof e=="string"){let d=this.get(e);if(d){if(t instanceof p&&t.__operator){let c=()=>{a=d.__subscribe(t.__operator,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s)};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),t.__addOndisconnected(u)};c()}else if(typeof t=="function"||typeof t=="string"){let c=()=>{a=d.__subscribe(t,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s),a=void 0};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),typeof t=="string"&&this.get(t)&&this.get(t).__addOndisconnected(u)};c()}}else typeof t=="string"&&(t=this.__node.nodes.get(t).__operator),typeof t=="function"&&!t?.__node&&(a=this.__node.state.subscribeEvent(e,t))}return a};unsubscribe=(e,t,n,i)=>e instanceof p?e.__unsubscribe(t,n,i):this.get(e)?.__unsubscribe(t,n,i);setState=e=>{this.__node.state.setState(e)}};function N(_,e,t=1/0,n=0){for(let i in e)e[i]?.constructor.name==="Object"&&n{if(e.get(_)?.__operator){let t=e.get(_);return(...n)=>{t.__operator(...n)}}else if(_.includes(".")){let t=_.split("."),n=t.pop(),i=t.join("."),s=e.get(i);return typeof e.get(i)?.[n]=="function"?(...r)=>s[n](...r):()=>s[n]}else if(e.get(_)){let t=e.get(_);return()=>t}else{let t=_;return()=>t}},A=(_,e,t)=>{let n=[],i=(r,o)=>{if(r==="__output"||r==="__input"||r==="__callback")n[o]={__callback:l=>l,__args:void 0,idx:o};else if(typeof r=="string")n[o]={__callback:j(r,t),__args:void 0,idx:o};else if(typeof r=="function"){let l=r;n[o]={__callback:(...f)=>l(...f),__args:void 0,idx:o}}else if(typeof r=="object"&&(r.__input||r.__callback)){let l=function(f){let a=f.__input?f.__input:f.__callback;if(typeof f.__input=="string"&&(a={__callback:j(f.__input,t),__args:void 0,idx:o}),f.__args){let d=A(a,f.__args,t);a={__callback:d.__callback,__args:d.__args,idx:o}}else a={__callback:a,__args:void 0,idx:o};if(f.__output){let d=f.__output;if(typeof f.__output=="string"?d={__callback:j(d,t),__args:void 0,idx:o}:typeof r.__output=="object"&&(d=l(d)),typeof d?.__callback=="function"){let c=a.__callback,u=d.__callback;a={__callback:(...h)=>u(c(...h)),__args:d.__args,idx:o}}}return a};n[o]=l(r)}else{let l=r;n[o]={__callback:()=>l,__args:void 0,idx:o}}};e.forEach(i),typeof _=="string"&&(_={__callback:j(_,t),__args:void 0});let s=typeof _=="function"?_:_.__callback;return _=function(...r){let o=f=>f.__callback(...r);return s(...n.map(o))},{__callback:_,__args:n}},O=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var S=(_,e,t)=>{_.__node.backward&&e instanceof p&&t.setListeners({[e.__node.tag]:{[_.__node.tag]:e}})},I=(_,e,t)=>{if(_.__operator){let n=Math.random();if(_.__node.loops||(_.__node.loops={}),typeof _.__node.delay=="number"){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=setTimeout(async()=>{r(await i(...s))},_.__node.delay)}))}else if(_.__node.frame===!0){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=requestAnimationFrame(async()=>{r(await i(...s))})}))}if(typeof _.__node.repeat=="number"||typeof _.__node.recursive=="number"){let i=_.__operator;_.__setOperator(async(...s)=>{let r=_.__node.repeat?_.__node.repeat:_.__node.recursive,o,l=async(f,...a)=>{for(;f>0;){if(_.__node.delay||_.__node.frame){i(...a).then(async d=>{_.__node.recursive?await l(f,d):await l(f,...a)});break}else o=await i(...s);f--}};return await l(r,...s),o})}if(_.__node.loop&&typeof _.__node.loop=="number"){let i=_.__operator,s=_.__node.loop;_.__setOperator((...o)=>{if("looping"in _.__node||(_.__node.looping=!0),_.__node.looping){let l=performance.now();i(...o),_.__node.loops[n]=setTimeout(()=>{let a=performance.now()-l-_.__node.loop;a>0?s=_.__node.loop-a:s=_.__node.loop,s<=0&&(s=_.__node.loop),_.__operator(...o)},s)}}),_.__node.looping&&_.__operator();let r=o=>{o.__node.looping&&(o.__node.looping=!1),o.__node.loops[n]&&(clearTimeout(o.__node.loops[n]),cancelAnimationFrame(o.__node.loops[n]))};_.__addOndisconnected(r)}}},v=(_,e,t)=>{if(_.__node.animate===!0||_.__animation){let n=_.__operator;_.__setOperator((...s)=>{"animating"in _.__node||(_.__node.animating=!0),_.__node.animating&&(typeof _.__animation=="function"?_.__animation(...s):n(...s),_.__node.animationFrame=requestAnimationFrame(()=>{_.__operator(...s)}))}),(_.__node.animating||(!("animating"in _.__node)||_.__node.animating)&&_.__animation)&&setTimeout(()=>{_.__node.animationFrame=requestAnimationFrame(_.__operator)},10);let i=s=>{s.__node.animating&&(s.__node.animating=!1),s.__node.animationFrame&&cancelAnimationFrame(s.__node.animationFrame)};_.__addOndisconnected(i)}},M=(_,e,t)=>{if(typeof _.__branch=="object"&&_.__operator&&!_.__branchApplied){let n=_.__operator;_.__branchApplied=!0,_.__operator=(...i)=>{let s=n(...i);for(let r in _.__branch){let o=()=>{typeof _.__branch[r].then=="function"?_.__branch[r].then(s):_.__branch[r].then instanceof p&&_.__branch[r].then.__operator?_.__branch[r].then.__operator(s):s=_.__branch[r].then};typeof _.__branch[r].if=="function"?_.__branch[r].if(s)==!0&&o():_.__branch[r].if===s&&o()}return s}}if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&_.__listeners[n].branch&&!_.__listeners[n].branchApplied){let i=_.__listeners[n].callback;_.__listeners[n].branchApplied=!0,_.__listeners.callback=s=>{let r=()=>{typeof _.__listeners[n].branch.then=="function"?s=_.__listeners[n].branch.then(s):_.__listeners[n].branch.then instanceof p&&_.__listeners[n].branch.then.__operator?s=_.__listeners[n].branch.then.__operator(s):s=_.__listeners[n].branch.then};return typeof _.__listeners[n].branch.if=="function"?_.__listeners[n].branch.if(s)&&r():_.__listeners[n].branch.if===s&&r(),i(s)}}}},R=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&_.__listeners[n].oncreate&&_.__listeners[n].callback(_.__listeners[n].oncreate)},T=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].binding=="object"&&(_.__listeners.callback=_.__listeners.callback.bind(_.__listeners[n].binding))},$=(_,e,t)=>{if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].transform=="function"&&!_.__listeners[n].transformApplied){let i=_.__listeners[n].callback;_.__listeners[n].transformApplied=!0,_.__listeners.callback=s=>(s=_.__listeners[n].transform(s),i(s))}}},C=(_,e,t)=>{_.post&&!_.__operator?_.__setOperator(_.post):!_.__operator&&typeof _.get=="function"&&_.__setOperator(_.get),!_.get&&_.__operator,_.aliases&&_.aliases.forEach(n=>{t.set(n,_);let i=s=>{t.__node.nodes.delete(n)};_.__addOndisconnected(i)}),typeof t.__node.roots?.[_.__node.tag]=="object"&&_.get&&(t.__node.roots[_.__node.tag].get=_.get)},J={backprop:S,loop:I,animate:v,branching:M,triggerListenerOncreate:R,bindListener:T,transformListenerResult:$,substitute__operator:C};})(); diff --git a/dist/index.d.ts b/dist/index.d.ts deleted file mode 100644 index 07ec783e..00000000 --- a/dist/index.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -export * from './src/core/Graph'; -export * from './src/core/EventHandler'; -export * from './src/loaders'; -export * from './src/services/utils'; -export { methodstrings } from './src/loaders/methodstrings'; -export * from './src/services/Service'; -export * from './src/services/remote/remote.routes'; -export * from './src/services/ecs/ECS.service'; -export { html, xml } from './src/loaders/html/html'; -export * from './src/loaders/html/html.loader'; -export { DOMElement, addCustomElement } from './src/loaders/html/DOMElement'; -export * from './src/loaders/html/wc.loader'; -export * from './src/services/e2ee/E2EE.service'; -export * from './src/services/http/HTTP.browser'; -export * from './src/services/sse/SSE.browser'; -export * from './src/services/wss/WSS.browser'; -export * from './src/services/webrtc/WebRTC.browser'; -export * from './src/services/worker/Worker.service'; -export * from './src/services/worker/ProxyListener'; -export * from './src/services/worker/WorkerCanvas'; -export * from './src/services/sessions/sessions.service'; -export * from './src/services/router/Router'; diff --git a/dist/index.esm.js b/dist/index.esm.js deleted file mode 100644 index 25d48469..00000000 --- a/dist/index.esm.js +++ /dev/null @@ -1 +0,0 @@ -var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i2=l-1;i2>=0;i2--){run(this.triggers[statesubKey][i2].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i2=l-1;i2>=0;i2--){fn(this.triggers[key][i2])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.sub===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps2=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys2=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys2){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps2();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys2=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys2.push(...nonArrowFunctions);keys2=keys2.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys2){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys2=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t2=>{for(const key in t2){this.unsubscribe(t2[key]);this.delete(t2[key].__node.tag);delete this.__node.roots[t2[key].__node.tag];this.delete(key);delete this.__node.roots[key];t2[key].__node.tag=t2[key].__node.tag.substring(t2[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t2[key])}t2[key].__callDisconnected();if(t2[key].__children){recursiveRemove(t2[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i2)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i2]={__callback:inp=>{return inp},__args:void 0,idx:i2}}else if(typeof a==="string"){args[i2]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i2}}else if(typeof a==="function"){let fn2=a;args[i2]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i2}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i2}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i2}}else{input={__callback:input,__args:void 0,idx:i2}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i2}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i2}}}return input};args[i2]=recursivelyCreateCallback(a)}else{let arg=a;args[i2]={__callback:()=>{return arg},__args:void 0,idx:i2}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i2=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i2,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function getFnParamNames(fn){if(typeof fn!=="string")fn=fn.toString();const arrowMatch=fn.match(/\(?[^]*?\)?\s*=>/);if(arrowMatch)return arrowMatch[0].replace(/[()\s]/gi,"").replace("=>","").split(",");const match=fn.match(/\([^]*?\)/);return match?match[0].replace(/[()\s]/gi,"").split(","):[]}var getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}function reconstructObject(json="{}"){try{let parsed=typeof json==="string"?JSON.parse(json):json;const parseObj=obj=>{for(const prop in obj){if(typeof obj[prop]==="string"){let funcParsed=parseFunctionFromText(obj[prop]);if(typeof funcParsed==="function"){obj[prop]=funcParsed}}else if(typeof obj[prop]==="object"){parseObj(obj[prop])}}return obj};return parseObj(parsed)}catch(err){console.error(err);return void 0}}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs3(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value==="function"?value.toString():value,path.join("."))}}}return typeof value==="function"?value.toString():value}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str2;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str2=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str2=properties.toString();else if(typeof properties==="string")str2=properties;if(str2){if(connection.run)return connection.run("setNode",[str2]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str2},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str2}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(template);if(node){nodeTemplates[node.__node.tag]=template;return node.__node?.tag}else return false}else return false},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str2=recursivelyStringifyFunctions(properties);return str2},getListenerJSON:function(){const triggers=this.__node.state.triggers;let result={};for(const key in triggers){triggers[key].forEach(trigger=>{let t2=trigger;if(!result[t2.target])result[t2.target]={};let l=t2.source+(t2.key?"."+t2.key:"");result[t2.target][l]={__callback:t2.__callback};if(t2.__args)result[t2.target][l].__args=t2.__args;if(t2.subInput)result[t2.target][l].subInput=t2.subInput})}return result},makeRootTransferrable:function(){let roots={};for(const r in this.__node.graph.__node.roots){let properties=this.__node.graph.__node.roots[r];if(typeof properties==="function"){roots[r]=properties.toString()}else if(typeof properties!=="object"){roots[r]=properties}else{roots[r]={};let keys2=Object.getOwnPropertyNames(properties).filter(v=>!objProps2.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter(v=>!objProps2.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(typeof properties[key]==="function"){roots[r][key]=properties[key].toString()}else if(typeof properties[key]==="object")roots[r][key]=stringifyWithFunctionsAndCircularRefs(properties[key]);else roots[r][key]=properties[key]}}}return roots},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key of properties){if(typeof node[key]==="function"){let str2=node[key].toString();let isNative=str2.indexOf("[native code]")>-1;result[key]={type:"function",args:getFnParamNames(node[key]),native:isNative}}else result[key]=typeof node[key]}return result}return void 0},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]?.type==="function"){if(props[key].native||props[key].args){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{proxy[key]=()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})}}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};if(connection.run)return connection.run("receiveClass",[str2,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str2,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str2,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str2=fn.toString();let message={route:"setNode",args:[str2,fnName]};if(connection.run)return connection.run("setNode",[str2,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str2,fnName]},void 0);return new Promise(r=>r(fnName))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str2,fnName]}));return new Promise(r=>r(fnName))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var objProps2=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var ECSService=class extends Service{entities={};systems={};entityMap=new Map;entityKeyMap=new Map;order=[];animating=false;entityCt=0;systemCt=0;constructor(options){super(options);this.load(this);if(options?.systems)for(const key in options.systems){this.addSystem(options.systems[key],void 0,void 0,void 0,void 0,options.order)}if(options?.entities){for(const key in options.entities){this.addEntity(options.entities[key],options.entities[key].components)}}}updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};stop=()=>{this.animating=false};start=filter=>{this.animateEntities(filter)};addEntities=(prototype,components={},count=1)=>{let i2=0;let newEntities={};while(i2{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};removeEntities(entities){if(!Array.isArray(entities))entities=Object.keys(entities);entities.forEach(t2=>{this.removeEntity(t2)})}removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};bufferValues=(entities,property,keys2,buffer)=>{if(!Array.isArray(keys2)&&typeof keys2==="object")keys2=Object.keys(keys2);if(!buffer){let entkeys=Object.keys(entities);if(keys2)buffer=new Float32Array(entkeys.length*keys2.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys2=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys2.length)}else buffer=new Float32Array(entkeys.length)}}let i2=0;for(const key in entities){if(entities[key][property]){if(keys2){for(let j=0;j{combinedHTML+=string;if(args[i2]instanceof HTMLElement){combinedHTML+=``}else if(args[i2]!==void 0){combinedHTML+=args[i2]}};strings.forEach(withStr);template.innerHTML=combinedHTML;let dummyNodes=Array.from(template.content.querySelectorAll(`#${rand}`));const withArg=(arg,i2)=>{if(arg instanceof HTMLElement){let dummyNode=dummyNodes[i2];if(dummyNode){dummyNode.parentNode.replaceChild(arg,dummyNode)}}};args.forEach(withArg);if(elm){elm.appendChild(template.content);return elm}return template.content}}function xml(strings,...args){return function append(elm,namespace="http://www.w3.org/1999/xhtml"){let parser=new DOMParser;let serializer=new XMLSerializer;let xmlDoc=parser.parseFromString('',"application/xml");let template=xmlDoc.createElement("template");xmlDoc.documentElement.appendChild(template);for(let i2=0;i2{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if(node.tagName||node.__element){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var dummy=html``;var DOMElement=class extends HTMLElement{useShadow=false;FRAGMENT;STYLE;attachedShadow=false;static get tag(){return this.name.toLowerCase()+"-"}obsAttributes=["props","options","onchanged","onresize","ondelete","oncreate","template"];props={};static addElement(tag=this.tag,cls=this,extend=void 0){addCustomElement(cls,tag,extend)}attributeChangedCallback=(name2,old,val)=>{if(name2==="onchanged"){let onchanged=val;if(typeof onchanged==="string")onchanged=parseFunctionFromText2(onchanged);if(typeof onchanged==="function"){this.onchanged=onchanged;this.state.data.props=this.props;this.state.unsubscribeTrigger("props");this.state.subscribeTrigger("props",this.onchanged);let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)})}}else if(name2==="onresize"){let onresize=val;if(typeof onresize==="string")onresize=parseFunctionFromText2(onresize);if(typeof onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this.props,this)};this.onresize=onresize;window.addEventListener("resize",this.ONRESIZE)}}else if(name2==="ondelete"){let ondelete=val;if(typeof ondelete==="string")ondelete=parseFunctionFromText2(ondelete);if(typeof ondelete==="function"){this.ondelete=()=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");if(ondelete)ondelete(this.props,this)}}}else if(name2==="oncreate"){let oncreate=val;if(typeof oncreate==="string")oncreate=parseFunctionFromText2(oncreate);if(typeof oncreate==="function"){this.oncreate=oncreate}}else if(name2==="renderonchanged"){let rpc=val;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!=false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}else if(name2==="props"){let newProps=val;if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props})}else if(name2==="template"){let template=val;this.template=template;this.render(this.props);let created=new CustomEvent("created",{detail:{props:this.props}});this.dispatchEvent(created)}else{let parsed=val;if(name2.includes("eval_")){name2=name2.split("_");name2.shift();name2=name2.join();parsed=parseFunctionFromText2(val)}else if(typeof val==="string"){try{parsed=JSON.parse(val)}catch(err){parsed=val}}this[name2]=parsed;if(name2!=="props"&&this.props)this.props[name2]=parsed}};connectedCallback(){if(!this.props)this.props={};let newProps=this.getAttribute("props");if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props});Array.from(this.attributes).forEach(att=>{let name2=att.name;let parsed=att.value;if(name2.includes("eval_")||name2.includes("()")){if(name2.includes("eval_"))name2=name2.split("_");else if(name2.includes("()"))name2=name2.substring(0,name2.indexOf("("));name2.shift();name2=name2.join();parsed=parseFunctionFromText2(att.value)}else if(typeof att.value==="string"){try{parsed=JSON.parse(att.value)}catch(err){parsed=att.value}}if(!this[name2]){Object.defineProperties(this,att,{value:parsed,writable:true,get(){return this[name2]},set(val){this.setAttribute(name2,val)}})}this[name2]=parsed;if(name2!=="props")this.props[name2]=parsed;this.obsAttributes.push(name2)});let resizeevent=new CustomEvent("resized",{detail:{props:this.props,self:this}});let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});let deleted=new CustomEvent("deleted",{detail:{props:this.props,self:this}});let created=new CustomEvent("created",{detail:{props:this.props,self:this}});this.render(this.props);this.dispatchEvent(created);this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)});if(typeof this.onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this,this.props);this.dispatchEvent(resizeevent)};window.addEventListener("resize",this.ONRESIZE)}if(typeof this.ondelete==="function"){let ondelete=this.ondelete;this.ondelete=(props=this.props)=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");this.dispatchEvent(deleted);ondelete(this,props)}}if(typeof this.onchanged==="function"){this.state.data.props=this.props;this.state.subscribeTrigger("props",this.onchanged)}if(this.renderonchanged){let rpc=this.renderonchanged;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!==false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}}constructor(){super()}delete=()=>{this.remove();if(typeof this.ondelete==="function")this.ondelete(this.props)};render=(props=this.props)=>{const t2=document.createElement("template");let usingHTMLFunction=this.template.prototype?.constructor?.name==dummy.prototype.constructor.name;if(typeof this.template==="function"){if(usingHTMLFunction){this.template(t2.content)}else this.templateResult=this.template(this,props)}else this.templateResult=this.template;if(this.styles)this.templateResult=`${this.templateResult}`;if(!usingHTMLFunction){if(typeof this.templateResult==="string")t2.innerHTML=this.templateResult;else if(this.templateResult instanceof HTMLElement||this.templateResult instanceof DocumentFragment){if(this.templateResult.parentNode){this.templateResult.parentNode.removeChild(this.templateResult)}t2.content.appendChild(this.templateResult)}}const fragment=t2.content;if(this.FRAGMENT){if(this.useShadow){if(this.STYLE)this.shadowRoot.removeChild(this.STYLE);this.FRAGMENT.forEach(c=>{this.shadowRoot.removeChild(c)})}else this.FRAGMENT.forEach(c=>{this.removeChild(c)})}if(this.useShadow){if(!this.attachedShadow){this.attachShadow({mode:"open"}).innerHTML="";this.attachedShadow=true}if(this.styles){let style=document.createElement("style");style.textContent=this.styles;this.shadowRoot.prepend(style);this.STYLE=style}let len=fragment.childNodes.length;this.shadowRoot.prepend(fragment);this.FRAGMENT=Array.from(this.shadowRoot.childNodes).slice(0,len)}else{let len=fragment.childNodes.length;this.prepend(fragment);this.FRAGMENT=Array.from(this.childNodes).slice(0,len)}let rendered=new CustomEvent("rendered",{detail:{props:this.props,self:this}});this.dispatchEvent(rendered);if(this.oncreate)this.oncreate(this,props)};state={pushToState:{},data:{},triggers:{},setState(updateObj){Object.assign(this.pushToState,updateObj);if(Object.keys(this.triggers).length>0){for(const prop of Object.getOwnPropertyNames(this.triggers)){if(this.pushToState[prop]){this.data[prop]=this.pushToState[prop];delete this.pushToState[prop];this.triggers[prop].forEach(obj=>{obj.onchanged(this.data[prop])})}}}return this.pushToState},subscribeTrigger(key,onchanged=res=>{}){if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({idx:l,onchanged});return this.triggers[key].length-1}else return void 0},unsubscribeTrigger(key,sub){let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.idx===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);return true}}},subscribeTriggerOnce(key=void 0,onchanged=value=>{}){let sub;let changed=value=>{onchanged(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)}}};function addCustomElement(cls,tag,extend=null){try{if(extend){if(tag)window.customElements.define(tag,cls,{extends:extend});else window.customElements.define(cls.name.toLowerCase()+"-",cls,{extends:extend})}else{if(tag)window.customElements.define(tag,cls);else window.customElements.define(cls.name.toLowerCase()+"-",cls)}}catch(err){}}function parseFunctionFromText2(method){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf(")");return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;try{if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch(err){newFunc=(0,eval)(method)}}}}catch(err){}return newFunc}var wchtmlloader=(node,parent,graph,roots,properties,key)=>{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if((node.tagName||node.__element)&&!node.__props&&!node.__template){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}else if(typeof node.__css==="string"){node.__template+=``;delete node.__css}const registerElement=(node2,tagNameOverride)=>{if(isNativeClass(node2))node2=new node2;else if(typeof node2==="function"&&!node2.__node)node2=node2();class CustomElement extends DOMElement{props=node2.props;styles=node2.__css;useShadow=node2.useShadow;template=node2.__template;oncreate=node2.__onrender;onresize=node2.__onresize;ondelete=node2.__onremove;renderonchanged=node2.__renderonchanged}if(tagNameOverride?.includes("-"))node2.tagName=tagNameOverride;else if(node2.__element)node2.tagName=node2.__element;if(!node2.tagName)node2.tagName=`element${Math.floor(Math.random()*1e15)}-`;CustomElement.addElement(node2.tagName)};if("__components"in node){if(Array.isArray(node.__components))node.__components.forEach(c=>registerElement(c));else Object.entries(node.__components).forEach(([k,c])=>registerElement(c,k.includes("-")?k:void 0))}if("__template"in node){if(typeof node.__renderonchanged==="function"){let renderonchanged=node.__renderonchanged;node.__renderonchanged=element=>{renderonchanged.call(element.node,element)}}registerElement(node);node.__props=document.createElement(node.tagName);let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}}}else if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender&&!(node.__props instanceof DOMElement)&&!node.__template)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return new sjcl.hash.sha256().update(a).finalize()};sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=sjcl_default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};static generateSecret(){return sjcl_default.codec.base64.fromBits(sjcl_default.random.randomWords(8,10))}encrypt(message,key){message=sjcl_default.encrypt(key,message).cipher;return message}decrypt(message,key){message=sjcl_default.decrypt(key,message);return message}encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=sjcl_default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message}};var HTTPfrontend=class _HTTPfrontend extends Service{name="http";fetchProxied=false;listening={};constructor(options,path,fetched){super(options);this.load(this);this.listen(path,fetched)}static request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};GET=(url2="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url:url2,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{let obj=message;if(typeof obj==="object"&&!obj.byteLength){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url2);return this.POST(message,url2)};transponder=(url2,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url:url2,data:message,responseType:type,onload:ev=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}}};var SSEfrontend=class extends Service{name="sse";eventsources={};connections={eventsources:this.eventsources};constructor(options){super(options);this.load(this)}openSSE=options=>{let source=new EventSource(options.url);let sse={source,type:"eventsource",...options};if(!("keepState"in options))options.keepState=true;if(!options.events)options.events={};let close;if(options.events.close){close=options.events.close}options.events.close=ev=>{if(sse.onclose)sse.onclose(ev,sse);if(close)close(ev,sse);delete this.eventsources[options.url]};let open;if(options.events.open){open=options.events.open}options.events.open=ev=>{if(sse.onopen)sse.onopen(ev,sse);if(open)open(ev,sse)};let error;if(options.events.error){error=options.events.error}options.events.error=ev=>{if(sse.onerror)sse.onerror(ev,sse);if(error)error(ev,sse)};let message;if(options.events.message){message=options.events.message}if(!sse.onmessage){sse.onmessage=(ev,sse2)=>{let data=ev.data;if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"&&sse2){sse2._id=data.args;options.events.message=(e,sse3)=>{const result2=this.receive(e.data,sse3);if(options.keepState)this.setState({[options.url]:e.data})}}}}}const result=this.receive(ev.data,sse2);if(options.keepState)this.setState({[options.url]:data})}}options.events.message=ev=>{if(sse.onmessage)sse.onmessage(ev,sse);if(message)message(ev,sse)};if(!options.events.error)options.events.error=(ev,sse2)=>{this.terminate(sse2);delete this.eventsources[options.url]};if(options.events){if(!options.evoptions)options.evoptions=false;for(const key in options.events){if(typeof options.events[key]!=="function"){options.events[key]=ev=>{const result=this.receive(ev.data,sse);if(options.keepState)this.setState({[options.url]:result})}}else{let l=options.events[key];options.events[key]=ev=>{l(ev,sse)}}source.addEventListener(key,options.events[key],options.evoptions)}}let send=message2=>{return this.transmit(message2,options.url)};let request=(message2,method,sessionId)=>{return this.request(message2,options.url,method,sessionId)};let post=(route,args,method)=>{let message2={route,args};if(method)message2.method=method;return this.transmit(message2,options.url)};let run=(route,args,method,sessionId)=>{return this.request({route,args},options.url,method,sessionId)};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSSE(route,options.url,callback,args,key,subInput,sse._id)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options.url)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;this.eventsources[options.url]=sse;return sse};open=this.openSSE;POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="number"||typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{return this.POST(message,url2,"json")};request=(message,url2,method,sessionId)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,url2,callbackId,sessionId]};if(method)req.method=method;let evs=this.eventsources[url2].source;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){evs.removeEventListener("message",onmessage);res(data.args)}}};evs.addEventListener("message",onmessage);this.POST(message,url2,"json")})};runRequest=(message,url2,callbackId,sessionId)=>{let res=this.receive(message);if(url2){if(res instanceof Promise){res.then(r=>{let message2={args:r,callbackId,sessionId};this.POST(message2,url2,"json")})}else{let message2={args:res,callbackId,sessionId};this.POST(message2,url2,"json")}}return res};subscribeSSE=(route,url2,args,key,subInput)=>{if(this.restrict?.[route])return void 0;return this.subscribe(route,res=>{this.POST(res,url2,"json")},args,key,subInput)};subscribeToSSE=(route,url2,callback,args,key,subInput,sessionId)=>{if(url2){this.__node.state.subscribeEvent(url2,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[url2]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.eventsources[url2].run("subscribeSSE",[route,url2,args,key,subInput,sessionId])}};terminate=sse=>{if(typeof sse==="string"){let str2=sse;sse=this.eventsources[sse];delete this.eventsources[str2]}if(!sse)return;if(typeof sse==="object"){if(sse.source){sse=sse.source}if(sse instanceof EventSource){if(sse.readyState!==2)sse.close()}}}};var WSSfrontend=class extends Service{name="wss";sockets={};connections={sockets:this.sockets};constructor(options){super(options);this.load(this)}loadWebSocketRoute=node=>{let wsInfo=this.openWS(node);if(!wsInfo.__ondisconnected){wsInfo.__addOndisconnected(()=>{wsInfo.terminate()})}if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.post(node.callback,args);else return wsInfo.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.send(args);else return wsInfo.request(args)}}}if(!node.__ondisconnected){let ondelete=rt=>{rt?.terminate()};node.__addOndisconnected(ondelete)}return wsInfo};socketloader={"websockets":(node,parent,graph,roots)=>{node._id=node.__node.tag;let ws=this.loadWebSocketRoute(node);Object.assign(node,ws);if(parent&&parent.type==="socket"){let parentWs=this.sockets[parent._id];if(node.parentRoute){parentWs.subscribe(node.parentRoute,node.__operator)}}}};openWS=(options={host:"localhost",port:7e3,path:void 0,protocol:"ws"})=>{let protocol=options.protocol;if(!protocol)protocol="ws";let address=`${protocol}://${options.host}`;if(!("keepState"in options))options.keepState=true;if(options.port)address+=":"+options.port;if(options.path&&!options.path?.startsWith("/"))address+="/";if(options.path)address+=options.path;if(this.sockets[address]?.socket){if(this.sockets[address].socket.readyState===this.sockets[address].socket.OPEN)this.sockets[address].socket.close()}const socket=new WebSocket(address);if(!options.onmessage){if(!options._id){options.onmessage=(data,ws,wsinfo)=>{if(data){if(typeof data==="string"){if(options.debug){console.log("Message from ",address,": ",data)}let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;options.onmessage=(data2,ws2,wsinfo2)=>{if(options.debug){console.log("Message from ",address,": ",data2)}this.receive(data2);if(options.keepState){this.setState({[address]:data2})}}}}}}let res=this.receive(data);if(options.keepState)this.setState({[address]:data})}}else{options.onmessage=(data,ws,wsinfo)=>{if(options.debug){console.log("Message from ",socket.url,": ",data)}this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}}}}if(options.onmessage){socket.addEventListener("message",ev=>{this.sockets[address].onmessage(ev.data,socket,this.sockets[address])})}socket.addEventListener("open",ev=>{if(this.sockets[address].onopen)this.sockets[address].onopen(ev,socket,this.sockets[address])});socket.addEventListener("close",ev=>{let obj=this.sockets[address];let onclose=obj.onclose;delete this.sockets[address];this.remove(address);if(onclose)onclose(ev,socket,obj)});socket.addEventListener("error",ev=>{if(this.sockets[address].onerror)this.sockets[address].onerror(ev,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},this.sockets[address]._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,this.sockets[address]._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSocket(route,this.sockets[address]._id,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(address)};Object.assign(options,{type:"socket",socket,address,send,post,run,request,subscribe,unsubscribe,terminate});if(!(options instanceof GraphNode)){let node=this.add(options);node.__addOndisconnected(function(){terminate()});options=node}this.sockets[address]=options;return options};open=this.openWS;transmit=(data,ws)=>{if(typeof data==="object"&&(data?.route||data?.node||typeof data.arrayBuffer!=="function"&&typeof data.byteLength!=="number")||typeof data==="number")data=JSON.stringify(data);if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}if(ws instanceof WebSocket&&ws?.readyState===1)ws.send(data);return true};terminate=ws=>{let str2;if(!ws){let keys2=Object.keys(this.sockets);for(const key in keys2){this.terminate(key)}}else if(typeof ws==="string"){str2=ws;for(const k in this.sockets){if(k.includes(ws)||this.sockets[k]._id===k){ws=this.sockets[k].socket;break}}}if(ws instanceof WebSocket){if(ws.readyState===ws.OPEN)ws.close();if(this.get(str2?str2:ws.url))this.remove(str2?str2:ws.url)}return true};request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(typeof ws==="string"){for(const s in this.sockets){if(s===ws||this.sockets[s]._id===ws){ws=this.sockets[s].socket;break}}}if(ws){if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))}}return res};subscribeSocket=(route,socket,args,key,subInput)=>{if(this.restrict?.[route])return void 0;if(typeof socket==="string"&&this.sockets[socket]){socket=this.sockets[socket].socket}if(typeof socket==="object"){return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},args,key,subInput)}};subscribeToSocket=(route,socketId,callback,args,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeEvent(socketId,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[socketId]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,args,key,subInput]})}}};var WebRTCfrontend=class extends Service{name="webrtc";rtc={};unanswered={};iceServers=[{urls:["stun:stun.l.google.com:19302"]},{urls:["stun:stun1.l.google.com:19302"]},{urls:["stun:stun2.l.google.com:19302"]},{urls:["stun:stun3.l.google.com:19302"]},{urls:["stun:stun4.l.google.com:19302"]}];connections={rtc:this.rtc};constructor(options,iceServers){super(options);if(iceServers)this.iceServers=iceServers;this.load(this)}openRTC=async options=>{if(!options)options={};if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(!options.config)options.config={iceServers:this.iceServers};if(!this.rtc[options._id]){let rtc=new RTCPeerConnection(options.config);if(!options.channels)options.channels={"data":true};let firstChannel;for(const key in options.channels){firstChannel=key;break}let send=message=>{return this.transmit(message,options._id,options.channels[firstChannel])};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options._id,options.channels[firstChannel])};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let subscribe=(route,callback,args,key,subInput,channelId)=>{return this.subscribeToRTC(route,options._id,channelId?channelId:firstChannel,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.rtc[options._id]={rtc,_id:options._id,request,run,post,send,subscribe,unsubscribe,terminate,graph:this,...options};const setMessageChannelHandle=channel=>{if(!this.rtc[options._id].ondata){this.rtc[options._id].ondata=mev=>{this.receive(mev.data,channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})};channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}else{channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}};if(this.rtc[options._id].channels){for(const channel in this.rtc[options._id].channels){if(this.rtc[options._id].channels[channel]instanceof RTCDataChannel){}else if(typeof this.rtc[options._id].channels[channel]==="object"){this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel,this.rtc[options._id].channels[channel])}else{this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel)}setMessageChannelHandle(this.rtc[options._id].channels[channel])}}rtc.ontrack=ev=>{if(!this.rtc[options._id].receivers)this.rtc[options._id].receivers=[];this.rtc[options._id].receivers.push(ev.receiver);if(!this.rtc[options._id].streams)this.rtc[options._id].streams=[];this.rtc[options._id].streams.push(...ev.streams);let rlength=this.rtc[options._id].receivers.length;let slength=this.rtc[options._id].streams.length;ev.streams.forEach(s=>{s.addEventListener("removetrack",ev2=>{this.rtc[options._id].receivers[rlength]=void 0;this.rtc[options._id].streams[slength]=void 0;if(this.rtc[options._id].removetrack)this.rtc[options._id].removetrack(ev2)})});if(this.rtc[options._id].ontrack)this.rtc[options._id].ontrack(ev)};rtc.ondatachannel=ev=>{this.rtc[options._id].channels[ev.channel.label]=ev.channel;setMessageChannelHandle(ev.channel);if(this.rtc[options._id].ondatachannel)this.rtc[options._id].ondatachannel(ev)};rtc.onicecandidate=ev=>{if(this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate(ev)};rtc.onicecandidateerror=ev=>{if(this.rtc[options._id].onicecandidateerror)this.rtc[options._id].onicecandidateerror(ev)};let initialOffer=this.rtc[options._id].description===void 0;rtc.onnegotiationneeded=async ev=>{if(!initialOffer){const offer=await rtc.createOffer(this.rtc[options._id].offer);if(rtc.signalingState!="stable")return;await rtc.setLocalDescription(offer);if(this.rtc[options._id].onnegotiationneeded)this.rtc[options._id].onnegotiationneeded(ev,rtc.localDescription)}};rtc.oniceconnectionstatechange=ev=>{if(this.rtc[options._id].oniceconnectionstatechange)this.rtc[options._id].oniceconnectionstatechange(ev)};rtc.onconnectionstatechange=ev=>{if(this.rtc[options._id].onconnectionstatechange)this.rtc[options._id].onconnectionstatechange(ev)};rtc.addEventListener("connectionstatechange",ev=>{if(rtc.connectionState==="closed"||rtc.connectionState==="failed"){if(this.rtc[options._id].onclose){this.rtc[options._id].onclose(this.rtc[options._id])}delete this.rtc[options._id]}});if(!this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].candidates)this.rtc[options._id].candidates={};this.rtc[options._id].candidates[`candidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};if(!options.description)return await new Promise((res,rej)=>{this.rtc[options._id].rtc.createOffer(options.offer).then(offer=>this.rtc[options._id].rtc.setLocalDescription(offer)).then(()=>{initialOffer=false;res(this.rtc[options._id])})})}else{Object.assign(this.rtc[options._id],options)}if(options.description){this.rtc[options._id].polite=true;await this.negotiateCall(options._id,options.description,true)}if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);this.rtc[options._id].rtc.addIceCandidate(candidate).catch(console.error)}}return this.rtc[options._id]};open=this.openRTC;addIceCandidate=(rtc,candidate)=>{if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof candidate==="string")candidate=JSON.parse(decodeURIComponent(candidate));if(rtc&&rtc.remoteDescription)return rtc.addIceCandidate(candidate)};receiveCallInformation=async options=>{if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(this.rtc[options._id]){if(options.candidates){for(const key in options.candidates)this.addIceCandidate(this.rtc[options._id].rtc,options.candidates[key]);delete options.candidates}Object.assign(this.rtc[options._id],options)}else if(this.unanswered[options._id]){this.recursivelyAssign(this.unanswered[options._id],options)}else this.unanswered[options._id]=options;return options._id};answerCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return this.openRTC(options)};rejectCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return true};negotiateCall=async(rtc,description,polite)=>{if(typeof rtc==="string"){if(polite===void 0)polite=this.rtc[rtc].description!==void 0;rtc=this.rtc[rtc].rtc}if(typeof description==="string")description=new RTCSessionDescription(JSON.parse(decodeURIComponent(description)));if(description.type==="offer"&&rtc.signalingState!=="stable"){if(!polite)return;await Promise.all([rtc.setLocalDescription({type:"rollback"}),rtc.setRemoteDescription(description)]);return encodeURIComponent(JSON.stringify(rtc.localDescription))}else{await rtc.setRemoteDescription(description)}if(description.type=="offer"){await rtc.setLocalDescription(await rtc.createAnswer());return encodeURIComponent(JSON.stringify(rtc.localDescription))}};createOffer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc].rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createOffer(options.offer).then(offer=>rtc.setLocalDescription(offer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}createAnswer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createAnswer(options.answer).then(answer=>rtc.setLocalDescription(answer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}answerPeer=(rtc,options)=>{if(typeof rtc==="string"){let cpy=Object.assign(this.rtc[rtc],options);delete cpy.description;delete cpy.candidates;Object.assign(this.rtc[rtc],cpy);rtc=this.rtc[rtc]?.rtc}if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(typeof options.description==="string"){options.description=JSON.parse(decodeURIComponent(options.description))}const description=new RTCSessionDescription(options.description);rtc.setRemoteDescription(description).then(()=>{if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);if(this.rtc[options._id])this.rtc[options._id].candidates[prop]=options.candidates[prop];rtc.addIceCandidate(candidate).catch(console.error)}}if(description.type==="offer"){this.rtc[options._id].rtc.createAnswer(options.answer).then(a=>{this.rtc[options._id].rtc.setLocalDescription(a)})}res(this.rtc[options._id]?this.rtc[options._id]:rtc)}).catch(rej)})};createStream=options=>{let stream=new MediaStream;for(const key in options){let track=options[key].track;if(!(track instanceof MediaStreamTrack)&&typeof track==="object"){track=new MediaStreamTrack;track.applyConstraints(options[key].track);stream.addTrack(track)}if(track instanceof MediaStreamTrack){stream.addTrack(track);track.onmute=options[key].onmute;track.onunmute=options[key].onunmute;track.onended=options[key].onended}}return stream};addUserMedia=(rtc,options={audio:true,video:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560}]}},info)=>{return new Promise(async(res,rej)=>{let RTCRtpSenders=[];let stream=await navigator.mediaDevices.getUserMedia(options);if(stream){let tracks=stream.getTracks();tracks.forEach(track=>{let sender=rtc.addTrack(track,stream);if(track.kind==="video"&&info){info.videoSender=sender;info.videoStream=stream}if(track.kind==="audio"&&info){info.audioSender=sender;info.audioStream=stream}RTCRtpSenders.push(sender)});let str2=stream;if(info)info.senders=info.senders?[...info.senders,...RTCRtpSenders]:RTCRtpSenders;res(str2)}})};addTrack=(rtc,track,stream)=>{return rtc.addTrack(track,stream)};removeTrack=(rtc,sender)=>{rtc.removeTrack(sender);return true};addDataChannel=(rtc,name2,options)=>{return rtc.createDataChannel(name2,options)};enableAudio=async(call,audioOptions=true)=>{if(call.audioStream)this.disableAudio(call);let stream=await this.addUserMedia(call.rtc,{audio:audioOptions,video:false},call);if(audioOptions?.deviceId)call.audioSender.deviceId=audioOptions.deviceId;return stream};enableVideo=async(call,videoOptions={optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]},includeAudio=false)=>{if(call.videoStream)this.disableVideo(call);let stream=await this.addUserMedia(call.rtc,{audio:includeAudio,video:videoOptions?videoOptions:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]}},call);if(videoOptions?.deviceId)call.videoSender.deviceId=videoOptions.deviceId;if(includeAudio){if(includeAudio?.deviceId)call.audioSender.deviceId=includeAudio.deviceId;else if(videoOptions?.deviceId)call.audioSender.deviceId=videoOptions.deviceId}return stream};disableAudio(call){if(call.audioSender){call.senders?.find((s,i2)=>{if(call.audioStream?.getAudioTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.audioSender);call.audioSender=void 0}call.audioStream?.getTracks().forEach(track=>{if(track.kind==="audio")track.stop()});call.audioStream=void 0}disableVideo(call){if(call.videoSender){call.senders?.find((s,i2)=>{if(call.videoStream?.getVideoTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.videoSender);call.videoSender=void 0}call.videoStream?.getTracks().forEach(track=>{if(track.kind==="video")track.stop()});call.videoStream=void 0}transmit=(data,id,channel)=>{if(typeof data==="object"&&(data.route||data.node||!data.byteLength&&typeof data.arrayBuffer!=="function")||typeof data==="number")data=JSON.stringify(data);if(!channel&&id){let keys2=Object.keys(this.rtc[id].channels);if(keys2[0])channel=this.rtc[id].channels[keys2[0]]}if(typeof channel==="string"){if(id){channel=this.rtc[id].channels[channel]}else{for(const id2 in this.rtc){if(this.rtc[id2].channels[channel]instanceof RTCDataChannel)this.rtc[id2].channels[channel].send(data)}}}if(channel instanceof RTCDataChannel)channel.send(data);return true};terminate=rtc=>{let tx;if(typeof rtc==="string"){let room=this.rtc[rtc];delete this.rtc[rtc];if(room){tx=room.rtc}}else if(typeof rtc==="object"){tx=rtc.rtc}if(rtc instanceof RTCPeerConnection&&rtc.signalingState!=="closed"){rtc.close()}else if(tx&&tx.signalingState!=="closed"){if(tx)tx.close()}return true};request=(message,channel,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){channel.removeEventListener("message",onmessage);res(data.args)}}};channel.addEventListener("message",onmessage);channel.send(JSON.stringify(req))})};runRequest=(message,channelOrRtcId,callbackId)=>{let res=this.receive(message);if(channelOrRtcId){if(typeof channelOrRtcId==="string"){for(const key in this.rtc){if(key===channelOrRtcId){channelOrRtcId=this.rtc[key].channels.data?this.rtc[key].channels.data:this.rtc[key].channels[Object.keys(this.rtc[key].channels)[0]];break}}}if(res instanceof Promise)res.then(v=>{res={args:v,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res));return res});else{res={args:res,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res))}}return res};subscribeRTC=(route,rtcId,args,key,subInput,channel)=>{if(this.restrict?.[route])return void 0;if(typeof channel==="string"&&this.rtc[rtcId]){channel=this.rtc[rtcId].channels[channel]}else if(!channel){channel=this.rtc[rtcId].channels[Object.keys(this.rtc[rtcId].channels)[0]]}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{channel.send(JSON.stringify({args:r,callbackId:route}))})}else{channel.send(JSON.stringify({args:res,callbackId:route}))}},args,key,subInput)};subscribeToRTC=(route,rtcId,channelId,callback,args,key,subInput)=>{if(typeof channelId==="string"&&this.rtc[rtcId]){let c=this.rtc[rtcId];let channel=c.channels[channelId];if(channel){this.__node.state.subscribeEvent(rtcId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[rtcId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return c.request({route:"subscribeRTC",args:[route,rtcId,args,key,subInput,channelId]})}}}};var browser_default=Worker;var WorkerService=class extends Service{name="worker";workers={};threadRot=0;connections;constructor(options){super();this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.load(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}loadWorkerRoute=(node,routeKey)=>{if(node.workerUrl)node.url=node.workerUrl;if(node._id)node.__node.tag=node._id;if(!node.__node.tag)node.__node.tag=routeKey;node._id=node.__node.tag;let worker;if(this.workers[node._id])worker=this.workers[node._id];else if(node.worker)worker=node.worker;if(!worker){worker=this.addWorker(node)}node.worker=worker;if(!node.__ondisconnected){let ondelete=rt=>{rt.worker?.terminate()};node.__addOndisconnected(ondelete)}if(node.transferFunctions){for(const prop in node.transferFunctions){this.transferFunction(worker,node.transferFunctions[prop],prop)}}if(node.transferClasses){for(const prop in node.transferClasses){this.transferClass(worker,node.transferClasses[prop],prop)}}if(worker){if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.post(node.callback,args);else return worker.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(node.init){worker.run(node.init,node.initArgs,void 0,node.initTransfer)}return worker}};workerloader={"workers":(node,parent,graph,roots)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?._id&&this.workers[rt._id]||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent?.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&roots[rt.__parent]?.worker){roots[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}}return rt}};addDefaultMessageListener=()=>{globalThis.onmessage=ev=>{let result=this.receive(ev.data);if(this.__node.keepState)this.setState({[this.name]:result})}};postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new browser_default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,method,transfer)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,args,key,subInput,blocking)=>{return this.subscribeToWorker(route,options._id,callback,args,key,subInput,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,void 0,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,void 0,workerSubs[key].callback,void 0,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub});console.log(JSON.stringify(workerSubs))}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]).then(console.log)}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev=>{this.receive(ev.data);this.setState({[options._id]:ev.data})};if(!options.onerror){options.onerror=ev=>{console.error(ev.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;let workersettings={worker,__node:{tag:options._id},send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};let node=this.add(workersettings);this.workers[options._id]=node;node.__addOndisconnected(function(){terminate()});return this.workers[options._id]};open=this.addWorker;close=()=>{globalThis.close()};toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof browser_default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys2=Object.keys(this.workers);this.workers[keys2[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys2.length)this.threadRot=0}return message};terminate=worker=>{let onclose;let str2;if(typeof worker==="string"){str2=worker;let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}else if(typeof worker==="object"){if(worker?._id){worker=worker.worker;delete this.workers[worker?._id]}}if(worker instanceof browser_default){worker.terminate();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}return false};establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof browser_default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof browser_default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};runRequest=(message,worker,callbackId,getTransferable=true)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId},transfer)}return res};subscribeWorker=(route,worker,args,key,subInput,blocking,getTransferable=true)=>{if(this.restrict?.[route])return void 0;let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker?.postMessage)worker.postMessage({args:r,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker?.postMessage)worker.postMessage({args:res,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route},transfer)}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,args,key,subInput)};subscribeToWorker=(route,workerId,callback,args,key,subInput,blocking,getTransferable=true)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeEvent(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,args,key,subInput,blocking,getTransferable])}};triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i2=0;i2{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,args,key,subInput,blocking,getTransferable])};unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof sourceWorker==="object"){return sourceWorker.run("unsubscribe",[sourceRoute,sub])}}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name2 of properties){dst[name2]=src[name2]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};var str=String('(()=>{var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}if(typeof WorkerGlobalScope!=="undefined"){const routes={...workerCanvasRoutes};self.onmessage=ev=>{if(ev.data.route){if(Array.isArray(ev.data.args)){routes[ev.data.route](...ev.data.args)}else routes[ev.data.route](ev.data.args)}}}var canvas_worker_default=self;})();\n');var url=URL.createObjectURL(new globalThis.Blob([str],{type:"text/javascript"}));var canvas_worker_default=url;function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText3(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText3(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText3(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText3(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText3(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText3(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText3(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText3(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText3(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText3(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var SessionsService=class extends Service{name="sessions";users={};sessions={oneWay:{},shared:{}};invites={};constructor(options,users){super(options);this.setLoaders(loaders);this.load(this);if(users)this.users=users}getSessionInfo=(sessionIdOrName,userId)=>{if(!sessionIdOrName){return this.sessions.shared}else{if(this.sessions.oneWay[sessionIdOrName]){let s=this.sessions.oneWay[sessionIdOrName];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{oneWay:{[sessionIdOrName]:s}}}}else if(this.sessions.shared[sessionIdOrName]){return{shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};openOneWaySession=(options={},sourceUserId,listenerUserId)=>{if(!options._id){options._id=`oneWay${Math.floor(Math.random()*1e15)}`;if(this.sessions.oneWay[options._id]){delete options._id;this.openOneWaySession(options,sourceUserId)}}if(options._id&&sourceUserId&&this.users[sourceUserId]){if(sourceUserId){if(!options.settings)options.settings={listener:sourceUserId,source:sourceUserId,propnames:{latency:true},admins:{[sourceUserId]:true},ownerId:sourceUserId};if(!options.settings.listener)options.settings.listener=listenerUserId?listenerUserId:sourceUserId;if(!options.settings.source)options.settings.source=sourceUserId;if(!this.users[sourceUserId].sessions)this.users[sourceUserId].sessions={};this.users[sourceUserId].sessions[options._id]=options}if(!options.data)options.data={};if(options.onopen)options.onopen(options);if(this.sessions.oneWay[options._id]){return this.updateSession(options,sourceUserId)}else if(options.settings?.listener&&options.settings.source)this.sessions.oneWay[options._id]=options}return options};openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;return this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={oneWay:{},shared:{}};if(!options.settings.name)options.name=options.id;if(options.onopen)options.onopen(options);if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};open=(options,userId)=>{if(options.listener)this.openOneWaySession(options,userId);else this.openSharedSession(options,userId)};updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.oneWay[options._id];if(!session)session=this.sessions.shared[options._id];if(session&&userId){if(session.settings&&(session?.settings.source===userId||session.settings.admins?.[userId]||session.settings.moderators?.[userId]||session.settings.ownerId===userId)){return this.recursivelyAssign(session,options)}}else if(options.settings?.source){return this.openOneWaySession(options,userId)}else return this.openSharedSession(options,userId)}return false};joinSession=(sessionId,userId,options,remoteUser=true)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(!sesh)sesh=this.sessions.oneWay[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;sesh.settings.newUser=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options?.source||options?.listener){sesh=this.openOneWaySession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options){sesh=this.openSharedSession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}return false};inviteToSession=(session,userInvited,inviteEndpoint,remoteUser=true)=>{if(remoteUser&&this.users[userInvited]?.send){this.users[userInvited]?.send({route:"receiveSessionInvite",args:[session,userInvited,inviteEndpoint]})}else{this.receiveSessionInvite(session,userInvited,inviteEndpoint)}};receiveSessionInvite=(session,userInvited,endpoint)=>{if(!this.invites[userInvited])this.invites[userInvited]={};let id=typeof session==="string"?session:session._id;this.invites[userInvited][id]={session,endpoint};return id};acceptInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;let invite=this.invites[userInvited]?.[id];let endpoint;if(invite){session=invite.session;endpoint=invite.endpoint;delete this.invites[userInvited]?.[id]}return new Promise((res,rej)=>{if(!id)res(false);if(remoteUser&&endpoint&&this.users[endpoint]?.send){let resolved;let timeout=setTimeout(()=>{if(!resolved){this.unsubscribe("joinSession",subbed);rej(new Error("Session join timed out"))}},1e4);let subbed=this.subscribe("joinSession",result=>{if(typeof result==="object"&&result?._id===id){if(result.setting?.users?.includes(userInvited)){this.unsubscribe("joinSession",subbed);resolved=true;if(timeout)clearTimeout(timeout);res(result)}}});this.users[endpoint]?.send({route:"joinSession",args:[id,userInvited,void 0,true]})}else res(this.joinSession(id,userInvited,typeof session==="object"?session:void 0))})};rejectInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;if(this.invites[userInvited]?.[id]){let endpoint=this.invites[userInvited][id].endpoint;delete this.invites[userInvited][id];if(remoteUser&&endpoint&&this.users[endpoint]?.send){this.users[endpoint].send({route:"rejectInvite",args:[id,userInvited]})}return true}};leaveSession=(session,userId,clear=true,remoteUser=true)=>{let sessionId;if(typeof session==="string"){sessionId=session;session=this.sessions.oneWay[sessionId];if(!session)session=this.sessions.shared[sessionId]}else sessionId=session._id;if(session){if(this.sessions.oneWay[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.oneWay[sessionId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){this.swapHost(session,void 0,true);delete session.data.shared[userId]}}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}return true}return false};deleteSession=(session,userId,remoteUsers=true)=>{if(typeof session==="string"){let id=session;session=this.sessions.oneWay[id];if(!session)session=this.sessions.shared[id]}if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user]?.sessions)delete this.users[user].sessions[session._id];if(this.users[user]?.sessionSubs)delete this.users[user].sessionSubs[session._id];if(remoteUsers){if(session.users){for(const key in session.users){if(this.users[key]?.send)this.users[key].send({route:"unsubscribeFromSession",args:[session._id,key]})}}else if(session.listener){if(this.users[session.listener]?.send)this.users[session.listener].send({route:"unsubscribeFromSession",args:[session._id,session.listener]})}else if(this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId]})}}else{this.unsubsribeFromSession(session,user)}}if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.oneWay[session._id];if(session.onclose)session.onclose(session)}}return true};getFirstMatch(obj1,obj2){for(const i2 in obj1){if(i2 in obj2)return i2}return false}swapHost=(session,newHostId,adoptData=true,remoteUser=true)=>{if(typeof session==="string"){if(this.sessions.oneWay[session])session=this.sessions.oneWay[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){let oldHost=session.settings.host;delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];if(adoptData&&oldHost&&session.settings.inheritHostData!==false){if(session.data?.shared[oldHost]){if(session.data?.shared[oldHost]){session.data.shared[session.settings.host]=Object.assign(session.data.shared[session.settings.host]?session.data.shared[session.settings.host]:{},session.data.shared[oldHost]);if(remoteUser){}}}}return true}return false};subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}let user=this.users[userId];if(!user)return void 0;if(!user.sessionSubs)user.sessionSubs={};if(!user.sessionSubs[session._id])user.sessionSubs[session._id]={};if(onmessage)user.sessionSubs[session._id].onmessage=onmessage;if(onopen)this.sessionSubs[userId][session._id].onopen=onopen;if(onclose)user.sessionSubs[session._id].onclose=onclose;if(typeof onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)this.sessionSubs[userId][session._id].onopen(session,user);this.unsubscribe("joinSession",sub)});user.sessionSubs[session._id].onopenSub=sub}return session};unsubsribeFromSession=(session,userId,clear=true)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}const clearSessionSubs=(Id,s)=>{let u2=this.users[Id];if(!u2)return void 0;if(u2.sessionSubs?.[s._id]){if(u2.sessionSubs[s._id].onopenSub){this.unsubscribe("joinSession",u2.sessionSubs[s._id].onopenSub)}}if(u2.sessionSubs[s._id].onclose)u2.sessionSubs[s._id].onclose(s,u2);delete u2.sessionSubs[s._id]};if(userId){clearSessionSubs(userId,session)}else{for(const key in this.users){clearSessionSubs(key,session)}}if(clear){if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.shared[session._id]}};sessionUpdateCheck=(sessionHasUpdate,transmit=true)=>{let updates={oneWay:{},shared:{}};for(const session in this.sessions.oneWay){const sesh=this.sessions.oneWay[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.oneWay[session];continue}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(prop in this.users[sesh.source]){if(this.sessions.oneWay[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(prop in this.users[sesh.source]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.oneWay[session]?.data&&prop in this.sessions.oneWay[session]?.data)delete this.sessions.oneWay[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.oneWay[session].data,updateObj.data);updates.oneWay[sesh._id]=updateObj;if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.onhasupdate(sesh,updateObj)}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const oneWayData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}else if(sesh.settings.newUser){updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;sesh.settings.newUser=false}if(user!==sesh.settings.host){oneWayData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data?.oneWay&&!(user in sesh.data.oneWay)){if(typeof this.users[user][prop]==="object")oneWayData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else oneWayData[user][prop]=this.users[user][prop]}else if(typeof oneWayData[user][prop]==="object"&&sesh.data){if(prop in this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))oneWayData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.oneWay?.[prop]!==this.users[user][prop])oneWayData[user][prop]=this.users[user][prop]}else if(sesh.data?.oneWay?.[user]&&prop in sesh.data?.oneWay?.[user])delete sesh.data.oneWay[user][prop]}if(Object.keys(oneWayData[user]).length===0)delete oneWayData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user]))sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}}}if(Object.keys(oneWayData).length>0){updateObj.data.oneWay=oneWayData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user]?.[prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user]?.[prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.oneWay){updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){Object.assign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.oneWay){Object.assign(this.sessions.shared[session].data?.oneWay,updateObj.data.oneWay)}if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.settings.onhasupdate(sesh,updateObj)}}if(Object.keys(updates.oneWay).length===0)delete updates.oneWay;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};transmitSessionUpdates=updates=>{let users={};if(updates.oneWay){for(const s in updates.oneWay){let session=this.sessions.oneWay[s];if(session?.settings){let u2=session.settings.listener;if(!users[u2])users[u2]={};users[u2].oneWay[s]=updates.oneWay[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){for(const u2 in session.settings.users){if(!users[u2])users[u2]={};users[u2].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u2 in users){message.args=[u2,users[u2]];if(this.users[u2]?.send)this.users[u2].send(JSON.stringify(message));this.setState({[u2]:Object.create(message)})}return users};receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(user){if(!user.sessions)user.sessions={oneWay:{},shared:{}};if(!user.sessionSubs)user.sessionSubs={}}if(update.oneWay){for(const key in update.oneWay){this.recursivelyAssign(this.sessions.oneWay[key].data,update.oneWay[key].data);if(this.sessions.oneWay[key]?.settings.onmessage)this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key],update.oneWay[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}if(update.shared){for(const key in update.shared){if(update.shared[key].settings.users)this.sessions.shared[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)this.sessions.shared[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.oneWay)this.recursivelyAssign(this.sessions.shared[key].data.oneWay,update.shared[key].data.oneWay);if(update.shared[key].data.shared)this.recursivelyAssign(this.sessions.shared[key].data.shared,update.shared[key].data.shared);if(this.sessions.shared[key]?.settings.onmessage)this.sessions.shared[key].settings.onmessage(this.sessions.shared[key],update.shared[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}return user}};getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};userUpdateCheck=(user,onupdate)=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});if(onupdate){onupdate(user,updateObj)};return updateObj}}return void 0};setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};STREAMLATEST=0;STREAMALLLATEST=1;streamSettings={};streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};setStreamFunc=(name2,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name2].settings[key])this.streamSettings[name2].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name2].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name2].settings[key].callback=callback;if(!this.streamSettings[name2].settings[key].callback)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;return true};addStreamFunc=(name2,callback=data=>{})=>{this.streamFunctions[name2]=callback};setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};removeStream=(streamName,key)=>{if(streamName&&this.streamSettings[streamName]&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}}};var Router=class extends Service{name="router";connections={};sources={};services={};serviceConnections={};users={};userTimeout=1e4;order;constructor(options){super(options);this.load(this);if(options){if(options.order)this.order=options.order;if(options.timeout)this.userTimeout=options.timeout;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}addUser=async(info,connections,config,receiving)=>{let user;if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}if(this.users[info._id]){user=this.users[info._id]}else{user=Object.assign({},info)}if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>this.userTimeout){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}if(!this.users[info._id]){let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let sendAll=(message,...a)=>{let connections2=this.getConnections(user._id,"send");for(const key in connections2)if(connections2[key]?.send)return connections2[key].send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let requestAll=(message,method,...a)=>{let connections2=this.getConnections(user._id,"request");let results=[];for(const key in connections2)if(connections2[key]?.request)results.push(connections2[key].request(message,method,...a));return Promise.all(results)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let postAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"post");for(const key in connections2)if(connections2[key]?.post)connections2[key].post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let runAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"run");let results=[];for(const key in connections2)if(connections2[key]?.run)results.push(connections2[key].run(route,args,method,...a));return Promise.all(results)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let subscribeAll=(route,callback,...a)=>{let connections2=this.getConnections(user._id,"subscribe");let results=[];for(const key in connections2)if(connections2[key]?.post)results.push(connections2[key].subscribe(route,callback,...a));return Promise.all(results)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let unsubscribeAll=(route,subs,...a)=>{let connections2=this.getConnections(user._id,"unsubscribe");let results=[];for(const key in connections2)if(connections2[key]?.post&&subs[key])results.push(connections2[key].unsubscribe(route,subs[key],...a));return Promise.all(results)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;user.sendAll=sendAll;user.requestAll=requestAll;user.postAll=postAll;user.runAll=runAll;user.subscribeAll=subscribeAll;user.unsubscribeAll=unsubscribeAll;user.terminateAll=terminate;this.users[user._id]=user}if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i2)=>{if(connections[k]?._id){connectionIds[`${i2}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}getConnection=(sourceId,hasMethod,connectionId)=>{if(this.connections[sourceId]){return this.connections[sourceId]}else if(this.sources[sourceId]){if(hasMethod?.includes("All"))return this.users[sourceId];if(connectionId){if(hasMethod){if(this.sources[sourceId][connectionId]?.[hasMethod])return this.sources[sourceId][connectionId]}else if(this.sources[sourceId][connectionId])return this.sources[sourceId][connectionId];else return void 0}else if(this.order){for(let i2=0;i2{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}return found}};runConnection=async(userId,method,args,connectionId)=>{let sendTo;if(method.indexOf("All")>-1){sendTo=this.users[userId]}else{sendTo=this.getConnection(userId,method,connectionId)}if(sendTo){let res=sendTo[method](...args);res=await res;return res}};subscribeThroughConnection=(route,remoteRelay,remoteEndpoint,callback,...args)=>{if(typeof remoteRelay==="string"){remoteRelay=this.getConnection(remoteRelay,"run")}if(typeof remoteRelay==="object")return new Promise((res,rej)=>{remoteRelay.run("routeConnections",[route,remoteEndpoint,remoteRelay._id,...args]).then(sub=>{this.__node.state.subscribeEvent(remoteEndpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[remoteEndpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};addConnection=(options,source,autoRemove=true)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.connection=options.connection;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await connectionHasId(info,this.userTimeout)}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await connectionHasId(connection,this.userTimeout)}if(connection._id)return this.addConnection({connection,service},source)}}};terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}}};function connectionHasId(connection,timeout=1e4){return new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>timeout){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connection timed out:",er)})}export{Callable,DOMElement,E2EEService,ECSService,ElementProxyReceiver,EventDispatcher,EventHandler,Graph,GraphNode,HTTPfrontend,ProxyManager,Renderer,Router,SSEfrontend,Service,SessionsService,WSSfrontend,WebRTCfrontend,WorkerService,addCustomElement,animate,backprop,bindListener,branching,clearCanvas,connectionHasId,drawFrame,eventHandlers,getAllProperties,getCallbackFromString,getCanvas,getFnParamNames,getFunctionHead,html,htmlloader,initCanvas,initProxyElement,instanceObject,isFunction,isNativeClass,isTypedArray,loaders,loop,methodstrings,nodeTemplates,parseFunctionFromText,proxyElementWorkerRoutes,reconstructObject,recursivelyAssign2 as recursivelyAssign,recursivelyStringifyFunctions,remoteGraphRoutes,setDraw,setProps,setupCanvas,spliceTypedArray,startAnim,state,stopAnim,stringifyFast,stringifyWithCircularRefs,stringifyWithFunctionsAndCircularRefs,substitute__operator,transferCanvas,transformListenerResult,triggerListenerOncreate,updateCanvas,wchtmlloader,workerCanvasRoutes,wrapArgs,xml}; diff --git a/dist/index.js b/dist/index.js deleted file mode 100644 index 184ad865..00000000 --- a/dist/index.js +++ /dev/null @@ -1 +0,0 @@ -(()=>{var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i2=l-1;i2>=0;i2--){run(this.triggers[statesubKey][i2].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i2=l-1;i2>=0;i2--){fn(this.triggers[key][i2])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.sub===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps2=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys2=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys2){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps2();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys2=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys2.push(...nonArrowFunctions);keys2=keys2.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys2){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys2=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t2=>{for(const key in t2){this.unsubscribe(t2[key]);this.delete(t2[key].__node.tag);delete this.__node.roots[t2[key].__node.tag];this.delete(key);delete this.__node.roots[key];t2[key].__node.tag=t2[key].__node.tag.substring(t2[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t2[key])}t2[key].__callDisconnected();if(t2[key].__children){recursiveRemove(t2[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i2)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i2]={__callback:inp=>{return inp},__args:void 0,idx:i2}}else if(typeof a==="string"){args[i2]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i2}}else if(typeof a==="function"){let fn2=a;args[i2]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i2}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i2}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i2}}else{input={__callback:input,__args:void 0,idx:i2}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i2}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i2}}}return input};args[i2]=recursivelyCreateCallback(a)}else{let arg=a;args[i2]={__callback:()=>{return arg},__args:void 0,idx:i2}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i2=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i2,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function getFnParamNames(fn){if(typeof fn!=="string")fn=fn.toString();const arrowMatch=fn.match(/\(?[^]*?\)?\s*=>/);if(arrowMatch)return arrowMatch[0].replace(/[()\s]/gi,"").replace("=>","").split(",");const match=fn.match(/\([^]*?\)/);return match?match[0].replace(/[()\s]/gi,"").split(","):[]}var getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}function reconstructObject(json="{}"){try{let parsed=typeof json==="string"?JSON.parse(json):json;const parseObj=obj=>{for(const prop in obj){if(typeof obj[prop]==="string"){let funcParsed=parseFunctionFromText(obj[prop]);if(typeof funcParsed==="function"){obj[prop]=funcParsed}}else if(typeof obj[prop]==="object"){parseObj(obj[prop])}}return obj};return parseObj(parsed)}catch(err){console.error(err);return void 0}}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs3(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value==="function"?value.toString():value,path.join("."))}}}return typeof value==="function"?value.toString():value}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str2;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str2=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str2=properties.toString();else if(typeof properties==="string")str2=properties;if(str2){if(connection.run)return connection.run("setNode",[str2]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str2},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str2}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(template);if(node){nodeTemplates[node.__node.tag]=template;return node.__node?.tag}else return false}else return false},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str2=recursivelyStringifyFunctions(properties);return str2},getListenerJSON:function(){const triggers=this.__node.state.triggers;let result={};for(const key in triggers){triggers[key].forEach(trigger=>{let t2=trigger;if(!result[t2.target])result[t2.target]={};let l=t2.source+(t2.key?"."+t2.key:"");result[t2.target][l]={__callback:t2.__callback};if(t2.__args)result[t2.target][l].__args=t2.__args;if(t2.subInput)result[t2.target][l].subInput=t2.subInput})}return result},makeRootTransferrable:function(){let roots={};for(const r in this.__node.graph.__node.roots){let properties=this.__node.graph.__node.roots[r];if(typeof properties==="function"){roots[r]=properties.toString()}else if(typeof properties!=="object"){roots[r]=properties}else{roots[r]={};let keys2=Object.getOwnPropertyNames(properties).filter(v=>!objProps2.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter(v=>!objProps2.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(typeof properties[key]==="function"){roots[r][key]=properties[key].toString()}else if(typeof properties[key]==="object")roots[r][key]=stringifyWithFunctionsAndCircularRefs(properties[key]);else roots[r][key]=properties[key]}}}return roots},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key of properties){if(typeof node[key]==="function"){let str2=node[key].toString();let isNative=str2.indexOf("[native code]")>-1;result[key]={type:"function",args:getFnParamNames(node[key]),native:isNative}}else result[key]=typeof node[key]}return result}return void 0},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]?.type==="function"){if(props[key].native||props[key].args){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{proxy[key]=()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})}}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};if(connection.run)return connection.run("receiveClass",[str2,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str2,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str2,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str2=fn.toString();let message={route:"setNode",args:[str2,fnName]};if(connection.run)return connection.run("setNode",[str2,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str2,fnName]},void 0);return new Promise(r=>r(fnName))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str2,fnName]}));return new Promise(r=>r(fnName))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var objProps2=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var ECSService=class extends Service{entities={};systems={};entityMap=new Map;entityKeyMap=new Map;order=[];animating=false;entityCt=0;systemCt=0;constructor(options){super(options);this.load(this);if(options?.systems)for(const key in options.systems){this.addSystem(options.systems[key],void 0,void 0,void 0,void 0,options.order)}if(options?.entities){for(const key in options.entities){this.addEntity(options.entities[key],options.entities[key].components)}}}updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};stop=()=>{this.animating=false};start=filter=>{this.animateEntities(filter)};addEntities=(prototype,components={},count=1)=>{let i2=0;let newEntities={};while(i2{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};removeEntities(entities){if(!Array.isArray(entities))entities=Object.keys(entities);entities.forEach(t2=>{this.removeEntity(t2)})}removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};bufferValues=(entities,property,keys2,buffer)=>{if(!Array.isArray(keys2)&&typeof keys2==="object")keys2=Object.keys(keys2);if(!buffer){let entkeys=Object.keys(entities);if(keys2)buffer=new Float32Array(entkeys.length*keys2.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys2=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys2.length)}else buffer=new Float32Array(entkeys.length)}}let i2=0;for(const key in entities){if(entities[key][property]){if(keys2){for(let j=0;j{combinedHTML+=string;if(args[i2]instanceof HTMLElement){combinedHTML+=``}else if(args[i2]!==void 0){combinedHTML+=args[i2]}};strings.forEach(withStr);template.innerHTML=combinedHTML;let dummyNodes=Array.from(template.content.querySelectorAll(`#${rand}`));const withArg=(arg,i2)=>{if(arg instanceof HTMLElement){let dummyNode=dummyNodes[i2];if(dummyNode){dummyNode.parentNode.replaceChild(arg,dummyNode)}}};args.forEach(withArg);if(elm){elm.appendChild(template.content);return elm}return template.content}}function xml(strings,...args){return function append(elm,namespace="http://www.w3.org/1999/xhtml"){let parser=new DOMParser;let serializer=new XMLSerializer;let xmlDoc=parser.parseFromString('',"application/xml");let template=xmlDoc.createElement("template");xmlDoc.documentElement.appendChild(template);for(let i2=0;i2{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if(node.tagName||node.__element){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var dummy=html``;var DOMElement=class extends HTMLElement{useShadow=false;FRAGMENT;STYLE;attachedShadow=false;static get tag(){return this.name.toLowerCase()+"-"}obsAttributes=["props","options","onchanged","onresize","ondelete","oncreate","template"];props={};static addElement(tag=this.tag,cls=this,extend=void 0){addCustomElement(cls,tag,extend)}attributeChangedCallback=(name2,old,val)=>{if(name2==="onchanged"){let onchanged=val;if(typeof onchanged==="string")onchanged=parseFunctionFromText2(onchanged);if(typeof onchanged==="function"){this.onchanged=onchanged;this.state.data.props=this.props;this.state.unsubscribeTrigger("props");this.state.subscribeTrigger("props",this.onchanged);let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)})}}else if(name2==="onresize"){let onresize=val;if(typeof onresize==="string")onresize=parseFunctionFromText2(onresize);if(typeof onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this.props,this)};this.onresize=onresize;window.addEventListener("resize",this.ONRESIZE)}}else if(name2==="ondelete"){let ondelete=val;if(typeof ondelete==="string")ondelete=parseFunctionFromText2(ondelete);if(typeof ondelete==="function"){this.ondelete=()=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");if(ondelete)ondelete(this.props,this)}}}else if(name2==="oncreate"){let oncreate=val;if(typeof oncreate==="string")oncreate=parseFunctionFromText2(oncreate);if(typeof oncreate==="function"){this.oncreate=oncreate}}else if(name2==="renderonchanged"){let rpc=val;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!=false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}else if(name2==="props"){let newProps=val;if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props})}else if(name2==="template"){let template=val;this.template=template;this.render(this.props);let created=new CustomEvent("created",{detail:{props:this.props}});this.dispatchEvent(created)}else{let parsed=val;if(name2.includes("eval_")){name2=name2.split("_");name2.shift();name2=name2.join();parsed=parseFunctionFromText2(val)}else if(typeof val==="string"){try{parsed=JSON.parse(val)}catch(err){parsed=val}}this[name2]=parsed;if(name2!=="props"&&this.props)this.props[name2]=parsed}};connectedCallback(){if(!this.props)this.props={};let newProps=this.getAttribute("props");if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props});Array.from(this.attributes).forEach(att=>{let name2=att.name;let parsed=att.value;if(name2.includes("eval_")||name2.includes("()")){if(name2.includes("eval_"))name2=name2.split("_");else if(name2.includes("()"))name2=name2.substring(0,name2.indexOf("("));name2.shift();name2=name2.join();parsed=parseFunctionFromText2(att.value)}else if(typeof att.value==="string"){try{parsed=JSON.parse(att.value)}catch(err){parsed=att.value}}if(!this[name2]){Object.defineProperties(this,att,{value:parsed,writable:true,get(){return this[name2]},set(val){this.setAttribute(name2,val)}})}this[name2]=parsed;if(name2!=="props")this.props[name2]=parsed;this.obsAttributes.push(name2)});let resizeevent=new CustomEvent("resized",{detail:{props:this.props,self:this}});let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});let deleted=new CustomEvent("deleted",{detail:{props:this.props,self:this}});let created=new CustomEvent("created",{detail:{props:this.props,self:this}});this.render(this.props);this.dispatchEvent(created);this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)});if(typeof this.onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this,this.props);this.dispatchEvent(resizeevent)};window.addEventListener("resize",this.ONRESIZE)}if(typeof this.ondelete==="function"){let ondelete=this.ondelete;this.ondelete=(props=this.props)=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");this.dispatchEvent(deleted);ondelete(this,props)}}if(typeof this.onchanged==="function"){this.state.data.props=this.props;this.state.subscribeTrigger("props",this.onchanged)}if(this.renderonchanged){let rpc=this.renderonchanged;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!==false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}}constructor(){super()}delete=()=>{this.remove();if(typeof this.ondelete==="function")this.ondelete(this.props)};render=(props=this.props)=>{const t2=document.createElement("template");let usingHTMLFunction=this.template.prototype?.constructor?.name==dummy.prototype.constructor.name;if(typeof this.template==="function"){if(usingHTMLFunction){this.template(t2.content)}else this.templateResult=this.template(this,props)}else this.templateResult=this.template;if(this.styles)this.templateResult=`${this.templateResult}`;if(!usingHTMLFunction){if(typeof this.templateResult==="string")t2.innerHTML=this.templateResult;else if(this.templateResult instanceof HTMLElement||this.templateResult instanceof DocumentFragment){if(this.templateResult.parentNode){this.templateResult.parentNode.removeChild(this.templateResult)}t2.content.appendChild(this.templateResult)}}const fragment=t2.content;if(this.FRAGMENT){if(this.useShadow){if(this.STYLE)this.shadowRoot.removeChild(this.STYLE);this.FRAGMENT.forEach(c=>{this.shadowRoot.removeChild(c)})}else this.FRAGMENT.forEach(c=>{this.removeChild(c)})}if(this.useShadow){if(!this.attachedShadow){this.attachShadow({mode:"open"}).innerHTML="";this.attachedShadow=true}if(this.styles){let style=document.createElement("style");style.textContent=this.styles;this.shadowRoot.prepend(style);this.STYLE=style}let len=fragment.childNodes.length;this.shadowRoot.prepend(fragment);this.FRAGMENT=Array.from(this.shadowRoot.childNodes).slice(0,len)}else{let len=fragment.childNodes.length;this.prepend(fragment);this.FRAGMENT=Array.from(this.childNodes).slice(0,len)}let rendered=new CustomEvent("rendered",{detail:{props:this.props,self:this}});this.dispatchEvent(rendered);if(this.oncreate)this.oncreate(this,props)};state={pushToState:{},data:{},triggers:{},setState(updateObj){Object.assign(this.pushToState,updateObj);if(Object.keys(this.triggers).length>0){for(const prop of Object.getOwnPropertyNames(this.triggers)){if(this.pushToState[prop]){this.data[prop]=this.pushToState[prop];delete this.pushToState[prop];this.triggers[prop].forEach(obj=>{obj.onchanged(this.data[prop])})}}}return this.pushToState},subscribeTrigger(key,onchanged=res=>{}){if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({idx:l,onchanged});return this.triggers[key].length-1}else return void 0},unsubscribeTrigger(key,sub){let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.idx===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);return true}}},subscribeTriggerOnce(key=void 0,onchanged=value=>{}){let sub;let changed=value=>{onchanged(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)}}};function addCustomElement(cls,tag,extend=null){try{if(extend){if(tag)window.customElements.define(tag,cls,{extends:extend});else window.customElements.define(cls.name.toLowerCase()+"-",cls,{extends:extend})}else{if(tag)window.customElements.define(tag,cls);else window.customElements.define(cls.name.toLowerCase()+"-",cls)}}catch(err){}}function parseFunctionFromText2(method){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf(")");return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;try{if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch(err){newFunc=(0,eval)(method)}}}}catch(err){}return newFunc}var wchtmlloader=(node,parent,graph,roots,properties,key)=>{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if((node.tagName||node.__element)&&!node.__props&&!node.__template){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}else if(typeof node.__css==="string"){node.__template+=``;delete node.__css}const registerElement=(node2,tagNameOverride)=>{if(isNativeClass(node2))node2=new node2;else if(typeof node2==="function"&&!node2.__node)node2=node2();class CustomElement extends DOMElement{props=node2.props;styles=node2.__css;useShadow=node2.useShadow;template=node2.__template;oncreate=node2.__onrender;onresize=node2.__onresize;ondelete=node2.__onremove;renderonchanged=node2.__renderonchanged}if(tagNameOverride?.includes("-"))node2.tagName=tagNameOverride;else if(node2.__element)node2.tagName=node2.__element;if(!node2.tagName)node2.tagName=`element${Math.floor(Math.random()*1e15)}-`;CustomElement.addElement(node2.tagName)};if("__components"in node){if(Array.isArray(node.__components))node.__components.forEach(c=>registerElement(c));else Object.entries(node.__components).forEach(([k,c])=>registerElement(c,k.includes("-")?k:void 0))}if("__template"in node){if(typeof node.__renderonchanged==="function"){let renderonchanged=node.__renderonchanged;node.__renderonchanged=element=>{renderonchanged.call(element.node,element)}}registerElement(node);node.__props=document.createElement(node.tagName);let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}}}else if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender&&!(node.__props instanceof DOMElement)&&!node.__template)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return new sjcl.hash.sha256().update(a).finalize()};sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=sjcl_default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};static generateSecret(){return sjcl_default.codec.base64.fromBits(sjcl_default.random.randomWords(8,10))}encrypt(message,key){message=sjcl_default.encrypt(key,message).cipher;return message}decrypt(message,key){message=sjcl_default.decrypt(key,message);return message}encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=sjcl_default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message}};var HTTPfrontend=class _HTTPfrontend extends Service{name="http";fetchProxied=false;listening={};constructor(options,path,fetched){super(options);this.load(this);this.listen(path,fetched)}static request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};GET=(url2="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url:url2,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{let obj=message;if(typeof obj==="object"&&!obj.byteLength){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url2);return this.POST(message,url2)};transponder=(url2,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url:url2,data:message,responseType:type,onload:ev=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}}};var SSEfrontend=class extends Service{name="sse";eventsources={};connections={eventsources:this.eventsources};constructor(options){super(options);this.load(this)}openSSE=options=>{let source=new EventSource(options.url);let sse={source,type:"eventsource",...options};if(!("keepState"in options))options.keepState=true;if(!options.events)options.events={};let close;if(options.events.close){close=options.events.close}options.events.close=ev=>{if(sse.onclose)sse.onclose(ev,sse);if(close)close(ev,sse);delete this.eventsources[options.url]};let open;if(options.events.open){open=options.events.open}options.events.open=ev=>{if(sse.onopen)sse.onopen(ev,sse);if(open)open(ev,sse)};let error;if(options.events.error){error=options.events.error}options.events.error=ev=>{if(sse.onerror)sse.onerror(ev,sse);if(error)error(ev,sse)};let message;if(options.events.message){message=options.events.message}if(!sse.onmessage){sse.onmessage=(ev,sse2)=>{let data=ev.data;if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"&&sse2){sse2._id=data.args;options.events.message=(e,sse3)=>{const result2=this.receive(e.data,sse3);if(options.keepState)this.setState({[options.url]:e.data})}}}}}const result=this.receive(ev.data,sse2);if(options.keepState)this.setState({[options.url]:data})}}options.events.message=ev=>{if(sse.onmessage)sse.onmessage(ev,sse);if(message)message(ev,sse)};if(!options.events.error)options.events.error=(ev,sse2)=>{this.terminate(sse2);delete this.eventsources[options.url]};if(options.events){if(!options.evoptions)options.evoptions=false;for(const key in options.events){if(typeof options.events[key]!=="function"){options.events[key]=ev=>{const result=this.receive(ev.data,sse);if(options.keepState)this.setState({[options.url]:result})}}else{let l=options.events[key];options.events[key]=ev=>{l(ev,sse)}}source.addEventListener(key,options.events[key],options.evoptions)}}let send=message2=>{return this.transmit(message2,options.url)};let request=(message2,method,sessionId)=>{return this.request(message2,options.url,method,sessionId)};let post=(route,args,method)=>{let message2={route,args};if(method)message2.method=method;return this.transmit(message2,options.url)};let run=(route,args,method,sessionId)=>{return this.request({route,args},options.url,method,sessionId)};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSSE(route,options.url,callback,args,key,subInput,sse._id)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options.url)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;this.eventsources[options.url]=sse;return sse};open=this.openSSE;POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="number"||typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{return this.POST(message,url2,"json")};request=(message,url2,method,sessionId)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,url2,callbackId,sessionId]};if(method)req.method=method;let evs=this.eventsources[url2].source;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){evs.removeEventListener("message",onmessage);res(data.args)}}};evs.addEventListener("message",onmessage);this.POST(message,url2,"json")})};runRequest=(message,url2,callbackId,sessionId)=>{let res=this.receive(message);if(url2){if(res instanceof Promise){res.then(r=>{let message2={args:r,callbackId,sessionId};this.POST(message2,url2,"json")})}else{let message2={args:res,callbackId,sessionId};this.POST(message2,url2,"json")}}return res};subscribeSSE=(route,url2,args,key,subInput)=>{if(this.restrict?.[route])return void 0;return this.subscribe(route,res=>{this.POST(res,url2,"json")},args,key,subInput)};subscribeToSSE=(route,url2,callback,args,key,subInput,sessionId)=>{if(url2){this.__node.state.subscribeEvent(url2,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[url2]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.eventsources[url2].run("subscribeSSE",[route,url2,args,key,subInput,sessionId])}};terminate=sse=>{if(typeof sse==="string"){let str2=sse;sse=this.eventsources[sse];delete this.eventsources[str2]}if(!sse)return;if(typeof sse==="object"){if(sse.source){sse=sse.source}if(sse instanceof EventSource){if(sse.readyState!==2)sse.close()}}}};var WSSfrontend=class extends Service{name="wss";sockets={};connections={sockets:this.sockets};constructor(options){super(options);this.load(this)}loadWebSocketRoute=node=>{let wsInfo=this.openWS(node);if(!wsInfo.__ondisconnected){wsInfo.__addOndisconnected(()=>{wsInfo.terminate()})}if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.post(node.callback,args);else return wsInfo.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.send(args);else return wsInfo.request(args)}}}if(!node.__ondisconnected){let ondelete=rt=>{rt?.terminate()};node.__addOndisconnected(ondelete)}return wsInfo};socketloader={"websockets":(node,parent,graph,roots)=>{node._id=node.__node.tag;let ws=this.loadWebSocketRoute(node);Object.assign(node,ws);if(parent&&parent.type==="socket"){let parentWs=this.sockets[parent._id];if(node.parentRoute){parentWs.subscribe(node.parentRoute,node.__operator)}}}};openWS=(options={host:"localhost",port:7e3,path:void 0,protocol:"ws"})=>{let protocol=options.protocol;if(!protocol)protocol="ws";let address=`${protocol}://${options.host}`;if(!("keepState"in options))options.keepState=true;if(options.port)address+=":"+options.port;if(options.path&&!options.path?.startsWith("/"))address+="/";if(options.path)address+=options.path;if(this.sockets[address]?.socket){if(this.sockets[address].socket.readyState===this.sockets[address].socket.OPEN)this.sockets[address].socket.close()}const socket=new WebSocket(address);if(!options.onmessage){if(!options._id){options.onmessage=(data,ws,wsinfo)=>{if(data){if(typeof data==="string"){if(options.debug){console.log("Message from ",address,": ",data)}let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;options.onmessage=(data2,ws2,wsinfo2)=>{if(options.debug){console.log("Message from ",address,": ",data2)}this.receive(data2);if(options.keepState){this.setState({[address]:data2})}}}}}}let res=this.receive(data);if(options.keepState)this.setState({[address]:data})}}else{options.onmessage=(data,ws,wsinfo)=>{if(options.debug){console.log("Message from ",socket.url,": ",data)}this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}}}}if(options.onmessage){socket.addEventListener("message",ev=>{this.sockets[address].onmessage(ev.data,socket,this.sockets[address])})}socket.addEventListener("open",ev=>{if(this.sockets[address].onopen)this.sockets[address].onopen(ev,socket,this.sockets[address])});socket.addEventListener("close",ev=>{let obj=this.sockets[address];let onclose=obj.onclose;delete this.sockets[address];this.remove(address);if(onclose)onclose(ev,socket,obj)});socket.addEventListener("error",ev=>{if(this.sockets[address].onerror)this.sockets[address].onerror(ev,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},this.sockets[address]._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,this.sockets[address]._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSocket(route,this.sockets[address]._id,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(address)};Object.assign(options,{type:"socket",socket,address,send,post,run,request,subscribe,unsubscribe,terminate});if(!(options instanceof GraphNode)){let node=this.add(options);node.__addOndisconnected(function(){terminate()});options=node}this.sockets[address]=options;return options};open=this.openWS;transmit=(data,ws)=>{if(typeof data==="object"&&(data?.route||data?.node||typeof data.arrayBuffer!=="function"&&typeof data.byteLength!=="number")||typeof data==="number")data=JSON.stringify(data);if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}if(ws instanceof WebSocket&&ws?.readyState===1)ws.send(data);return true};terminate=ws=>{let str2;if(!ws){let keys2=Object.keys(this.sockets);for(const key in keys2){this.terminate(key)}}else if(typeof ws==="string"){str2=ws;for(const k in this.sockets){if(k.includes(ws)||this.sockets[k]._id===k){ws=this.sockets[k].socket;break}}}if(ws instanceof WebSocket){if(ws.readyState===ws.OPEN)ws.close();if(this.get(str2?str2:ws.url))this.remove(str2?str2:ws.url)}return true};request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(typeof ws==="string"){for(const s in this.sockets){if(s===ws||this.sockets[s]._id===ws){ws=this.sockets[s].socket;break}}}if(ws){if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))}}return res};subscribeSocket=(route,socket,args,key,subInput)=>{if(this.restrict?.[route])return void 0;if(typeof socket==="string"&&this.sockets[socket]){socket=this.sockets[socket].socket}if(typeof socket==="object"){return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},args,key,subInput)}};subscribeToSocket=(route,socketId,callback,args,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeEvent(socketId,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[socketId]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,args,key,subInput]})}}};var WebRTCfrontend=class extends Service{name="webrtc";rtc={};unanswered={};iceServers=[{urls:["stun:stun.l.google.com:19302"]},{urls:["stun:stun1.l.google.com:19302"]},{urls:["stun:stun2.l.google.com:19302"]},{urls:["stun:stun3.l.google.com:19302"]},{urls:["stun:stun4.l.google.com:19302"]}];connections={rtc:this.rtc};constructor(options,iceServers){super(options);if(iceServers)this.iceServers=iceServers;this.load(this)}openRTC=async options=>{if(!options)options={};if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(!options.config)options.config={iceServers:this.iceServers};if(!this.rtc[options._id]){let rtc=new RTCPeerConnection(options.config);if(!options.channels)options.channels={"data":true};let firstChannel;for(const key in options.channels){firstChannel=key;break}let send=message=>{return this.transmit(message,options._id,options.channels[firstChannel])};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options._id,options.channels[firstChannel])};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let subscribe=(route,callback,args,key,subInput,channelId)=>{return this.subscribeToRTC(route,options._id,channelId?channelId:firstChannel,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.rtc[options._id]={rtc,_id:options._id,request,run,post,send,subscribe,unsubscribe,terminate,graph:this,...options};const setMessageChannelHandle=channel=>{if(!this.rtc[options._id].ondata){this.rtc[options._id].ondata=mev=>{this.receive(mev.data,channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})};channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}else{channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}};if(this.rtc[options._id].channels){for(const channel in this.rtc[options._id].channels){if(this.rtc[options._id].channels[channel]instanceof RTCDataChannel){}else if(typeof this.rtc[options._id].channels[channel]==="object"){this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel,this.rtc[options._id].channels[channel])}else{this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel)}setMessageChannelHandle(this.rtc[options._id].channels[channel])}}rtc.ontrack=ev=>{if(!this.rtc[options._id].receivers)this.rtc[options._id].receivers=[];this.rtc[options._id].receivers.push(ev.receiver);if(!this.rtc[options._id].streams)this.rtc[options._id].streams=[];this.rtc[options._id].streams.push(...ev.streams);let rlength=this.rtc[options._id].receivers.length;let slength=this.rtc[options._id].streams.length;ev.streams.forEach(s=>{s.addEventListener("removetrack",ev2=>{this.rtc[options._id].receivers[rlength]=void 0;this.rtc[options._id].streams[slength]=void 0;if(this.rtc[options._id].removetrack)this.rtc[options._id].removetrack(ev2)})});if(this.rtc[options._id].ontrack)this.rtc[options._id].ontrack(ev)};rtc.ondatachannel=ev=>{this.rtc[options._id].channels[ev.channel.label]=ev.channel;setMessageChannelHandle(ev.channel);if(this.rtc[options._id].ondatachannel)this.rtc[options._id].ondatachannel(ev)};rtc.onicecandidate=ev=>{if(this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate(ev)};rtc.onicecandidateerror=ev=>{if(this.rtc[options._id].onicecandidateerror)this.rtc[options._id].onicecandidateerror(ev)};let initialOffer=this.rtc[options._id].description===void 0;rtc.onnegotiationneeded=async ev=>{if(!initialOffer){const offer=await rtc.createOffer(this.rtc[options._id].offer);if(rtc.signalingState!="stable")return;await rtc.setLocalDescription(offer);if(this.rtc[options._id].onnegotiationneeded)this.rtc[options._id].onnegotiationneeded(ev,rtc.localDescription)}};rtc.oniceconnectionstatechange=ev=>{if(this.rtc[options._id].oniceconnectionstatechange)this.rtc[options._id].oniceconnectionstatechange(ev)};rtc.onconnectionstatechange=ev=>{if(this.rtc[options._id].onconnectionstatechange)this.rtc[options._id].onconnectionstatechange(ev)};rtc.addEventListener("connectionstatechange",ev=>{if(rtc.connectionState==="closed"||rtc.connectionState==="failed"){if(this.rtc[options._id].onclose){this.rtc[options._id].onclose(this.rtc[options._id])}delete this.rtc[options._id]}});if(!this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].candidates)this.rtc[options._id].candidates={};this.rtc[options._id].candidates[`candidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};if(!options.description)return await new Promise((res,rej)=>{this.rtc[options._id].rtc.createOffer(options.offer).then(offer=>this.rtc[options._id].rtc.setLocalDescription(offer)).then(()=>{initialOffer=false;res(this.rtc[options._id])})})}else{Object.assign(this.rtc[options._id],options)}if(options.description){this.rtc[options._id].polite=true;await this.negotiateCall(options._id,options.description,true)}if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);this.rtc[options._id].rtc.addIceCandidate(candidate).catch(console.error)}}return this.rtc[options._id]};open=this.openRTC;addIceCandidate=(rtc,candidate)=>{if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof candidate==="string")candidate=JSON.parse(decodeURIComponent(candidate));if(rtc&&rtc.remoteDescription)return rtc.addIceCandidate(candidate)};receiveCallInformation=async options=>{if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(this.rtc[options._id]){if(options.candidates){for(const key in options.candidates)this.addIceCandidate(this.rtc[options._id].rtc,options.candidates[key]);delete options.candidates}Object.assign(this.rtc[options._id],options)}else if(this.unanswered[options._id]){this.recursivelyAssign(this.unanswered[options._id],options)}else this.unanswered[options._id]=options;return options._id};answerCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return this.openRTC(options)};rejectCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return true};negotiateCall=async(rtc,description,polite)=>{if(typeof rtc==="string"){if(polite===void 0)polite=this.rtc[rtc].description!==void 0;rtc=this.rtc[rtc].rtc}if(typeof description==="string")description=new RTCSessionDescription(JSON.parse(decodeURIComponent(description)));if(description.type==="offer"&&rtc.signalingState!=="stable"){if(!polite)return;await Promise.all([rtc.setLocalDescription({type:"rollback"}),rtc.setRemoteDescription(description)]);return encodeURIComponent(JSON.stringify(rtc.localDescription))}else{await rtc.setRemoteDescription(description)}if(description.type=="offer"){await rtc.setLocalDescription(await rtc.createAnswer());return encodeURIComponent(JSON.stringify(rtc.localDescription))}};createOffer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc].rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createOffer(options.offer).then(offer=>rtc.setLocalDescription(offer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}createAnswer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createAnswer(options.answer).then(answer=>rtc.setLocalDescription(answer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}answerPeer=(rtc,options)=>{if(typeof rtc==="string"){let cpy=Object.assign(this.rtc[rtc],options);delete cpy.description;delete cpy.candidates;Object.assign(this.rtc[rtc],cpy);rtc=this.rtc[rtc]?.rtc}if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(typeof options.description==="string"){options.description=JSON.parse(decodeURIComponent(options.description))}const description=new RTCSessionDescription(options.description);rtc.setRemoteDescription(description).then(()=>{if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);if(this.rtc[options._id])this.rtc[options._id].candidates[prop]=options.candidates[prop];rtc.addIceCandidate(candidate).catch(console.error)}}if(description.type==="offer"){this.rtc[options._id].rtc.createAnswer(options.answer).then(a=>{this.rtc[options._id].rtc.setLocalDescription(a)})}res(this.rtc[options._id]?this.rtc[options._id]:rtc)}).catch(rej)})};createStream=options=>{let stream=new MediaStream;for(const key in options){let track=options[key].track;if(!(track instanceof MediaStreamTrack)&&typeof track==="object"){track=new MediaStreamTrack;track.applyConstraints(options[key].track);stream.addTrack(track)}if(track instanceof MediaStreamTrack){stream.addTrack(track);track.onmute=options[key].onmute;track.onunmute=options[key].onunmute;track.onended=options[key].onended}}return stream};addUserMedia=(rtc,options={audio:true,video:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560}]}},info)=>{return new Promise(async(res,rej)=>{let RTCRtpSenders=[];let stream=await navigator.mediaDevices.getUserMedia(options);if(stream){let tracks=stream.getTracks();tracks.forEach(track=>{let sender=rtc.addTrack(track,stream);if(track.kind==="video"&&info){info.videoSender=sender;info.videoStream=stream}if(track.kind==="audio"&&info){info.audioSender=sender;info.audioStream=stream}RTCRtpSenders.push(sender)});let str2=stream;if(info)info.senders=info.senders?[...info.senders,...RTCRtpSenders]:RTCRtpSenders;res(str2)}})};addTrack=(rtc,track,stream)=>{return rtc.addTrack(track,stream)};removeTrack=(rtc,sender)=>{rtc.removeTrack(sender);return true};addDataChannel=(rtc,name2,options)=>{return rtc.createDataChannel(name2,options)};enableAudio=async(call,audioOptions=true)=>{if(call.audioStream)this.disableAudio(call);let stream=await this.addUserMedia(call.rtc,{audio:audioOptions,video:false},call);if(audioOptions?.deviceId)call.audioSender.deviceId=audioOptions.deviceId;return stream};enableVideo=async(call,videoOptions={optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]},includeAudio=false)=>{if(call.videoStream)this.disableVideo(call);let stream=await this.addUserMedia(call.rtc,{audio:includeAudio,video:videoOptions?videoOptions:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]}},call);if(videoOptions?.deviceId)call.videoSender.deviceId=videoOptions.deviceId;if(includeAudio){if(includeAudio?.deviceId)call.audioSender.deviceId=includeAudio.deviceId;else if(videoOptions?.deviceId)call.audioSender.deviceId=videoOptions.deviceId}return stream};disableAudio(call){if(call.audioSender){call.senders?.find((s,i2)=>{if(call.audioStream?.getAudioTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.audioSender);call.audioSender=void 0}call.audioStream?.getTracks().forEach(track=>{if(track.kind==="audio")track.stop()});call.audioStream=void 0}disableVideo(call){if(call.videoSender){call.senders?.find((s,i2)=>{if(call.videoStream?.getVideoTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.videoSender);call.videoSender=void 0}call.videoStream?.getTracks().forEach(track=>{if(track.kind==="video")track.stop()});call.videoStream=void 0}transmit=(data,id,channel)=>{if(typeof data==="object"&&(data.route||data.node||!data.byteLength&&typeof data.arrayBuffer!=="function")||typeof data==="number")data=JSON.stringify(data);if(!channel&&id){let keys2=Object.keys(this.rtc[id].channels);if(keys2[0])channel=this.rtc[id].channels[keys2[0]]}if(typeof channel==="string"){if(id){channel=this.rtc[id].channels[channel]}else{for(const id2 in this.rtc){if(this.rtc[id2].channels[channel]instanceof RTCDataChannel)this.rtc[id2].channels[channel].send(data)}}}if(channel instanceof RTCDataChannel)channel.send(data);return true};terminate=rtc=>{let tx;if(typeof rtc==="string"){let room=this.rtc[rtc];delete this.rtc[rtc];if(room){tx=room.rtc}}else if(typeof rtc==="object"){tx=rtc.rtc}if(rtc instanceof RTCPeerConnection&&rtc.signalingState!=="closed"){rtc.close()}else if(tx&&tx.signalingState!=="closed"){if(tx)tx.close()}return true};request=(message,channel,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){channel.removeEventListener("message",onmessage);res(data.args)}}};channel.addEventListener("message",onmessage);channel.send(JSON.stringify(req))})};runRequest=(message,channelOrRtcId,callbackId)=>{let res=this.receive(message);if(channelOrRtcId){if(typeof channelOrRtcId==="string"){for(const key in this.rtc){if(key===channelOrRtcId){channelOrRtcId=this.rtc[key].channels.data?this.rtc[key].channels.data:this.rtc[key].channels[Object.keys(this.rtc[key].channels)[0]];break}}}if(res instanceof Promise)res.then(v=>{res={args:v,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res));return res});else{res={args:res,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res))}}return res};subscribeRTC=(route,rtcId,args,key,subInput,channel)=>{if(this.restrict?.[route])return void 0;if(typeof channel==="string"&&this.rtc[rtcId]){channel=this.rtc[rtcId].channels[channel]}else if(!channel){channel=this.rtc[rtcId].channels[Object.keys(this.rtc[rtcId].channels)[0]]}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{channel.send(JSON.stringify({args:r,callbackId:route}))})}else{channel.send(JSON.stringify({args:res,callbackId:route}))}},args,key,subInput)};subscribeToRTC=(route,rtcId,channelId,callback,args,key,subInput)=>{if(typeof channelId==="string"&&this.rtc[rtcId]){let c=this.rtc[rtcId];let channel=c.channels[channelId];if(channel){this.__node.state.subscribeEvent(rtcId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[rtcId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return c.request({route:"subscribeRTC",args:[route,rtcId,args,key,subInput,channelId]})}}}};var browser_default=Worker;var WorkerService=class extends Service{name="worker";workers={};threadRot=0;connections;constructor(options){super();this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.load(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}loadWorkerRoute=(node,routeKey)=>{if(node.workerUrl)node.url=node.workerUrl;if(node._id)node.__node.tag=node._id;if(!node.__node.tag)node.__node.tag=routeKey;node._id=node.__node.tag;let worker;if(this.workers[node._id])worker=this.workers[node._id];else if(node.worker)worker=node.worker;if(!worker){worker=this.addWorker(node)}node.worker=worker;if(!node.__ondisconnected){let ondelete=rt=>{rt.worker?.terminate()};node.__addOndisconnected(ondelete)}if(node.transferFunctions){for(const prop in node.transferFunctions){this.transferFunction(worker,node.transferFunctions[prop],prop)}}if(node.transferClasses){for(const prop in node.transferClasses){this.transferClass(worker,node.transferClasses[prop],prop)}}if(worker){if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.post(node.callback,args);else return worker.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(node.init){worker.run(node.init,node.initArgs,void 0,node.initTransfer)}return worker}};workerloader={"workers":(node,parent,graph,roots)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?._id&&this.workers[rt._id]||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent?.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&roots[rt.__parent]?.worker){roots[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}}return rt}};addDefaultMessageListener=()=>{globalThis.onmessage=ev=>{let result=this.receive(ev.data);if(this.__node.keepState)this.setState({[this.name]:result})}};postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new browser_default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,method,transfer)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,args,key,subInput,blocking)=>{return this.subscribeToWorker(route,options._id,callback,args,key,subInput,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,void 0,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,void 0,workerSubs[key].callback,void 0,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub});console.log(JSON.stringify(workerSubs))}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]).then(console.log)}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev=>{this.receive(ev.data);this.setState({[options._id]:ev.data})};if(!options.onerror){options.onerror=ev=>{console.error(ev.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;let workersettings={worker,__node:{tag:options._id},send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};let node=this.add(workersettings);this.workers[options._id]=node;node.__addOndisconnected(function(){terminate()});return this.workers[options._id]};open=this.addWorker;close=()=>{globalThis.close()};toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof browser_default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys2=Object.keys(this.workers);this.workers[keys2[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys2.length)this.threadRot=0}return message};terminate=worker=>{let onclose;let str2;if(typeof worker==="string"){str2=worker;let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}else if(typeof worker==="object"){if(worker?._id){worker=worker.worker;delete this.workers[worker?._id]}}if(worker instanceof browser_default){worker.terminate();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}return false};establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof browser_default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof browser_default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};runRequest=(message,worker,callbackId,getTransferable=true)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId},transfer)}return res};subscribeWorker=(route,worker,args,key,subInput,blocking,getTransferable=true)=>{if(this.restrict?.[route])return void 0;let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker?.postMessage)worker.postMessage({args:r,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker?.postMessage)worker.postMessage({args:res,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route},transfer)}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,args,key,subInput)};subscribeToWorker=(route,workerId,callback,args,key,subInput,blocking,getTransferable=true)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeEvent(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,args,key,subInput,blocking,getTransferable])}};triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i2=0;i2{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,args,key,subInput,blocking,getTransferable])};unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof sourceWorker==="object"){return sourceWorker.run("unsubscribe",[sourceRoute,sub])}}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name2 of properties){dst[name2]=src[name2]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};var str=String('(()=>{var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}if(typeof WorkerGlobalScope!=="undefined"){const routes={...workerCanvasRoutes};self.onmessage=ev=>{if(ev.data.route){if(Array.isArray(ev.data.args)){routes[ev.data.route](...ev.data.args)}else routes[ev.data.route](ev.data.args)}}}var canvas_worker_default=self;})();\n');var url=URL.createObjectURL(new globalThis.Blob([str],{type:"text/javascript"}));var canvas_worker_default=url;function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText3(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText3(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText3(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText3(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText3(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText3(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText3(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText3(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText3(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText3(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var SessionsService=class extends Service{name="sessions";users={};sessions={oneWay:{},shared:{}};invites={};constructor(options,users){super(options);this.setLoaders(loaders);this.load(this);if(users)this.users=users}getSessionInfo=(sessionIdOrName,userId)=>{if(!sessionIdOrName){return this.sessions.shared}else{if(this.sessions.oneWay[sessionIdOrName]){let s=this.sessions.oneWay[sessionIdOrName];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{oneWay:{[sessionIdOrName]:s}}}}else if(this.sessions.shared[sessionIdOrName]){return{shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};openOneWaySession=(options={},sourceUserId,listenerUserId)=>{if(!options._id){options._id=`oneWay${Math.floor(Math.random()*1e15)}`;if(this.sessions.oneWay[options._id]){delete options._id;this.openOneWaySession(options,sourceUserId)}}if(options._id&&sourceUserId&&this.users[sourceUserId]){if(sourceUserId){if(!options.settings)options.settings={listener:sourceUserId,source:sourceUserId,propnames:{latency:true},admins:{[sourceUserId]:true},ownerId:sourceUserId};if(!options.settings.listener)options.settings.listener=listenerUserId?listenerUserId:sourceUserId;if(!options.settings.source)options.settings.source=sourceUserId;if(!this.users[sourceUserId].sessions)this.users[sourceUserId].sessions={};this.users[sourceUserId].sessions[options._id]=options}if(!options.data)options.data={};if(options.onopen)options.onopen(options);if(this.sessions.oneWay[options._id]){return this.updateSession(options,sourceUserId)}else if(options.settings?.listener&&options.settings.source)this.sessions.oneWay[options._id]=options}return options};openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;return this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={oneWay:{},shared:{}};if(!options.settings.name)options.name=options.id;if(options.onopen)options.onopen(options);if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};open=(options,userId)=>{if(options.listener)this.openOneWaySession(options,userId);else this.openSharedSession(options,userId)};updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.oneWay[options._id];if(!session)session=this.sessions.shared[options._id];if(session&&userId){if(session.settings&&(session?.settings.source===userId||session.settings.admins?.[userId]||session.settings.moderators?.[userId]||session.settings.ownerId===userId)){return this.recursivelyAssign(session,options)}}else if(options.settings?.source){return this.openOneWaySession(options,userId)}else return this.openSharedSession(options,userId)}return false};joinSession=(sessionId,userId,options,remoteUser=true)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(!sesh)sesh=this.sessions.oneWay[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;sesh.settings.newUser=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options?.source||options?.listener){sesh=this.openOneWaySession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options){sesh=this.openSharedSession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}return false};inviteToSession=(session,userInvited,inviteEndpoint,remoteUser=true)=>{if(remoteUser&&this.users[userInvited]?.send){this.users[userInvited]?.send({route:"receiveSessionInvite",args:[session,userInvited,inviteEndpoint]})}else{this.receiveSessionInvite(session,userInvited,inviteEndpoint)}};receiveSessionInvite=(session,userInvited,endpoint)=>{if(!this.invites[userInvited])this.invites[userInvited]={};let id=typeof session==="string"?session:session._id;this.invites[userInvited][id]={session,endpoint};return id};acceptInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;let invite=this.invites[userInvited]?.[id];let endpoint;if(invite){session=invite.session;endpoint=invite.endpoint;delete this.invites[userInvited]?.[id]}return new Promise((res,rej)=>{if(!id)res(false);if(remoteUser&&endpoint&&this.users[endpoint]?.send){let resolved;let timeout=setTimeout(()=>{if(!resolved){this.unsubscribe("joinSession",subbed);rej(new Error("Session join timed out"))}},1e4);let subbed=this.subscribe("joinSession",result=>{if(typeof result==="object"&&result?._id===id){if(result.setting?.users?.includes(userInvited)){this.unsubscribe("joinSession",subbed);resolved=true;if(timeout)clearTimeout(timeout);res(result)}}});this.users[endpoint]?.send({route:"joinSession",args:[id,userInvited,void 0,true]})}else res(this.joinSession(id,userInvited,typeof session==="object"?session:void 0))})};rejectInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;if(this.invites[userInvited]?.[id]){let endpoint=this.invites[userInvited][id].endpoint;delete this.invites[userInvited][id];if(remoteUser&&endpoint&&this.users[endpoint]?.send){this.users[endpoint].send({route:"rejectInvite",args:[id,userInvited]})}return true}};leaveSession=(session,userId,clear=true,remoteUser=true)=>{let sessionId;if(typeof session==="string"){sessionId=session;session=this.sessions.oneWay[sessionId];if(!session)session=this.sessions.shared[sessionId]}else sessionId=session._id;if(session){if(this.sessions.oneWay[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.oneWay[sessionId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){this.swapHost(session,void 0,true);delete session.data.shared[userId]}}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}return true}return false};deleteSession=(session,userId,remoteUsers=true)=>{if(typeof session==="string"){let id=session;session=this.sessions.oneWay[id];if(!session)session=this.sessions.shared[id]}if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user]?.sessions)delete this.users[user].sessions[session._id];if(this.users[user]?.sessionSubs)delete this.users[user].sessionSubs[session._id];if(remoteUsers){if(session.users){for(const key in session.users){if(this.users[key]?.send)this.users[key].send({route:"unsubscribeFromSession",args:[session._id,key]})}}else if(session.listener){if(this.users[session.listener]?.send)this.users[session.listener].send({route:"unsubscribeFromSession",args:[session._id,session.listener]})}else if(this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId]})}}else{this.unsubsribeFromSession(session,user)}}if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.oneWay[session._id];if(session.onclose)session.onclose(session)}}return true};getFirstMatch(obj1,obj2){for(const i2 in obj1){if(i2 in obj2)return i2}return false}swapHost=(session,newHostId,adoptData=true,remoteUser=true)=>{if(typeof session==="string"){if(this.sessions.oneWay[session])session=this.sessions.oneWay[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){let oldHost=session.settings.host;delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];if(adoptData&&oldHost&&session.settings.inheritHostData!==false){if(session.data?.shared[oldHost]){if(session.data?.shared[oldHost]){session.data.shared[session.settings.host]=Object.assign(session.data.shared[session.settings.host]?session.data.shared[session.settings.host]:{},session.data.shared[oldHost]);if(remoteUser){}}}}return true}return false};subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}let user=this.users[userId];if(!user)return void 0;if(!user.sessionSubs)user.sessionSubs={};if(!user.sessionSubs[session._id])user.sessionSubs[session._id]={};if(onmessage)user.sessionSubs[session._id].onmessage=onmessage;if(onopen)this.sessionSubs[userId][session._id].onopen=onopen;if(onclose)user.sessionSubs[session._id].onclose=onclose;if(typeof onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)this.sessionSubs[userId][session._id].onopen(session,user);this.unsubscribe("joinSession",sub)});user.sessionSubs[session._id].onopenSub=sub}return session};unsubsribeFromSession=(session,userId,clear=true)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}const clearSessionSubs=(Id,s)=>{let u2=this.users[Id];if(!u2)return void 0;if(u2.sessionSubs?.[s._id]){if(u2.sessionSubs[s._id].onopenSub){this.unsubscribe("joinSession",u2.sessionSubs[s._id].onopenSub)}}if(u2.sessionSubs[s._id].onclose)u2.sessionSubs[s._id].onclose(s,u2);delete u2.sessionSubs[s._id]};if(userId){clearSessionSubs(userId,session)}else{for(const key in this.users){clearSessionSubs(key,session)}}if(clear){if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.shared[session._id]}};sessionUpdateCheck=(sessionHasUpdate,transmit=true)=>{let updates={oneWay:{},shared:{}};for(const session in this.sessions.oneWay){const sesh=this.sessions.oneWay[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.oneWay[session];continue}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(prop in this.users[sesh.source]){if(this.sessions.oneWay[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(prop in this.users[sesh.source]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.oneWay[session]?.data&&prop in this.sessions.oneWay[session]?.data)delete this.sessions.oneWay[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.oneWay[session].data,updateObj.data);updates.oneWay[sesh._id]=updateObj;if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.onhasupdate(sesh,updateObj)}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const oneWayData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}else if(sesh.settings.newUser){updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;sesh.settings.newUser=false}if(user!==sesh.settings.host){oneWayData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data?.oneWay&&!(user in sesh.data.oneWay)){if(typeof this.users[user][prop]==="object")oneWayData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else oneWayData[user][prop]=this.users[user][prop]}else if(typeof oneWayData[user][prop]==="object"&&sesh.data){if(prop in this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))oneWayData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.oneWay?.[prop]!==this.users[user][prop])oneWayData[user][prop]=this.users[user][prop]}else if(sesh.data?.oneWay?.[user]&&prop in sesh.data?.oneWay?.[user])delete sesh.data.oneWay[user][prop]}if(Object.keys(oneWayData[user]).length===0)delete oneWayData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user]))sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}}}if(Object.keys(oneWayData).length>0){updateObj.data.oneWay=oneWayData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user]?.[prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user]?.[prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.oneWay){updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){Object.assign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.oneWay){Object.assign(this.sessions.shared[session].data?.oneWay,updateObj.data.oneWay)}if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.settings.onhasupdate(sesh,updateObj)}}if(Object.keys(updates.oneWay).length===0)delete updates.oneWay;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};transmitSessionUpdates=updates=>{let users={};if(updates.oneWay){for(const s in updates.oneWay){let session=this.sessions.oneWay[s];if(session?.settings){let u2=session.settings.listener;if(!users[u2])users[u2]={};users[u2].oneWay[s]=updates.oneWay[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){for(const u2 in session.settings.users){if(!users[u2])users[u2]={};users[u2].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u2 in users){message.args=[u2,users[u2]];if(this.users[u2]?.send)this.users[u2].send(JSON.stringify(message));this.setState({[u2]:Object.create(message)})}return users};receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(user){if(!user.sessions)user.sessions={oneWay:{},shared:{}};if(!user.sessionSubs)user.sessionSubs={}}if(update.oneWay){for(const key in update.oneWay){this.recursivelyAssign(this.sessions.oneWay[key].data,update.oneWay[key].data);if(this.sessions.oneWay[key]?.settings.onmessage)this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key],update.oneWay[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}if(update.shared){for(const key in update.shared){if(update.shared[key].settings.users)this.sessions.shared[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)this.sessions.shared[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.oneWay)this.recursivelyAssign(this.sessions.shared[key].data.oneWay,update.shared[key].data.oneWay);if(update.shared[key].data.shared)this.recursivelyAssign(this.sessions.shared[key].data.shared,update.shared[key].data.shared);if(this.sessions.shared[key]?.settings.onmessage)this.sessions.shared[key].settings.onmessage(this.sessions.shared[key],update.shared[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}return user}};getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};userUpdateCheck=(user,onupdate)=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});if(onupdate){onupdate(user,updateObj)};return updateObj}}return void 0};setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};STREAMLATEST=0;STREAMALLLATEST=1;streamSettings={};streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};setStreamFunc=(name2,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name2].settings[key])this.streamSettings[name2].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name2].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name2].settings[key].callback=callback;if(!this.streamSettings[name2].settings[key].callback)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;return true};addStreamFunc=(name2,callback=data=>{})=>{this.streamFunctions[name2]=callback};setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};removeStream=(streamName,key)=>{if(streamName&&this.streamSettings[streamName]&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}}};var Router=class extends Service{name="router";connections={};sources={};services={};serviceConnections={};users={};userTimeout=1e4;order;constructor(options){super(options);this.load(this);if(options){if(options.order)this.order=options.order;if(options.timeout)this.userTimeout=options.timeout;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}addUser=async(info,connections,config,receiving)=>{let user;if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}if(this.users[info._id]){user=this.users[info._id]}else{user=Object.assign({},info)}if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>this.userTimeout){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}if(!this.users[info._id]){let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let sendAll=(message,...a)=>{let connections2=this.getConnections(user._id,"send");for(const key in connections2)if(connections2[key]?.send)return connections2[key].send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let requestAll=(message,method,...a)=>{let connections2=this.getConnections(user._id,"request");let results=[];for(const key in connections2)if(connections2[key]?.request)results.push(connections2[key].request(message,method,...a));return Promise.all(results)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let postAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"post");for(const key in connections2)if(connections2[key]?.post)connections2[key].post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let runAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"run");let results=[];for(const key in connections2)if(connections2[key]?.run)results.push(connections2[key].run(route,args,method,...a));return Promise.all(results)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let subscribeAll=(route,callback,...a)=>{let connections2=this.getConnections(user._id,"subscribe");let results=[];for(const key in connections2)if(connections2[key]?.post)results.push(connections2[key].subscribe(route,callback,...a));return Promise.all(results)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let unsubscribeAll=(route,subs,...a)=>{let connections2=this.getConnections(user._id,"unsubscribe");let results=[];for(const key in connections2)if(connections2[key]?.post&&subs[key])results.push(connections2[key].unsubscribe(route,subs[key],...a));return Promise.all(results)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;user.sendAll=sendAll;user.requestAll=requestAll;user.postAll=postAll;user.runAll=runAll;user.subscribeAll=subscribeAll;user.unsubscribeAll=unsubscribeAll;user.terminateAll=terminate;this.users[user._id]=user}if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i2)=>{if(connections[k]?._id){connectionIds[`${i2}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}getConnection=(sourceId,hasMethod,connectionId)=>{if(this.connections[sourceId]){return this.connections[sourceId]}else if(this.sources[sourceId]){if(hasMethod?.includes("All"))return this.users[sourceId];if(connectionId){if(hasMethod){if(this.sources[sourceId][connectionId]?.[hasMethod])return this.sources[sourceId][connectionId]}else if(this.sources[sourceId][connectionId])return this.sources[sourceId][connectionId];else return void 0}else if(this.order){for(let i2=0;i2{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}return found}};runConnection=async(userId,method,args,connectionId)=>{let sendTo;if(method.indexOf("All")>-1){sendTo=this.users[userId]}else{sendTo=this.getConnection(userId,method,connectionId)}if(sendTo){let res=sendTo[method](...args);res=await res;return res}};subscribeThroughConnection=(route,remoteRelay,remoteEndpoint,callback,...args)=>{if(typeof remoteRelay==="string"){remoteRelay=this.getConnection(remoteRelay,"run")}if(typeof remoteRelay==="object")return new Promise((res,rej)=>{remoteRelay.run("routeConnections",[route,remoteEndpoint,remoteRelay._id,...args]).then(sub=>{this.__node.state.subscribeEvent(remoteEndpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[remoteEndpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};addConnection=(options,source,autoRemove=true)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.connection=options.connection;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await connectionHasId(info,this.userTimeout)}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await connectionHasId(connection,this.userTimeout)}if(connection._id)return this.addConnection({connection,service},source)}}};terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}}};function connectionHasId(connection,timeout=1e4){return new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>timeout){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connection timed out:",er)})}})(); diff --git a/dist/index.node.d.ts b/dist/index.node.d.ts deleted file mode 100644 index c5c0af0d..00000000 --- a/dist/index.node.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export * from './src/core/Graph'; -export * from './src/core/EventHandler'; -export * from './src/loaders'; -export { methodstrings } from './src/loaders/methodstrings'; -export * from './src/services/Service'; -export * from './src/services/remote/remote.routes'; -export * from './src/services/ecs/ECS.service'; -export * from './src/services/e2ee/E2EE.service'; -export * from './src/services/http/HTTP.node'; -export * from './src/services/sse/SSE.node'; -export * from './src/services/wss/WSS.node'; -export * from './src/services/cmd/CMD.node'; -export * from './src/services/sessions/sessions.service'; -export * from './src/services/router/Router'; diff --git a/dist/index.node.js b/dist/index.node.js deleted file mode 100644 index 003fd2c1..00000000 --- a/dist/index.node.js +++ /dev/null @@ -1,107 +0,0 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name2 in all)__defProp(target,name2,{get:all[name2],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var require_build=__commonJS({"node_modules/better-sse/build/index.js"(exports2,module2){!function(e,t2){if("object"==typeof exports2&&"object"==typeof module2)module2.exports=t2();else if("function"==typeof define&&define.amd)define([],t2);else{var s=t2();for(var i in s)("object"==typeof exports2?exports2:e)[i]=s[i]}}(global,()=>(()=>{"use strict";var e={n:t3=>{var s2=t3&&t3.__esModule?()=>t3.default:()=>t3;return e.d(s2,{a:s2}),s2},d:(t3,s2)=>{for(var i2 in s2)e.o(s2,i2)&&!e.o(t3,i2)&&Object.defineProperty(t3,i2,{enumerable:true,get:s2[i2]})},o:(e2,t3)=>Object.prototype.hasOwnProperty.call(e2,t3),r:e2=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e2,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e2,"__esModule",{value:true})}},t2={};e.r(t2),e.d(t2,{Channel:()=>g,EventBuffer:()=>d,Session:()=>m,SseError:()=>v,createChannel:()=>y2,createEventBuffer:()=>w,createSession:()=>b});const s=require("http"),i=e2=>JSON.stringify(e2),r=/(\r\n|\r|\n)/g,n=/\n+$/g,o=e2=>{let t3=e2;return t3=t3.replace(r,"\n"),t3=t3.replace(n,""),t3},h=require("crypto");let a;a=h.randomUUID?()=>(0,h.randomUUID)():()=>(0,h.randomBytes)(4).toString("hex");const c=e2=>async(t3,s2={})=>{const{eventName:i2="stream"}=s2;return await new Promise((s3,r2)=>{t3.on("data",t4=>{let s4;s4=Buffer.isBuffer(t4)?t4.toString():t4,e2(s4,i2)}),t3.once("end",()=>s3(true)),t3.once("close",()=>s3(true)),t3.once("error",e3=>r2(e3))})},l=e2=>async(t3,s2={})=>{const{eventName:i2="iteration"}=s2;for await(const s3 of t3)e2(s3,i2)};class d{constructor(e2={}){var t3,s2;this.buffer="",this.writeField=(e3,t4)=>{const s3=this.sanitize(t4);return this.buffer+=e3+":"+s3+"\n",this},this.data=e3=>{const t4=this.serialize(e3);return this.writeField("data",t4),this},this.id=(e3="")=>(this.writeField("id",e3),this),this.retry=e3=>{const t4=e3.toString();return this.writeField("retry",t4),this},this.comment=(e3="")=>(this.writeField("",e3),this),this.dispatch=()=>(this.buffer+="\n",this),this.push=(e3,t4="message",s3=a())=>(this.event(t4).id(s3).data(e3).dispatch(),this),this.stream=c(this.push),this.iterate=l(this.push),this.clear=()=>(this.buffer="",this),this.read=()=>this.buffer,this.serialize=null!==(t3=e2.serializer)&&void 0!==t3?t3:i,this.sanitize=null!==(s2=e2.sanitizer)&&void 0!==s2?s2:o}event(e2){return this.writeField("event",e2),this}}const u2=require("events");var f=e.n(u2);class p extends f(){addListener(e2,t3){return super.addListener(e2,t3)}prependListener(e2,t3){return super.prependListener(e2,t3)}prependOnceListener(e2,t3){return super.prependOnceListener(e2,t3)}on(e2,t3){return super.on(e2,t3)}once(e2,t3){return super.once(e2,t3)}emit(e2,...t3){return super.emit(e2,...t3)}off(e2,t3){return super.off(e2,t3)}removeListener(e2,t3){return super.removeListener(e2,t3)}}class v extends Error{constructor(e2){super(e2),this.message=`better-sse: ${e2}`}}class m extends p{constructor(e2,t3,r2={}){var n2,h2,u3,f2,p2,m2,b2;super(),this.lastId="",this.isConnected=false,this.state={},this.initialize=()=>{var e3,t4,i2;const r3=`http://${this.req.headers.host}${this.req.url}`,n3=new URL(r3).searchParams;if(this.trustClientEventId){const s2=null!==(i2=null!==(t4=null!==(e3=this.req.headers["last-event-id"])&&void 0!==e3?e3:n3.get("lastEventId"))&&void 0!==t4?t4:n3.get("evs_last_event_id"))&&void 0!==i2?i2:"";this.lastId=s2}const o2={};this.res instanceof s.ServerResponse?(o2["Content-Type"]="text/event-stream",o2["Cache-Control"]="private, no-cache, no-store, no-transform, must-revalidate, max-age=0",o2.Connection="keep-alive",o2.Pragma="no-cache",o2["X-Accel-Buffering"]="no"):(o2["content-type"]="text/event-stream",o2["cache-control"]="private, no-cache, no-store, no-transform, must-revalidate, max-age=0",o2.pragma="no-cache",o2["x-accel-buffering"]="no");for(const[e4,t5]of Object.entries(this.headers))o2[e4]=null!=t5?t5:"";this.res.writeHead(this.statusCode,o2),n3.has("padding")&&this.buffer.comment(" ".repeat(2049)).dispatch(),n3.has("evs_preamble")&&this.buffer.comment(" ".repeat(2056)).dispatch(),null!==this.initialRetry&&this.buffer.retry(this.initialRetry).dispatch(),this.flush(),null!==this.keepAliveInterval&&(this.keepAliveTimer=setInterval(this.keepAlive,this.keepAliveInterval)),this.isConnected=true,this.emit("connected")},this.onDisconnected=()=>{this.req.removeListener("close",this.onDisconnected),this.res.removeListener("close",this.onDisconnected),this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.isConnected=false,this.emit("disconnected")},this.keepAlive=()=>{this.buffer.comment().dispatch(),this.flush()},this.data=e3=>(this.buffer.data(e3),this),this.id=(e3="")=>(this.buffer.id(e3),this.lastId=e3,this),this.retry=e3=>(this.buffer.retry(e3),this),this.comment=e3=>(this.buffer.comment(e3),this),this.dispatch=()=>(this.buffer.dispatch(),this),this.flush=()=>(this.res.write(this.buffer.read()),this.buffer.clear(),this),this.push=(e3,t4="message",s2=a())=>{if(!this.isConnected)throw new v("Cannot push data to a non-active session.");return this.buffer.push(e3,t4,s2),this.flush(),this.lastId=s2,this.emit("push",e3,t4,s2),this},this.stream=c(this.push),this.iterate=l(this.push),this.batch=async e3=>{if(e3 instanceof d)this.res.write(e3.read());else{const t4=new d({serializer:this.serialize,sanitizer:this.sanitize});await e3(t4),this.res.write(t4.read())}},this.req=e2,this.res=t3;const g2=null!==(n2=r2.serializer)&&void 0!==n2?n2:i,y3=null!==(h2=r2.sanitizer)&&void 0!==h2?h2:o;this.serialize=g2,this.sanitize=y3,this.buffer=new d({serializer:g2,sanitizer:y3}),this.trustClientEventId=null===(u3=r2.trustClientEventId)||void 0===u3||u3,this.initialRetry=null===r2.retry?null:null!==(f2=r2.retry)&&void 0!==f2?f2:2e3,this.keepAliveInterval=null===r2.keepAlive?null:null!==(p2=r2.keepAlive)&&void 0!==p2?p2:1e4,this.statusCode=null!==(m2=r2.statusCode)&&void 0!==m2?m2:200,this.headers=null!==(b2=r2.headers)&&void 0!==b2?b2:{},this.req.once("close",this.onDisconnected),this.res.once("close",this.onDisconnected),setImmediate(this.initialize)}event(e2){return this.buffer.event(e2),this}}const b=(...e2)=>new Promise(t3=>{const s2=new m(...e2);s2.once("connected",()=>{t3(s2)})});class g extends p{constructor(){super(),this.state={},this.sessions=new Set,this.broadcast=(e2,t3="message",s2={})=>{const i2=a(),r2=s2.filter?this.activeSessions.filter(s2.filter):this.sessions;for(const s3 of r2)s3.push(e2,t3,i2);return this.emit("broadcast",e2,t3,i2),this}}get activeSessions(){return Array.from(this.sessions)}get sessionCount(){return this.sessions.size}register(e2){if(this.sessions.has(e2))return this;if(!e2.isConnected)throw new v("Cannot register a non-active session.");return e2.once("disconnected",()=>{this.emit("session-disconnected",e2),this.deregister(e2)}),this.sessions.add(e2),this.emit("session-registered",e2),this}deregister(e2){return this.sessions.has(e2)?(this.sessions.delete(e2),this.emit("session-deregistered",e2),this):this}}const y2=(...e2)=>new g(...e2),w=(...e2)=>new d(...e2);return t2})())}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports2,module2){"use strict";var{Duplex}=require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream2(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err2){called=true;callback(err2)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module2.exports=createWebSocketStream2}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports2,module2){"use strict";module2.exports={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports2,module2){"use strict";var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module2.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports2,module2){"use strict";var zlib=require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;var PerMessageDeflate=class{constructor(options,isServer,maxPayload){this._maxPayload=maxPayload|0;this._options=options||{};this._threshold=this._options.threshold!==void 0?this._options.threshold:1024;this._isServer=!!isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&!params.client_max_window_bits){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module2.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;err[kStatusCode]=1007;this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports2,module2){"use strict";var{isUtf8}=require("buffer");var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}module2.exports={isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module2.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=require("utf-8-validate");module2.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports2,module2){"use strict";var{Writable}=require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var promise=Promise.resolve();var queueTask=typeof queueMicrotask==="function"?queueMicrotask:queueMicrotaskShim;var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;var Receiver2=class extends Writable{constructor(options={}){super();this._allowSynchronousEvents=!!options.allowSynchronousEvents;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes7){this.controlMessage(data,cb);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else{data=fragments}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;queueTask(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;queueTask(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;queueTask(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}};module2.exports=Receiver2;function queueMicrotaskShim(cb){promise.then(cb).catch(throwErrorNextTick)}function throwError(err){throw err}function throwErrorNextTick(err){process.nextTick(throwError,err)}}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports2,module2){"use strict";var{Duplex}=require("stream");var{randomFillSync}=require("crypto");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER}=require_constants();var{isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._deflating=false;this._queue=[]}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{randomFillSync(mask,0,4)}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else{buf.set(data,2)}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(_Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;if(perMessageDeflate){const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(this._deflating){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}else{this.sendFrame(_Sender.frame(data,{[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1:false}),cb)}}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._deflating=true;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");if(typeof cb==="function")cb(err);for(let i=0;i{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension].concat(Object.keys(params).map(k=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map(v=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module2.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports2,module2){"use strict";var EventEmitter=require("events");var https2=require("https");var http2=require("http");var net=require("net");var tls=require("tls");var{randomBytes,createHash}=require("crypto");var{Duplex,Readable}=require("stream");var{URL:URL2}=require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver2=require_receiver();var Sender2=require_sender();var{BINARY_TYPES,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener:addEventListener2,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var closeTimeout=30*1e3;var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket3=class _WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._extensions={};this._paused=false;this._protocol="";this._readyState=_WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});this._sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._socket=socket;receiver[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=_WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===_WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=_WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,err=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),closeTimeout)}pause(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=_WebSocket.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket3,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket3.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket3.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket3.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket3.prototype.addEventListener=addEventListener2;WebSocket3.prototype.removeEventListener=removeEventListener;module2.exports=WebSocket3;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:false,autoPong:true,protocolVersion:protocolVersions[1],maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};websocket._autoPong=opts.autoPong;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch(e){throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request=isSecure?https2.request:http2.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=isSecure?tlsConnect:netConnect;opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate(opts.perMessageDeflate!==true?opts.perMessageDeflate:{},false,opts.maxPayload);opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key2,value]of Object.entries(headers)){options.headers[key2.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",res=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;if(res.headers.upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket3.CLOSING;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket3.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}websocket.emit("error",err)}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket3.CLOSING;let chunk;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&(chunk=websocket._socket.read())!==null){websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket3.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket3.CLOSING;this.destroy()}}}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports2,module2){"use strict";var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i{const body=http2.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(req.headers.upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(!key||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==8&&version!==13){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate(this.options.perMessageDeflate,true,this.options.maxPayload);try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}};module2.exports=WebSocketServer2;function addListeners(server,map){for(const event of Object.keys(map))server.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server.removeListener(event,map[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http2.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r -`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message){if(server.listenerCount("wsClientError")){const err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message)}}}});var index_node_exports={};__export(index_node_exports,{CMDService:()=>CMDService,Callable:()=>Callable,E2EEService:()=>E2EEService,ECSService:()=>ECSService,EventHandler:()=>EventHandler,Graph:()=>Graph,GraphNode:()=>GraphNode,HTTPbackend:()=>HTTPbackend,Router:()=>Router,SSEbackend:()=>SSEbackend,Service:()=>Service,SessionsService:()=>SessionsService,WSSbackend:()=>WSSbackend,animate:()=>animate,backprop:()=>backprop,bindListener:()=>bindListener,branching:()=>branching,connectionHasId:()=>connectionHasId,defaultManifest:()=>defaultManifest,defaultServiceWorker:()=>defaultServiceWorker,getAllProperties:()=>getAllProperties,getCallbackFromString:()=>getCallbackFromString,htmlBodyBoilerPlate:()=>htmlBodyBoilerPlate,instanceObject:()=>instanceObject,isFunction:()=>isFunction,isNativeClass:()=>isNativeClass,isTypedArray:()=>isTypedArray,loaders:()=>loaders,loop:()=>loop,methodstrings:()=>methodstrings,nodeTemplates:()=>nodeTemplates,recursivelyAssign:()=>recursivelyAssign2,remoteGraphRoutes:()=>remoteGraphRoutes,scriptBoilerPlate:()=>scriptBoilerPlate,spliceTypedArray:()=>spliceTypedArray,state:()=>state,substitute__operator:()=>substitute__operator,transformListenerResult:()=>transformListenerResult,triggerListenerOncreate:()=>triggerListenerOncreate,wrapArgs:()=>wrapArgs});module.exports=__toCommonJS(index_node_exports);var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t2=>{for(const key in t2){this.unsubscribe(t2[key]);this.delete(t2[key].__node.tag);delete this.__node.roots[t2[key].__node.tag];this.delete(key);delete this.__node.roots[key];t2[key].__node.tag=t2[key].__node.tag.substring(t2[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t2[key])}t2[key].__callDisconnected();if(t2[key].__children){recursiveRemove(t2[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function getFnParamNames(fn){if(typeof fn!=="string")fn=fn.toString();const arrowMatch=fn.match(/\(?[^]*?\)?\s*=>/);if(arrowMatch)return arrowMatch[0].replace(/[()\s]/gi,"").replace("=>","").split(",");const match=fn.match(/\([^]*?\)/);return match?match[0].replace(/[()\s]/gi,"").split(","):[]}var getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path3.join("."))}}}return value}return function stringifyWithCircularRefs3(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value==="function"?value.toString():value,path3.join("."))}}}return typeof value==="function"?value.toString():value}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path3.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str=properties.toString();else if(typeof properties==="string")str=properties;if(str){if(connection.run)return connection.run("setNode",[str]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(template);if(node){nodeTemplates[node.__node.tag]=template;return node.__node?.tag}else return false}else return false},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str=recursivelyStringifyFunctions(properties);return str},getListenerJSON:function(){const triggers=this.__node.state.triggers;let result={};for(const key in triggers){triggers[key].forEach(trigger=>{let t2=trigger;if(!result[t2.target])result[t2.target]={};let l=t2.source+(t2.key?"."+t2.key:"");result[t2.target][l]={__callback:t2.__callback};if(t2.__args)result[t2.target][l].__args=t2.__args;if(t2.subInput)result[t2.target][l].subInput=t2.subInput})}return result},makeRootTransferrable:function(){let roots={};for(const r in this.__node.graph.__node.roots){let properties=this.__node.graph.__node.roots[r];if(typeof properties==="function"){roots[r]=properties.toString()}else if(typeof properties!=="object"){roots[r]=properties}else{roots[r]={};let keys=Object.getOwnPropertyNames(properties).filter(v=>!objProps2.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter(v=>!objProps2.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(typeof properties[key]==="function"){roots[r][key]=properties[key].toString()}else if(typeof properties[key]==="object")roots[r][key]=stringifyWithFunctionsAndCircularRefs(properties[key]);else roots[r][key]=properties[key]}}}return roots},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key of properties){if(typeof node[key]==="function"){let str=node[key].toString();let isNative=str.indexOf("[native code]")>-1;result[key]={type:"function",args:getFnParamNames(node[key]),native:isNative}}else result[key]=typeof node[key]}return result}return void 0},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]?.type==="function"){if(props[key].native||props[key].args){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{proxy[key]=()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})}}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};if(connection.run)return connection.run("receiveClass",[str,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str=fn.toString();let message={route:"setNode",args:[str,fnName]};if(connection.run)return connection.run("setNode",[str,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str,fnName]},void 0);return new Promise(r=>r(fnName))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str,fnName]}));return new Promise(r=>r(fnName))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var objProps2=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var ECSService=class extends Service{entities={};systems={};entityMap=new Map;entityKeyMap=new Map;order=[];animating=false;entityCt=0;systemCt=0;constructor(options){super(options);this.load(this);if(options?.systems)for(const key in options.systems){this.addSystem(options.systems[key],void 0,void 0,void 0,void 0,options.order)}if(options?.entities){for(const key in options.entities){this.addEntity(options.entities[key],options.entities[key].components)}}}updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};stop=()=>{this.animating=false};start=filter=>{this.animateEntities(filter)};addEntities=(prototype,components={},count=1)=>{let i=0;let newEntities={};while(i{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};removeEntities(entities){if(!Array.isArray(entities))entities=Object.keys(entities);entities.forEach(t2=>{this.removeEntity(t2)})}removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};bufferValues=(entities,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let entkeys=Object.keys(entities);if(keys)buffer=new Float32Array(entkeys.length*keys.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys.length)}else buffer=new Float32Array(entkeys.length)}}let i=0;for(const key in entities){if(entities[key][property]){if(keys){for(let j=0;j>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return new sjcl.hash.sha256().update(a).finalize()};sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=sjcl_default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};static generateSecret(){return sjcl_default.codec.base64.fromBits(sjcl_default.random.randomWords(8,10))}encrypt(message,key){message=sjcl_default.encrypt(key,message).cipher;return message}decrypt(message,key){message=sjcl_default.decrypt(key,message);return message}encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=sjcl_default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message}};var http=__toESM(require("http"));var https=__toESM(require("https"));var fs=__toESM(require("fs"));var path=__toESM(require("path"));function htmlBodyBoilerPlate(html){let template=``;if(Array.isArray(html)){html.forEach(src=>{template+=src})}else{template+=html}template+=``;return template}function scriptBoilerPlate(scripts){let template=``;if(Array.isArray(scripts)){scripts.forEach(src=>{template+=``})}else{template+=``}template+=``;return template}var defaultServiceWorker=function(cacheExpirationDays=4/24){return`//https://github.com/ibrahima92/pwa-with-vanilla-js - -//https://github.com/ibrahima92/pwa-with-vanilla-js -let cacheName = 'pwa-assets'; -const assets = [ - "/", - "/index.html", - "/dist/index.css", //alt default paths - "/dist/index.js", - '/favicon.ico' -]; - -let cacheExpiration = 1000 * 60 * //seconds - 60 * //minutes - 24 * //hours - ${cacheExpirationDays}; //days - -let isValid = function (response) { - if (!response) return false; - var fetched = response.headers.get('sw-fetched-on'); - if (fetched && (!navigator.onLine || (parseFloat(fetched) + (cacheExpiration)) > new Date().getTime())) - return true; - return false; -}; - -self.addEventListener("install", installEvent => { - installEvent.waitUntil( - caches.open(cacheName).then(cache => { - cache.addAll(assets); - }) - ); -}); - -self.addEventListener("fetch", fetchEvent => { //https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/ - fetchEvent.respondWith( - caches.match(fetchEvent.request).then(function (response) { - - // If there's a cached API and it's still valid, use it - if (isValid(response)) { - return response; - } - - // Otherwise, make a fresh API call - if(response && !assets.includes(fetchEvent.request.url)) return response; - // Otherwise, make a fresh API call - else return fetch(fetchEvent.request).then(function (response) { - - // Cache for offline access - if(assets.includes(fetchEvent.request.url)){ - var copy = response.clone(); - fetchEvent.waitUntil(caches.open(cacheName).then(function (cache) { - var headers = new Headers(copy.headers); - headers.append('sw-fetched-on', new Date().getTime()); - return copy.blob().then(function (body) { - return cache.put(fetchEvent.request, new Response(body, { - status: copy.status ? copy.status : 200, - statusText: copy.statusText, - headers: headers - })); - }); - })); - } - - // Return the requested file - return response; - - }) - // .catch(function (error) { - // return caches.match(request).then(function (response) { //fallback to offline cache - // return response || caches.match('/offline.json'); //todo: figure out what is supposed to go in offline.json (https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/) - // }); - // }); - })); -}); - -`};var defaultManifest=(pwaName="PWA")=>{return`{ - "short_name": "${pwaName}", - "name": "${pwaName}", - "start_url": "/", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "description": "${pwaName} Test", - "lang": "en-US", - "permissions": [ - "storage" - ], - "icons":[{ - "src": "./assets/logo196.png", - "sizes": "196x196" - }, - { - "src": "./assets/logo512.png", - "sizes": "512x512" - }] -}`};var HTTPbackend=class extends Service{name="http";server;debug=false;servers={};mimeTypes={".html":"text/html",".htm":"text/html",".js":"text/javascript",".css":"text/css",".json":"application/json",".txt":"text/plain",".png":"image/png",".jpg":"image/jpg",".jpeg":"image/jpg",".gif":"image/gif",".svg":"image/svg+xml",".xhtml":"application/xhtml+xml",".bmp":"image/bmp",".wav":"audio/wav",".mp3":"audio/mpeg",".mp4":"video/mp4",".xml":"application/xml",".webm":"video/webm",".webp":"image/webp",".weba":"audio/webm",".woff":"font/woff","woff2":"font/woff2",".ttf":"application/font-ttf",".eot":"application/vnd.ms-fontobject",".otf":"application/font-otf",".wasm":"application/wasm",".zip":"application/zip",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".tif":"image/tiff",".sh":"application/x-sh",".csh":"application/x-csh",".rar":"application/vnd.rar",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".mpeg":"video/mpeg",".mjs":"text/javascript",".cjs":"text/javascript",".jsonld":"application/ld+json",".jar":"application/java-archive",".ico":"image/vnd.microsoft.icon",".gz":"application/gzip","epub":"application/epub+zip",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".csv":"text/csv",".avi":"video/x-msvideo",".aac":"audio/aac",".mpkg":"application/vnd.apple.installer+xml",".oga":"audio/ogg",".ogv":"video/ogg","ogx":"application/ogg",".php":"application/x-httpd-php",".rtf":"application/rtf",".swf":"application/x-shockwave-flash",".7z":"application/x-7z-compressed",".3gp":"video/3gpp"};constructor(options,settings){super(options);this.load(this);if(settings){this.setupServer(settings)}}onStarted=(protocol,host,port)=>{console.log(`\u{1F431} Node server running at - ${protocol}://${host}:${port}/`)};setupServer=(options={protocol:"http",host:"localhost",port:8080,startpage:"index.html"},requestListener,onStarted)=>{if(options.pages){for(const key in options.pages){if(typeof options.pages[key]==="string"){this.addPage(`${options.port}/${key}`,options.pages[key])}else if(typeof options.pages[key]==="object"||typeof options.pages[key]==="function"){if(options.pages[key].template){options.pages[key].get=options.pages[key].template}let rt=`${options.port}/${key}`;if(key!=="_all")this.load({[rt]:options.pages[key]})}}}this.setupHTTPserver(options,requestListener,onStarted)};open=this.setupServer;setupHTTPserver=(options={host:"localhost",port:8080,startpage:"index.html",errpage:void 0},requestListener,onStarted=()=>{this.onStarted("http",options.host,options.port)})=>{const host=options.host?options.host:"localhost";const port=options.port?options.port:8e3;if(!host||!port)return;const address=`${host}:${port}`;if(this.servers[address])this.terminate(this.servers[address]);if(!("keepState"in options))options.keepState=true;const served={server:void 0,type:"httpserver",address,...options};if(!requestListener)requestListener=(request,response)=>{let received={args:{request,response},method:request.method,served};let url=request.url.slice(1);if(!url)url="/";if(options.debug){let time=getHoursAndMinutes(new Date);console.log(time," | ","From: ",request.socket?.remoteAddress,"For: ",request.url," | ",request.method)}if(options.pages){getPageOptions.call(this,url,received,options.pages,request,response,options.port)}else received.route=url;this.receive(received)};let server=void 0;if(options.protocol==="http")server=http.createServer(requestListener);else{let opts;if(options.keypath&&options.certpath){opts={key:fs.readFileSync(options.keypath),cert:fs.readFileSync(options.certpath),passphrase:options.passphrase};server=https.createServer(opts,requestListener)}else console.error("Error, key and/or cert .pem SSL files not provided. See OpenSSL certbot for more info on how to create free SSL certifications, or create your own self-signed one for local development.")}if(!server){console.error("Server not successfully created.");return void 0}served.server=server;served.terminate=()=>{this.terminate(served)};served.service=this;this.servers[address]=served;served._id=options._id?options._id:address;return new Promise((resolve,reject)=>{let resolved;server.on("error",err=>{if(served.onerror)served.onerror(err,served);else console.error("Server error:",err.toString());if(!resolved)reject(err)});server.on("clientError",(err,socket)=>{if(served.onerror)served.onerror(err,served);else console.error(getHoursAndMinutes(new Date)," | Server clientError:",err.toString()," | From: ",socket.remoteAddress);if(socket)socket.destroy()});server.on("tlsClientError",(err,socket)=>{if(served.onerror)served.onerror(err,served);else console.error(getHoursAndMinutes(new Date)," | Server tlsClientError: ",err.toString()," | From: ",socket.remoteAddress);if(socket)socket.destroy()});server.on("upgrade",(request,socket,head)=>{if(served.onupgrade)served.onupgrade(request,socket,head,served)});server.listen(port,host,()=>{onStarted();if(served.onopen)served.onopen(served);resolved=true;resolve(served)})})};transmit=(message,options,ondata,onend)=>{let input=message;if(typeof input==="object"&&!input.byteLength)input=JSON.stringify(input);if(typeof options==="string"&&message)return this.POST(options,message);else if(typeof options==="string")return this.GET(options);if(!options){let server=this.servers[Object.keys(this.servers)[0]];options={protocol:server.protocol,host:server.host,port:server.port,method:"POST",path:message.route,headers:{"Content-Type":"application/json","Content-Length":input.length}}}else if(!options.headers){options.headers={"Content-Type":"application/json","Content-Length":input.length}}return this.request(options,input,ondata,onend)};withResult=(response,result,message)=>{if(result&&!response.writableEnded&&!response.destroyed){let mimeType="text/plain";let head={};if(typeof result==="string"){let extname2=path.extname(result);if(extname2&&fs.existsSync(path.join(process.cwd(),result))){mimeType=this.mimeTypes[extname2]||"application/octet-stream";result=fs.readFileSync(path.join(process.cwd(),result));if(mimeType==="text/html"&&(message.served?.pages?._all||message.served?.pages?.[message.route])){let{templateString,headers}=this.injectPageCode(result.toString(),message.route,message.served);result=templateString;Object.assign(head,headers)}}else if(typeof result==="string"&&result.includes("<")&&result.includes(">")&&result.indexOf("<")")){head["Content-Type"]="text/html";if(message?.served?.pages?._all||message?.served?.pages?.[message.route]){let{templateString,headers}=this.injectPageCode(result,message.route,message.served);result=templateString;Object.assign(head,headers)}response.writeHead(200,head);response.end(result,"utf-8");return}}else if(typeof result==="object"){result=JSON.stringify(result);mimeType="application/json"}head["Content-Type"]=mimeType;response.writeHead(200,head);response.end(result,"utf-8")}else{try{response.destroy()}catch{}}};injectPageCode=(templateString,url,served)=>{if(served?.pages?.[url]?.inject){if(typeof served.pages[url].inject==="object")templateString=this.buildPage(served.pages[url].inject,templateString);else if(typeof served.pages[url].inject==="function")templateString+=served.pages[url].inject();else if(typeof served.pages[url].inject==="string"||typeof served.pages[url].inject==="number")templateString+=served.pages[url].inject}if(served?.pages?._all?.inject){if(typeof served.pages._all.inject==="object")templateString=this.buildPage(served.pages._all.inject,templateString);else if(typeof served.pages._all.inject==="function")templateString+=served.pages._all.inject();else if(typeof served.pages._all.inject==="string"||typeof served.pages._all.inject==="number")templateString+=served.pages._all.inject}let headers={};if(served.pages._all.headers)Object.assign(headers,served.pages._all.headers);if(served.pages[url].headers)Object.assign(headers,served.pages[url].headers);return{templateString,headers}};receive=message=>{if(this.debug)console.log(message.args.request.method,message.args.request.url);let result=new Promise((resolve,reject)=>{this.responsePromiseHandler(resolve,reject,message,message.args.request,message.args.response,message.method,message.served)}).catch(er=>{console.error("Request Error:",er)});return result};responseOnErrorPromiseHandler=(response,reject,err)=>{if(!response.writableEnded||!response.destroyed){response.statusCode=400;response.end(void 0,void 0);reject(err)}else{try{response.destroy()}catch{}reject(err)}};getFailedPromiseHandler=(resolve,reject,requestURL,message,response,served)=>{if(response.writableEnded||response.destroyed)reject(requestURL);if(requestURL=="./"||requestURL==served?.startpage){let template=`

Brains@Play Server

`;if(served?.pages?._all||served?.pages?.error){let{templateString,headers}=this.injectPageCode(template,message.route,served);template=templateString}response.writeHead(200,{"Content-Type":"text/html"});response.end(template,"utf-8");resolve(template);if(served?.keepState)this.setState({[served.address]:template});return}else if(this.debug)console.log(`File ${requestURL} does not exist on path!`);response.writeHead(500);response.end(void 0,void 0);reject(requestURL)};handleBufferedPostBodyPromiseHandler=(resolve,body,message,response,served)=>{body=Buffer.concat(body).toString();if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}let route,method,args;if(body?.route){route=body.route;method=body.method;args=body.args;if(!route){if(typeof body.route==="string"){if(body.route.includes("/")&&body.route.length>1)body.route=body.route.split("/").pop()}route=body.route}}if(!route){if(message?.route){let route2=message.route;method=message.method;args=message.args;if(!route2){if(typeof message.route==="string"){if(message.route.includes("/")&&message.route.length>1)message.route=message.route.split("/").pop()}route2=message.route}}}let res=body;if(route){if(this.restrict?.[route]){try{response.destroy()}catch{}resolve(res)}else{if(body.method){res=this.handleMethod(route,method,args)}else if(body.node){res=this.handleGraphNodeCall(body.node,body.args)}else res=this.handleServiceMessage({route,args,method});if(res instanceof Promise){res.then(r=>{this.withResult(response,r,message);if(served?.keepState)this.setState({[served.address]:res});resolve(res)})}else{this.withResult(response,res,message);if(served?.keepState)this.setState({[served.address]:res});resolve(res)}}}else if(!response.writableEnded||!response.destroyed){response.statusCode=200;response.end(void 0,void 0);resolve(res)}else{try{response.destroy()}catch{}resolve(res)}};onRequestFileReadPromiseHandler=(error,content,resolve,reject,requestURL,response,message,served)=>{if(error){if(error.code=="ENOENT"){if(served?.errpage){fs.readFile(served.errpage,(er,content2)=>{response.writeHead(404,{"Content-Type":"text/html"});if(served.pages?._all||served.pages?.error){let{templateString,headers}=this.injectPageCode(content2.toString(),message.route,served);content2=templateString}response.end(content2,"utf-8");reject(content2)})}else{response.writeHead(404,{"Content-Type":"text/html"});let content2=`

Error: ${error.code}

`;if(served?.pages?._all||served?.pages?.[message.route]){let{templateString,headers}=this.injectPageCode(content2.toString(),message.route,served);content2=templateString}response.end(content2,"utf-8");reject(error.code)}}else{response.writeHead(500);response.end("Something went wrong: "+error.code+" ..\n","utf-8");reject(error.code)}}else{var extname2=String(path.extname(requestURL)).toLowerCase();var contentType=this.mimeTypes[extname2]||"application/octet-stream";let head={"Content-Type":contentType};if(contentType==="text/html"&&(served?.pages?._all||served?.pages?.[message.route])){let{templateString,headers}=this.injectPageCode(content.toString(),message.route,served);Object.assign(head,headers);content=templateString}response.writeHead(200,head);response.end(content,"utf-8");resolve(content)}};responsePromiseHandler=(resolve,reject,message,request,response,method,served)=>{response.on("error",err=>{if(served.debug){let time=getHoursAndMinutes(new Date);console.error(time,"| Response Error: ",err," From: ",request.socket?.remoteAddress," For: ",request.url," | ",request.method)}this.responseOnErrorPromiseHandler(response,reject,err);request.destroy();request.socket?.destroy()});if(method==="GET"||method==="get"){var requestURL="."+request.url;if(request.url&&this.restrict?.[request.url])reject(request.url);if(requestURL=="./"&&served?.startpage){requestURL=served.startpage}if(requestURL.includes("?"))requestURL=requestURL.substring(0,requestURL.indexOf("?"));if((request.url!=="/"||served?.startpage)&&fs.existsSync(path.join(process.cwd(),requestURL))){if(response.writableEnded||response.destroyed)reject(requestURL);else{fs.readFile(path.join(process.cwd(),requestURL),(error,content)=>{this.onRequestFileReadPromiseHandler(error,content,resolve,reject,requestURL,response,message,served)})}}else if(message.route){let route;if(served){let rt=`${served.port}/${message.route}`;if(this.__node.nodes.get(rt))route=rt}if(!route&&this.__node.nodes.get(message.route))route=message.route;if(route){let res;if(message.method){res=this.handleMethod(route,message.method,void 0)}else if(message.node){res=this.handleGraphNodeCall(message.node,void 0)}else res=this.handleServiceMessage({route,args:void 0,method:message.method});if(res instanceof Promise)res.then(r=>{if(served?.keepState)this.setState({[served.address]:res});this.withResult(response,r,message);resolve(res)});else if(res){if(served?.keepState)this.setState({[served.address]:res});this.withResult(response,res,message);resolve(res)}}else if(message.redirect){response.writeHead(301,{"Location":message.redirect});response.end();resolve(true)}else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served)}else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served)}else{let requestBody;let timedOut=true;let timeout;request.on("data",chunk=>{if(!requestBody)requestBody=[];requestBody.push(chunk);if(timedOut){timedOut=false;if(timeout)clearTimeout(timeout)}}).on("end",()=>{this.handleBufferedPostBodyPromiseHandler(resolve,requestBody,message,response,served)});timeout=setTimeout(()=>{if(timedOut){let errMessage=new Error(`Request timed out from | ${request.socket?.remoteAddress} | For: ${request.url} | ${request.method}`);request.destroy(errMessage);served.server.emit("clientError",errMessage,request.socket);if(served.debug){console.error(errMessage)}reject(errMessage)}},served.timeout?served.timeout:1e3)}};request=(options,send,ondata,onend)=>{let client=http;if(options.protocol?.includes("https")){client=https}delete options.protocol;const req=client.request(options,res=>{if(ondata)res.on("data",ondata);if(onend)res.on("end",onend)});if(options.headers){for(const head in options.headers){req.setHeader(head,options.headers[head])}}if(send)req.write(send);req.end();return req};POST=(url,data,headers)=>{let urlstring=url;if(urlstring instanceof URL)urlstring=url.toString();let protocol=urlstring.startsWith("https")?"https":"http";let host,port,path3;let split=urlstring.split("/");split.forEach(s=>{if(s.includes(":")){let ss=s.split(":");host=ss[0];port=ss[1]}});if(split.length>3){path3=split.slice(3).join("/")}let req=this.request({protocol,host,port,path:path3,method:"POST",headers},data);return req};GET=url=>{return new Promise((resolve,reject)=>{let client=http;let urlstring=url;if(url instanceof URL)urlstring=url.toString();if(urlstring.includes("https")){client=https}client.get(url,resp=>{let chunks=[];resp.on("data",chunk=>{chunks.push(chunk)});resp.on("end",()=>{resolve(Buffer.concat(chunks))})}).on("error",err=>{reject(err)})})};terminate=served=>{if(typeof served==="string")served=this.servers[served];if(typeof served==="object"){served.server.close();if(served.onclose)served.onclose(served)}};getRequestBody(req){let chunks=[];return new Promise((resolve,reject)=>{req.on("data",chunk=>{chunks.push(chunk)}).on("end",()=>{resolve(Buffer.concat(chunks))}).on("error",er=>{let errMessage=new Error(`Request timed out from | ${req.socket?.remoteAddress} | For: ${req.url} | ${req.method}`);req.destroy(errMessage);reject(errMessage)})})}addPage=(path3,template)=>{if(typeof template==="string"){if(!template.includes(""+template+""}if(typeof this.__node.roots?.[path3]==="object"){this.__node.roots[path3].get=template;this.__node.nodes.get(path3).get=template}else this.load({[path3]:{get:template}})};addHTML=(path3,template)=>{if(typeof template==="string"){if(!template.includes("<")||!template.includes(">"))template="
"+template+"
"}if(typeof this.__node.roots?.[path3]==="object"){this.__node.roots[path3].get=template;this.__node.nodes.get(path3).get=template}else this.load({[path3]:{get:template}})};buildPage=(pageStructure,baseTemplate)=>{let result=``;if(baseTemplate)result+=baseTemplate;let appendTemplate=(obj,r,res)=>{if(!Array.isArray(obj[r])&&typeof obj[r]==="object"){for(const key in obj){appendTemplate(obj,key,res)}}else if(this.__node.nodes.get(r)?.get){let toAdd=this.__node.nodes.get(r)?.get;if(typeof toAdd==="function"){if(Array.isArray(obj[r])){toAdd=toAdd(...obj[r])}else toAdd=toAdd(obj[r])}if(typeof toAdd==="string"){let lastDiv=res.lastIndexOf("<");if(lastDiv>0){let end=res.substring(lastDiv);res=res.substring(0,lastDiv)+toAdd+end}else res+=toAdd}}else if(this.__node.nodes.get(r)?.__operator){let routeresult;if(this.__node.nodes.get(r)?.__operator)routeresult=this.__node.nodes.get(r).__operator(obj[r]);if(typeof routeresult==="string"){let lastDiv=res.lastIndexOf("<");if(lastDiv>0){let end=res.substring(lastDiv);res=res.substring(0,lastDiv)+routeresult+end}else res+=routeresult}}else if(typeof this.__node.nodes.get(r)==="string")res+=this.__node.nodes.get(r);return res};if(Array.isArray(pageStructure)){pageStructure.forEach(r=>{result=appendTemplate(pageStructure,r,result)})}else if(typeof pageStructure==="object"){for(const r in pageStructure){result=appendTemplate(pageStructure,r,result)}}else if(typeof pageStructure==="string")result+=pageStructure;else if(typeof pageStructure==="function")result+=pageStructure();return result};hotreload=(socketURL=`http://localhost:8080/wss`,esbuild_cssFileName)=>{if(socketURL instanceof URL)socketURL=socketURL.toString();const HotReloadClient=(socketUrl,esbuild_cssFileName2)=>{let socket=new WebSocket(socketUrl);function reloadLink(file){let split=file.includes("/")?file.split("/"):file.split("\\");let fname=split[split.length-1];var links=document.getElementsByTagName("link");for(var cl in links){var link=links[cl];if(!file||link.href?.includes(fname)){let href=link.getAttribute("href").split("?")[0];let newHref=href+="";link.setAttribute("href",newHref)}}}function reloadAsset(file,reloadscripts,isJs){let split=file.includes("/")?file.split("/"):file.split("\\");let fname=split[split.length-1];let elements=document.querySelectorAll("[src]");let found=false;for(const s of elements){if(s.src.includes(fname)){if(s.tagName==="SCRIPT"&&!reloadscripts){window.location.reload();return}else{let placeholder=document.createElement("object");s.insertAdjacentElement("afterend",placeholder);s.remove();let elm=s.cloneNode(true);placeholder.insertAdjacentElement("beforebegin",elm);placeholder.remove();found=true}}}if(!found)window.location.reload()}socket.addEventListener("message",ev=>{let message=ev.data;if(typeof message==="string"&&message.startsWith("{")){message=JSON.parse(message)}if(message.file){let f=message.file;let rs=message.reloadscripts;if(f.endsWith("html")||f.endsWith("xml")||f.endsWith("wasm")){window.location.reload()}else if(f.endsWith("css")){if(!esbuild_cssFileName2.endsWith("css"))esbuild_cssFileName2+=".css";reloadLink(esbuild_cssFileName2)}else if(f.endsWith("js")||f.endsWith("ts")||f.endsWith("jsx")||f.endsWith("tsx")||f.endsWith("vue")){reloadAsset(f,rs)}else{reloadLink(f);reloadAsset(f)}}});socket.addEventListener("close",()=>{const interAttemptTimeoutMilliseconds=100;const maxDisconnectedTimeMilliseconds=3e3;const maxAttempts=Math.round(maxDisconnectedTimeMilliseconds/interAttemptTimeoutMilliseconds);let attempts=0;const reloadIfCanConnect=()=>{attempts++;if(attempts>maxAttempts){console.error("Could not reconnect to dev server.");return}socket=new WebSocket(socketUrl);socket.onerror=er=>{console.error(`Hot reload port disconnected, will reload on reconnected. Attempt ${attempts} of ${maxAttempts}`)};socket.addEventListener("error",()=>{setTimeout(reloadIfCanConnect,interAttemptTimeoutMilliseconds)});socket.addEventListener("open",()=>{location.reload()})};reloadIfCanConnect()})};return` - - `};pwa=(pwaName="PWA",cacheExpirationDays=4/24,serviceWorkerUrl="service-worker.js")=>{if(!fs.existsSync(serviceWorkerUrl)){fs.writeFileSync(path.join(process.cwd(),serviceWorkerUrl),defaultServiceWorker(cacheExpirationDays))}if(!fs.existsSync("manifest.webmanifest")){fs.writeFileSync(path.join(process.cwd(),"/manifest.webmanifest"),defaultManifest(pwaName))}function ServiceWorkerInstaller(serviceWorkerUrl2){if(!Array.from(document.head.querySelectorAll("link")).find(elm=>{if(elm.href.includes("manifest"))return true})){document.head.insertAdjacentHTML("beforeend",``)}const isLocalhost=Boolean(window.location.hostname==="localhost"||window.location.hostname==="[::1]"||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/));function registerSW(){navigator.serviceWorker.register(serviceWorkerUrl2).then(registration=>{registration.onupdatefound=()=>{const installingWorker=registration.installing;if(installingWorker==null){return}installingWorker.onstatechange=()=>{if(installingWorker.state==="installed"){if(navigator.serviceWorker.controller){console.log("New content is available and will be used when all tabs for this page are closed.")}else{console.log("Content is cached for offline use.")}}}}}).catch(error=>{console.error("Error during service worker registration:",error)})}if("serviceWorker"in navigator)addEventListener("load",()=>{if(isLocalhost){fetch(serviceWorkerUrl2).then(response=>{const contentType=response.headers.get("content-type");if(response.status===404||contentType!=null&&contentType.indexOf("javascript")===-1){navigator.serviceWorker.ready.then(registration=>{registration.unregister().then(()=>{window.location.reload()})})}else{registerSW()}}).catch(()=>{console.log("No internet connection found. App is running in offline mode.")});navigator.serviceWorker.ready.then(()=>{console.log("This web app is being served cache-first by a service worker.")})}else{registerSW()}})}return` - - `}};function getPageOptions(url,received,pages,request,response,port){let pageOptions=pages[url];let key=url;if(!pageOptions){let url2="/"+url;pageOptions=pages[url2];key=url2;if(!pageOptions&&!path.extname(url)){let split=url.split("/");key=split[0]+"/*";if(pages[key]){pageOptions=pages[key];received.route=key;request.url=key}else{let spl=url2.split("/");spl[spl.length-1]="";key=spl.join("/")+"*";if(pages[key]){pageOptions=pages[key];received.route=key;request.url=key}}}else{received.route=url2;request.url=url2}}else{received.route=url;request.url=url}if(typeof pageOptions==="object"){if(pageOptions.redirect){url=pageOptions.redirect;received.redirect=url;received.route=url}if(pageOptions.onrequest){if(typeof pageOptions.onrequest==="string"){pageOptions.onrequest=this.__node.nodes.get(pageOptions.onrequest)}if(typeof pageOptions.onrequest==="object"){if(pageOptions.onrequest.__operator){pageOptions.onrequest.__operator(pageOptions,request,response)}}else if(typeof pageOptions.onrequest==="function"){pageOptions.onrequest(this,this.__node.nodes.get(`${port}/${key}`),request,response)}}}return pageOptions}function getHoursAndMinutes(date){let hours=date.getHours();let minutes=date.getMinutes();hours=hours<10?"0"+hours:hours;minutes=minutes<10?"0"+minutes:minutes;return`${hours}:${minutes}`}var import_better_sse=__toESM(require_build());var SSEbackend=class extends Service{name="sse";debug=false;servers={};eventsources={};connections={servers:this.servers,eventsources:this.eventsources};constructor(options){super(options);this.load(this)}openSSE=options=>{const server=options.server;let path3=options.path;if(this.servers[path3]){return false}const channel=(0,import_better_sse.createChannel)();let sse={type:"sse",channel,sessions:{},requests:{},...options};this.servers[path3]=sse;sse._id=options._id?options._id:path3;const send=(message,eventName,sessionId)=>{return this.transmit(message,path3,eventName,sessionId)};const terminate=()=>{return this.terminate(path3)};let request=(message,method,sessionId,eventName)=>{if(!sessionId){let promises=[];for(const key in sse.sessions){promises.push(this.request(message,path3,key,eventName))}return promises}return this.request(message,path3,method,sessionId,eventName)};let post=(route,args,method,sessionId,eventName)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,path3,eventName,sessionId)};let run=(route,args,method,sessionId,eventName)=>{let r={route,args};if(!sessionId){let promises=[];for(const key in sse.sessions){promises.push(this.request(r,path3,key,eventName))}return promises}return this.request(r,path3,method,sessionId,eventName)};let subscribe=(route,callback,args,key,subInput,sessionId,eventName)=>{return this.subscribeToSSE(route,options.url,callback,args,key,subInput,sessionId,eventName)};let unsubscribe=(route,sub,sessionId,eventName)=>{return run("unsubscribe",[route,sub],void 0,sessionId,eventName)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;let onRequest=(req,response)=>{if(req.url?.includes(path3)){if(req.method==="GET"){if(this.debug)console.log("SSE Request",path3);(0,import_better_sse.createSession)(req,response).then(session=>{channel.register(session);let _id=`sse${Math.floor(Math.random()*1e15)}`;sse.sessions[_id]=session;this.eventsources[_id]={_id,session,served:sse,send:(message,eventName)=>{return send(message,eventName,_id)},request:(message,method,eventName)=>{return request(message,method,_id,eventName)},post:(route,args,method,eventName)=>{return post(route,args,method,_id,eventName)},run:(route,args,method,eventName)=>{return run(route,args,method,_id,eventName)},subscribe:(route,callback)=>{return subscribe(route,callback,void 0,_id)},unsubscribe:(route,sub,eventName)=>{return unsubscribe(route,sub,_id,eventName)},terminate:()=>{delete this.eventsources[_id];delete sse.sessions[_id];return true},onclose:(session2,sse2,_id2,req2,res)=>{if(sse2.onconnectionclose)sse2.onconnectionclose(session2,sse2,_id2,req2,res)},graph:this};session.push(JSON.stringify({route:"setId",args:_id}));session.on("close",()=>{let obj=this.eventsources[_id];let onclose=obj.onclose;delete this.eventsources[_id];if(onclose)obj.onclose(session,sse,_id,req,response)});if(sse.onconnection){sse.onconnection(session,sse,_id,req,response)}})}else{let body=[];req.on("data",chunk=>{body.push(chunk)}).on("end",()=>{body=Buffer.concat(body).toString();if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}let route,method,args,callbackId;if(body?.route||body?.callbackId){method=body.method;args=body.args;callbackId=body.callbackId;if(typeof body.route==="string"){if(body.route.includes("/")&&body.route.length>1)body.route=body.route.split("/").pop();route=this.__node.roots?.[body.route]}}if(route){let res=this.receive({route,args,method})}else if(callbackId&&sse.requests[callbackId]){sse.requests[callbackId](args)}if(this.__node.keepState)this.setState({[path3]:body})})}}};let requestListeners=server.listeners("request");server.removeAllListeners("request");const otherListeners=(req,res)=>{requestListeners.forEach(l=>{l(req,res)})};const sseListener=(req,res)=>{if(req.url)if(req.url.indexOf(path3)>-1){if(!this.servers[path3]){server.removeListener("request",sseListener);server.addListener("request",otherListeners)}onRequest(req,res)}else otherListeners(req,res)};server.addListener("request",sseListener);server.addListener("close",()=>{if(sse.onclose)sse.onclose(sse)});return sse};open=this.openSSE;streamIterable=(path3,iterable,sessionId,eventName="message")=>{let server=this.servers[path3];if(server){if(sessionId){if(server.sessions[sessionId]){return server.sessions[sessionId].iterate(iterable,{eventName})}}else{let promises=[];for(const key in server.sessions){promises.push(server.sessions[key].iterate(iterable))}return promises}}};streamReadable=(path3,readable,sessionId,eventName="message")=>{let server=this.servers[path3];if(server){if(sessionId){if(server.sessions[sessionId]){return server.sessions[sessionId].stream(readable,{eventName})}}else{let promises=[];for(const key in server.sessions){promises.push(server.sessions[key].stream(readable))}return promises}}};transmit=(data,path3,eventName,sessionId)=>{if(!path3&&(typeof data==="object"&&!data.byteLength||typeof data==="number")){if(data?.route){let keys=Object.keys(this.servers);if(keys.length>0){let evs=this.servers[keys[0]];if(evs.channels?.includes(data.route)){path3=evs.path;eventName=data.route}}if(!path3&&data.route){if(this.servers[data.route])path3=data.route}}data=JSON.stringify(data)}if(!path3)path3=Object.keys(this.servers)[0];if(path3&&this.servers[path3]){if(sessionId){if(this.servers[path3].sessions[sessionId]?.isConnected){this.servers[path3].sessions[sessionId].push(data,eventName)}else if(this.servers[path3].sessions[sessionId]){delete this.servers[path3].sessions[sessionId];return false}}else this.servers[path3].channel.broadcast(data,eventName);return true}return false};request=(message,path3,method,sessionId,eventName)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,path3,callbackId,sessionId]};if(method)req.method=method;let sse=this.servers[path3];let callback=result=>{res(result)};sse.requests[callbackId]=callback;if(sse){if(sessionId){if(sse.sessions[sessionId])sse.sessions[sessionId].push(JSON.stringify(req),eventName)}else sse.channel.broadcast(JSON.stringify(req),eventName)}})};runRequest=(message,path3,callbackId,sessionId)=>{let res=this.receive(message);if(path3){let sse=this.servers[path3];if(sse){if(res instanceof Promise){res.then(r=>{if(sessionId){if(sse.sessions[sessionId]){sse.sessions[sessionId].push(JSON.stringify({args:r,callbackId}))}}else{sse.channel.broadcast(JSON.stringify({args:r,callbackId}))}})}else{if(sessionId){if(sse.sessions[sessionId]){sse.sessions[sessionId].push(JSON.stringify({args:res,callbackId}))}}else sse.channel.broadcast(JSON.stringify({args:res,callbackId}))}}}return res};subscribeSSE=(route,path3,args,key,subInput,sessionId,eventName)=>{if(this.restrict?.[route])return void 0;if(this.servers[path3]){return this.subscribe(route,res=>{this.servers[path3].send({args:res,callbackId:route},eventName,sessionId)},args,key,subInput)}};subscribeToSSE=(route,path3,callback,args,key,subInput,sessionId,eventName)=>{if(this.servers[path3]){this.__node.state.subscribeEvent(path3,res=>{if(res?.callbackId===route){if(!callback)this.setState({[path3]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});if(sessionId){if(this.servers[path3].sessions[sessionId]){return this.eventsources[sessionId].run("subscribeSSE",{route:"subscribeSSE",args:[route,path3,args,key,subInput]},void 0,eventName)}}else{let promises=[];for(const k in this.servers[path3].sessions){promises.push(this.eventsources[k].run("subscribeSSE",{route:"subscribeSSE",args:[route,path3,args,key,subInput]},void 0,eventName))}return promises}}};terminate=sse=>{if(typeof sse==="object")delete this.servers[sse.path];else if(typeof sse==="string"){delete this.servers[sse];delete this.eventsources[sse]}return true}};var import_stream=__toESM(require_stream(),1);var import_receiver=__toESM(require_receiver(),1);var import_sender=__toESM(require_sender(),1);var import_websocket=__toESM(require_websocket(),1);var import_websocket_server=__toESM(require_websocket_server(),1);var wrapper_default=import_websocket.default;var WSSbackend=class extends Service{name="wss";debug=false;servers={};sockets={};connections={servers:this.servers,sockets:this.sockets};constructor(options){super(options);this.load(this)}open=options=>{if(options?.server){return this.setupWSS(options)}else return this.openWS(options)};setupWSS=options=>{let port=options.port;let path3=options.path;const server=typeof options.server==="object"?options.server:void 0;let host=options.host;delete options.server;if(!("keepState"in options))options.keepState=true;let opts={};if(options.noServer)opts.noServer=true;else if(port){if(port)opts.port=port}else if(server)opts.server=server;if(options.perMessageDeflate)opts.perMessageDeflate=options.perMessageDeflate;if(typeof options.serverOptions)Object.assign(opts,options.serverOptions);const wss=new import_websocket_server.default(opts);let address="";if(!host&&server){let addr=server.address();if(!port)port=addr.port;address=addr.address}else if(host)address=host;if(port)address+=":"+port;if(path3){if(!path3.startsWith("/"))path3="/"+path3;address+=path3}this.servers[address]={type:"wss",wss,clients:{},address,...options};if(!options.onmessage)options.onmessage=data=>{if(data instanceof Buffer)data=data.toString();if(options.debug){console.log(data)}const result=this.receive(data,wss,this.servers[address]);if(options.keepState)this.setState({[address]:result})};wss.addListener("connection",(ws,request2)=>{if(this.debug)console.log(`New socket connection on ${address}`);let clientId=`socket${Math.floor(Math.random()*1e12)}`;this.servers[address].clients[clientId]=ws;ws.send(JSON.stringify({route:"setId",args:clientId}));this.openWS({socket:ws,address:clientId,_id:clientId,debug:options.debug,onclose:(code,reason)=>{if(this.servers[address].onconnectionclosed)this.servers[address].onconnectionclosed(code,reason,ws,this.servers[address],clientId);delete this.servers[address].clients[clientId]}});if(options.debug){let time=getHoursAndMinutes2(new Date);console.log(time," | ",clientId," | Number of live sockets: ",Object.keys(this.servers[address].clients).length)}if(this.servers[address].onconnection)this.servers[address].onconnection(ws,request2,this.servers[address],clientId)});wss.on("error",err=>{if(this.debug)console.log("Socket Error:",err);if(this.servers[address].onerror)this.servers[address].onerror(err,wss,this.servers[address]);else console.error(err)});let onUpgrade=(request2,socket,head)=>{if(request2.headers&&request2.url){if(this.debug)console.log("Upgrade request at: ",request2.url);let pass=false;if(path3&&request2.url===path3)pass=true;else{let addr=request2.headers.host.split(":")[0];if(port)addr+=":"+port;if(addr===address)pass=true;else{addr+=request2.url.split("?")[0];if(addr===address)pass=true}}if(pass&&this.servers[address]){this.servers[address].wss.handleUpgrade(request2,socket,head,ws=>{if(this.servers[address].onupgrade)this.servers[address].onupgrade(ws,this.servers[address],request2,socket,head);this.servers[address].wss.emit("connection",ws,request2)})}}};if(server)server.addListener("upgrade",onUpgrade);wss.addListener("close",()=>{if(server)server.removeListener("upgrade",onUpgrade);if(this.servers[address].onclose)this.servers[address].onclose(wss,this.servers[address]);else console.log(`wss closed: ${address}`);delete this.servers[address]});let send=(message,socketId)=>{if(typeof message==="object")message=JSON.stringify(message);if(!socketId){for(const key in this.servers[address].clients){this.sockets[key].send(message)}}else return this.sockets[socketId].send(message)};let request=(message,method,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].request(message,method))}return promises}else return this.sockets[socketId].request(message,method)};let post=(route,args,method,socketId)=>{if(!socketId){for(const key in this.servers[address].clients){this.sockets[key].post(route,args,method)}}else return this.sockets[socketId].post(route,args,method)};let run=(route,args,method,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].run(route,args,method))}return promises}else return this.sockets[socketId].run(route,args,method)};let subscribe=(route,callback,socketId,args,key,subInput)=>{if(!socketId){let promises=[];for(const k in this.servers[address].clients){promises.push(this.sockets[k].subscribe(route,callback,args,key,subInput))}return promises}else this.sockets[socketId].subscribe(route,callback,args,key,subInput)};let unsubscribe=(route,sub,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].unsubscribe(route,sub))}return promises}else this.sockets[socketId].unsubscribe(route,sub)};let terminate=socketId=>{if(socketId)return this.terminate(socketId);else return this.terminate(address)};this.servers[address].send=send;this.servers[address].request=request;this.servers[address].post=post;this.servers[address].run=run;this.servers[address].subscribe=subscribe;this.servers[address].unsubscribe=unsubscribe;this.servers[address].terminate=terminate;this.servers[address].graph=this;this.servers[address]._id=options._id?options._id:address;return this.servers[address]};openWS=options=>{if(!options.address){let protocol=options.protocol;if(!protocol)protocol="wss";options.address=`${protocol}://${options.host}`;if(options.port)options.address+=":"+options.port;if(!options.path||options.path?.startsWith("/"))options.address+="/";if(options.path)options.address+=options.path}const address=options.address;let socket;if(options.socket)socket=options.socket;else socket=new wrapper_default(address);if(!("keepState"in options))options.keepState=true;if(options.onmessage){socket.on("message",data=>{this.sockets[address].onmessage(data,socket,this.sockets[address])})}else if(options._id){socket.addListener("message",data=>{if(ArrayBuffer.isView(data))data=data.toString();if(options.debug){console.log("Message from ",options._id,": ",data)}this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}})}else{let socketonmessage=data=>{if(ArrayBuffer.isView(data))data=data.toString();if(data){if(options.debug){console.log("Message from ",address,": ",data)}if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;socket.removeEventListener("message",socketonmessage);socket.on("message",data2=>{if(ArrayBuffer.isView(data2))data2=data2.toString();if(options.debug){console.log("Message from ",this.sockets[address]._id,": ",data2)}this.receive(data2,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data2})}})}}}}this.receive(data,socket,this.sockets[address]);if(options.keepState)this.setState({[address]:data})};socket.addListener("message",socketonmessage);options.onmessage=socketonmessage}socket.addListener("open",()=>{if(this.sockets[address].onopen)this.sockets[address].onopen(socket,this.sockets[address])});socket.addListener("close",(code,reason)=>{let obj=this.sockets[address];let onclose=obj.onclose;delete this.sockets[address];if(onclose)onclose(code,reason,socket,obj)});socket.on("error",er=>{if(this.sockets[address].onerror)this.sockets[address].onerror(er,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},this.sockets[address]._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return this.request(message,socket,this.sockets[address]._id,method)};let subscribe=(route,callback)=>{return this.subscribeToSocket(route,this.sockets[address]._id,callback)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{this.terminate(this.sockets[address]._id)};this.sockets[address]={type:"socket",socket,send,post,request,run,subscribe,unsubscribe,terminate,graph:this,__node:{tag:address},...options};return this.sockets[address]};transmit=(message,ws)=>{if(typeof message==="object"&&(message?.route||message?.node||typeof message.arrayBuffer!=="function"&&typeof message.byteLength!=="number"&&typeof message[0]?.byteLength!=="number")||typeof message==="number")message=JSON.stringify(message);if(!ws){let served=this.servers[Object.keys(this.servers)[0]];if(served)ws=served.wss;else{let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket};}if(ws instanceof import_websocket_server.default){ws.clients.forEach(c=>{c.send(message)})}else if(ws instanceof wrapper_default)ws.send(message)};closeWS=ws=>{if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}else if(typeof ws==="string"){for(const k in this.sockets){if(k.includes(ws)){ws=this.sockets[k].socket;delete this.sockets[k];break}}}if(ws instanceof wrapper_default){if(ws.readyState===ws.OPEN)ws.close()}return true};terminate=ws=>{let str;if(!ws){let served=Object.keys(this.servers);for(const key in served){this.terminate(key)}let sockets=Object.keys(this.sockets);for(const key in sockets){this.terminate(key)}}else if(typeof ws==="string"){str=ws;for(const k in this.servers){if(k.includes(ws)||this.servers[k]._id===ws){ws=this.servers[k].wss;for(const key in this.servers[k].clients){this.closeWS(this.servers[k].clients[key])}delete this.servers[k];break}}if(!ws){for(const k in this.sockets){if(k.includes(ws)||this.sockets[k]._id===ws){ws=this.sockets[k].socket;delete this.sockets[k];break}}}}if(ws instanceof import_websocket_server.default){ws.close(er=>{if(er)console.error(er)})}else if(ws instanceof wrapper_default){if(ws.readyState===ws.OPEN)ws.close();if(this.get(str?str:ws.url))this.remove(str?str:ws.url)}return true};request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(ws){if(typeof ws==="string"){for(const key in this.servers){for(const c in this.servers[key].clients){if(c===ws){ws=this.servers[key].clients[c];break}}}if(!(ws instanceof wrapper_default)){for(const s in this.sockets){if(s===ws){ws=this.sockets[s].socket;break}}}}if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof wrapper_default)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof wrapper_default)ws.send(JSON.stringify(res))}}return res};subscribeSocket=(route,socket,args,key,subInput)=>{if(this.restrict?.[route])return void 0;if(typeof socket==="string"){if(this.sockets[socket])socket=this.sockets[socket].socket;else{for(const prop in this.servers){if(this.servers[prop].clients[socket])socket=this.servers[prop].clients[socket]}}}if(typeof socket==="object"){return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},args,key,subInput)}};subscribeToSocket=(route,socketId,callback,args,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeEvent(socketId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[socketId]:res.args});else if(typeof callback==="string"){this.setState({[callback]:res.args})}else callback(res.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,args,key,subInput]})}}};function getHoursAndMinutes2(date){let hours=date.getHours();let minutes=date.getMinutes();hours=hours<10?"0"+hours:hours;minutes=minutes<10?"0"+minutes:minutes;return`${hours}:${minutes}`}var import_child_process=require("child_process");var import_path=__toESM(require("path"));var CMDService=class extends Service{processes;connections={processes:void 0};subprocessloader={"process":(node,parent,graph,roots,properties)=>{if(node.command){this.createProcess(node)}}};constructor(options){super(options);this.load(this);this.connections.processes=this.processes;if(process?.stdin){process.stdin.on("data",data=>{let str=data.toString();this.receive(str)})}}createProcess=properties=>{let newprocess=properties;if(!newprocess.command)newprocess.command="node";if(!newprocess.args)newprocess.args=[import_path.default.join(process.cwd(),"node_modules","graphscript-node","services","cmd","childprocess.js")];if(newprocess.command){let p;if(!newprocess.options){newprocess.options={shell:true,stdio:"inherit"}}newprocess.controller=new AbortController;newprocess.options=Object.assign({signal:newprocess.controller.signal,env:process.env,cwd:process.cwd()},newprocess.options);if(newprocess.tag)newprocess._id=newprocess.tag;else{newprocess._id=`process${Math.floor(Math.random()*1e15)}`;newprocess.tag=newprocess._id}if(typeof newprocess.command==="string"){if(newprocess.command.includes(".js")){p=(0,import_child_process.fork)(newprocess.command,newprocess.args,newprocess.options)}else p=(0,import_child_process.spawn)(newprocess.command,newprocess.args?newprocess.args:[],newprocess.options);if(p instanceof import_child_process.ChildProcess){if(p.stderr){if(newprocess.onerror){p.stderr.on("data",newprocess.onerror)}else p.stderr.on("data",console.error)}if(p.stdout){if(newprocess.stdout){p.stdout.on("data",newprocess.stdout)}else p.stdout.on("data",data=>{let str=data.toString();this.receive(str);this.setState({[newprocess._id]:str})})}if(newprocess.onclose){p.on("close",newprocess.onclose)}newprocess.process=p;newprocess.controller=new AbortController;newprocess.send=data=>{return p.send(data)};newprocess.request=(message,method)=>{return this.request(message,newprocess._id,method)};newprocess.post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return p.send(JSON.stringify(message))};newprocess.run=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.request(message,newprocess._id)};newprocess.subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToProcess(route,newprocess._id,callback,args,key,subInput)};newprocess.unsubscribe=(route,sub)=>{return newprocess.run("unsubscribe",[route,sub])};this.processes[newprocess._id]=newprocess}}}return newprocess};open=this.createProcess;abort=childprocess=>{if(childprocess.controller)childprocess.controller.abort();else childprocess.kill();return true};send=(childprocess,data)=>{return childprocess.send(data)};request=(message,processId,method)=>{let childprocess=this.processes[processId].process;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let ondata=data=>{let str=data.toString();if(str.includes("{")){let parsed=JSON.parse(str);if(parsed.callbackId===callbackId){childprocess.removeListener("data",ondata);res(parsed.args)}}};childprocess.addListener("data",ondata);childprocess.send(req)})};runRequest=(message,callbackId,childprocess)=>{let res=this.receive(message);if(typeof childprocess==="string")childprocess=this.processes[childprocess].process;if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(childprocess instanceof import_child_process.ChildProcess)childprocess.send(JSON.stringify(res));else process.stdout.write(JSON.stringify(res))})}else{res={args:res,callbackId};if(childprocess instanceof import_child_process.ChildProcess)childprocess.send(JSON.stringify(res));else process.stdout.write(JSON.stringify(res))}return res};subscribeProcess(route,childprocess,args,key,subInput){if(this.restrict?.[route])return void 0;if(typeof childprocess==="string"&&this.processes[childprocess]){childprocess=this.processes[childprocess].process}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{childprocess.send(JSON.stringify({args:r,callbackId:route}))})}else{childprocess.send(JSON.stringify({args:res,callbackId:route}))}},args,key,subInput)}subscribeToProcess(route,processId,callback,args,key,subInput){if(typeof processId==="string"&&this.processes[processId]){this.__node.state.subscribeEvent(processId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[processId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.processes[processId].request(JSON.stringify({route:"subscribeSocket",args:[route,processId,args,key,subInput]}))}}};var SessionsService=class extends Service{name="sessions";users={};sessions={oneWay:{},shared:{}};invites={};constructor(options,users){super(options);this.setLoaders(loaders);this.load(this);if(users)this.users=users}getSessionInfo=(sessionIdOrName,userId)=>{if(!sessionIdOrName){return this.sessions.shared}else{if(this.sessions.oneWay[sessionIdOrName]){let s=this.sessions.oneWay[sessionIdOrName];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{oneWay:{[sessionIdOrName]:s}}}}else if(this.sessions.shared[sessionIdOrName]){return{shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};openOneWaySession=(options={},sourceUserId,listenerUserId)=>{if(!options._id){options._id=`oneWay${Math.floor(Math.random()*1e15)}`;if(this.sessions.oneWay[options._id]){delete options._id;this.openOneWaySession(options,sourceUserId)}}if(options._id&&sourceUserId&&this.users[sourceUserId]){if(sourceUserId){if(!options.settings)options.settings={listener:sourceUserId,source:sourceUserId,propnames:{latency:true},admins:{[sourceUserId]:true},ownerId:sourceUserId};if(!options.settings.listener)options.settings.listener=listenerUserId?listenerUserId:sourceUserId;if(!options.settings.source)options.settings.source=sourceUserId;if(!this.users[sourceUserId].sessions)this.users[sourceUserId].sessions={};this.users[sourceUserId].sessions[options._id]=options}if(!options.data)options.data={};if(options.onopen)options.onopen(options);if(this.sessions.oneWay[options._id]){return this.updateSession(options,sourceUserId)}else if(options.settings?.listener&&options.settings.source)this.sessions.oneWay[options._id]=options}return options};openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;return this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={oneWay:{},shared:{}};if(!options.settings.name)options.name=options.id;if(options.onopen)options.onopen(options);if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};open=(options,userId)=>{if(options.listener)this.openOneWaySession(options,userId);else this.openSharedSession(options,userId)};updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.oneWay[options._id];if(!session)session=this.sessions.shared[options._id];if(session&&userId){if(session.settings&&(session?.settings.source===userId||session.settings.admins?.[userId]||session.settings.moderators?.[userId]||session.settings.ownerId===userId)){return this.recursivelyAssign(session,options)}}else if(options.settings?.source){return this.openOneWaySession(options,userId)}else return this.openSharedSession(options,userId)}return false};joinSession=(sessionId,userId,options,remoteUser=true)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(!sesh)sesh=this.sessions.oneWay[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;sesh.settings.newUser=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options?.source||options?.listener){sesh=this.openOneWaySession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options){sesh=this.openSharedSession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}return false};inviteToSession=(session,userInvited,inviteEndpoint,remoteUser=true)=>{if(remoteUser&&this.users[userInvited]?.send){this.users[userInvited]?.send({route:"receiveSessionInvite",args:[session,userInvited,inviteEndpoint]})}else{this.receiveSessionInvite(session,userInvited,inviteEndpoint)}};receiveSessionInvite=(session,userInvited,endpoint)=>{if(!this.invites[userInvited])this.invites[userInvited]={};let id=typeof session==="string"?session:session._id;this.invites[userInvited][id]={session,endpoint};return id};acceptInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;let invite=this.invites[userInvited]?.[id];let endpoint;if(invite){session=invite.session;endpoint=invite.endpoint;delete this.invites[userInvited]?.[id]}return new Promise((res,rej)=>{if(!id)res(false);if(remoteUser&&endpoint&&this.users[endpoint]?.send){let resolved;let timeout=setTimeout(()=>{if(!resolved){this.unsubscribe("joinSession",subbed);rej(new Error("Session join timed out"))}},1e4);let subbed=this.subscribe("joinSession",result=>{if(typeof result==="object"&&result?._id===id){if(result.setting?.users?.includes(userInvited)){this.unsubscribe("joinSession",subbed);resolved=true;if(timeout)clearTimeout(timeout);res(result)}}});this.users[endpoint]?.send({route:"joinSession",args:[id,userInvited,void 0,true]})}else res(this.joinSession(id,userInvited,typeof session==="object"?session:void 0))})};rejectInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;if(this.invites[userInvited]?.[id]){let endpoint=this.invites[userInvited][id].endpoint;delete this.invites[userInvited][id];if(remoteUser&&endpoint&&this.users[endpoint]?.send){this.users[endpoint].send({route:"rejectInvite",args:[id,userInvited]})}return true}};leaveSession=(session,userId,clear=true,remoteUser=true)=>{let sessionId;if(typeof session==="string"){sessionId=session;session=this.sessions.oneWay[sessionId];if(!session)session=this.sessions.shared[sessionId]}else sessionId=session._id;if(session){if(this.sessions.oneWay[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.oneWay[sessionId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){this.swapHost(session,void 0,true);delete session.data.shared[userId]}}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}return true}return false};deleteSession=(session,userId,remoteUsers=true)=>{if(typeof session==="string"){let id=session;session=this.sessions.oneWay[id];if(!session)session=this.sessions.shared[id]}if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user]?.sessions)delete this.users[user].sessions[session._id];if(this.users[user]?.sessionSubs)delete this.users[user].sessionSubs[session._id];if(remoteUsers){if(session.users){for(const key in session.users){if(this.users[key]?.send)this.users[key].send({route:"unsubscribeFromSession",args:[session._id,key]})}}else if(session.listener){if(this.users[session.listener]?.send)this.users[session.listener].send({route:"unsubscribeFromSession",args:[session._id,session.listener]})}else if(this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId]})}}else{this.unsubsribeFromSession(session,user)}}if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.oneWay[session._id];if(session.onclose)session.onclose(session)}}return true};getFirstMatch(obj1,obj2){for(const i in obj1){if(i in obj2)return i}return false}swapHost=(session,newHostId,adoptData=true,remoteUser=true)=>{if(typeof session==="string"){if(this.sessions.oneWay[session])session=this.sessions.oneWay[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){let oldHost=session.settings.host;delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];if(adoptData&&oldHost&&session.settings.inheritHostData!==false){if(session.data?.shared[oldHost]){if(session.data?.shared[oldHost]){session.data.shared[session.settings.host]=Object.assign(session.data.shared[session.settings.host]?session.data.shared[session.settings.host]:{},session.data.shared[oldHost]);if(remoteUser){}}}}return true}return false};subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}let user=this.users[userId];if(!user)return void 0;if(!user.sessionSubs)user.sessionSubs={};if(!user.sessionSubs[session._id])user.sessionSubs[session._id]={};if(onmessage)user.sessionSubs[session._id].onmessage=onmessage;if(onopen)this.sessionSubs[userId][session._id].onopen=onopen;if(onclose)user.sessionSubs[session._id].onclose=onclose;if(typeof onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)this.sessionSubs[userId][session._id].onopen(session,user);this.unsubscribe("joinSession",sub)});user.sessionSubs[session._id].onopenSub=sub}return session};unsubsribeFromSession=(session,userId,clear=true)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}const clearSessionSubs=(Id,s)=>{let u2=this.users[Id];if(!u2)return void 0;if(u2.sessionSubs?.[s._id]){if(u2.sessionSubs[s._id].onopenSub){this.unsubscribe("joinSession",u2.sessionSubs[s._id].onopenSub)}}if(u2.sessionSubs[s._id].onclose)u2.sessionSubs[s._id].onclose(s,u2);delete u2.sessionSubs[s._id]};if(userId){clearSessionSubs(userId,session)}else{for(const key in this.users){clearSessionSubs(key,session)}}if(clear){if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.shared[session._id]}};sessionUpdateCheck=(sessionHasUpdate,transmit=true)=>{let updates={oneWay:{},shared:{}};for(const session in this.sessions.oneWay){const sesh=this.sessions.oneWay[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.oneWay[session];continue}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(prop in this.users[sesh.source]){if(this.sessions.oneWay[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(prop in this.users[sesh.source]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.oneWay[session]?.data&&prop in this.sessions.oneWay[session]?.data)delete this.sessions.oneWay[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.oneWay[session].data,updateObj.data);updates.oneWay[sesh._id]=updateObj;if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.onhasupdate(sesh,updateObj)}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const oneWayData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}else if(sesh.settings.newUser){updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;sesh.settings.newUser=false}if(user!==sesh.settings.host){oneWayData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data?.oneWay&&!(user in sesh.data.oneWay)){if(typeof this.users[user][prop]==="object")oneWayData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else oneWayData[user][prop]=this.users[user][prop]}else if(typeof oneWayData[user][prop]==="object"&&sesh.data){if(prop in this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))oneWayData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.oneWay?.[prop]!==this.users[user][prop])oneWayData[user][prop]=this.users[user][prop]}else if(sesh.data?.oneWay?.[user]&&prop in sesh.data?.oneWay?.[user])delete sesh.data.oneWay[user][prop]}if(Object.keys(oneWayData[user]).length===0)delete oneWayData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user]))sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}}}if(Object.keys(oneWayData).length>0){updateObj.data.oneWay=oneWayData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user]?.[prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user]?.[prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.oneWay){updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){Object.assign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.oneWay){Object.assign(this.sessions.shared[session].data?.oneWay,updateObj.data.oneWay)}if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.settings.onhasupdate(sesh,updateObj)}}if(Object.keys(updates.oneWay).length===0)delete updates.oneWay;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};transmitSessionUpdates=updates=>{let users={};if(updates.oneWay){for(const s in updates.oneWay){let session=this.sessions.oneWay[s];if(session?.settings){let u2=session.settings.listener;if(!users[u2])users[u2]={};users[u2].oneWay[s]=updates.oneWay[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){for(const u2 in session.settings.users){if(!users[u2])users[u2]={};users[u2].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u2 in users){message.args=[u2,users[u2]];if(this.users[u2]?.send)this.users[u2].send(JSON.stringify(message));this.setState({[u2]:Object.create(message)})}return users};receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(user){if(!user.sessions)user.sessions={oneWay:{},shared:{}};if(!user.sessionSubs)user.sessionSubs={}}if(update.oneWay){for(const key in update.oneWay){this.recursivelyAssign(this.sessions.oneWay[key].data,update.oneWay[key].data);if(this.sessions.oneWay[key]?.settings.onmessage)this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key],update.oneWay[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}if(update.shared){for(const key in update.shared){if(update.shared[key].settings.users)this.sessions.shared[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)this.sessions.shared[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.oneWay)this.recursivelyAssign(this.sessions.shared[key].data.oneWay,update.shared[key].data.oneWay);if(update.shared[key].data.shared)this.recursivelyAssign(this.sessions.shared[key].data.shared,update.shared[key].data.shared);if(this.sessions.shared[key]?.settings.onmessage)this.sessions.shared[key].settings.onmessage(this.sessions.shared[key],update.shared[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}return user}};getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};userUpdateCheck=(user,onupdate)=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});if(onupdate){onupdate(user,updateObj)};return updateObj}}return void 0};setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};STREAMLATEST=0;STREAMALLLATEST=1;streamSettings={};streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};setStreamFunc=(name2,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name2].settings[key])this.streamSettings[name2].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name2].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name2].settings[key].callback=callback;if(!this.streamSettings[name2].settings[key].callback)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;return true};addStreamFunc=(name2,callback=data=>{})=>{this.streamFunctions[name2]=callback};setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};removeStream=(streamName,key)=>{if(streamName&&this.streamSettings[streamName]&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}}};var Router=class extends Service{name="router";connections={};sources={};services={};serviceConnections={};users={};userTimeout=1e4;order;constructor(options){super(options);this.load(this);if(options){if(options.order)this.order=options.order;if(options.timeout)this.userTimeout=options.timeout;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}addUser=async(info,connections,config,receiving)=>{let user;if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}if(this.users[info._id]){user=this.users[info._id]}else{user=Object.assign({},info)}if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>this.userTimeout){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}if(!this.users[info._id]){let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let sendAll=(message,...a)=>{let connections2=this.getConnections(user._id,"send");for(const key in connections2)if(connections2[key]?.send)return connections2[key].send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let requestAll=(message,method,...a)=>{let connections2=this.getConnections(user._id,"request");let results=[];for(const key in connections2)if(connections2[key]?.request)results.push(connections2[key].request(message,method,...a));return Promise.all(results)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let postAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"post");for(const key in connections2)if(connections2[key]?.post)connections2[key].post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let runAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"run");let results=[];for(const key in connections2)if(connections2[key]?.run)results.push(connections2[key].run(route,args,method,...a));return Promise.all(results)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let subscribeAll=(route,callback,...a)=>{let connections2=this.getConnections(user._id,"subscribe");let results=[];for(const key in connections2)if(connections2[key]?.post)results.push(connections2[key].subscribe(route,callback,...a));return Promise.all(results)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let unsubscribeAll=(route,subs,...a)=>{let connections2=this.getConnections(user._id,"unsubscribe");let results=[];for(const key in connections2)if(connections2[key]?.post&&subs[key])results.push(connections2[key].unsubscribe(route,subs[key],...a));return Promise.all(results)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;user.sendAll=sendAll;user.requestAll=requestAll;user.postAll=postAll;user.runAll=runAll;user.subscribeAll=subscribeAll;user.unsubscribeAll=unsubscribeAll;user.terminateAll=terminate;this.users[user._id]=user}if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i)=>{if(connections[k]?._id){connectionIds[`${i}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}getConnection=(sourceId,hasMethod,connectionId)=>{if(this.connections[sourceId]){return this.connections[sourceId]}else if(this.sources[sourceId]){if(hasMethod?.includes("All"))return this.users[sourceId];if(connectionId){if(hasMethod){if(this.sources[sourceId][connectionId]?.[hasMethod])return this.sources[sourceId][connectionId]}else if(this.sources[sourceId][connectionId])return this.sources[sourceId][connectionId];else return void 0}else if(this.order){for(let i=0;i{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}return found}};runConnection=async(userId,method,args,connectionId)=>{let sendTo;if(method.indexOf("All")>-1){sendTo=this.users[userId]}else{sendTo=this.getConnection(userId,method,connectionId)}if(sendTo){let res=sendTo[method](...args);res=await res;return res}};subscribeThroughConnection=(route,remoteRelay,remoteEndpoint,callback,...args)=>{if(typeof remoteRelay==="string"){remoteRelay=this.getConnection(remoteRelay,"run")}if(typeof remoteRelay==="object")return new Promise((res,rej)=>{remoteRelay.run("routeConnections",[route,remoteEndpoint,remoteRelay._id,...args]).then(sub=>{this.__node.state.subscribeEvent(remoteEndpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[remoteEndpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};addConnection=(options,source,autoRemove=true)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.connection=options.connection;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await connectionHasId(info,this.userTimeout)}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await connectionHasId(connection,this.userTimeout)}if(connection._id)return this.addConnection({connection,service},source)}}};terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}}};function connectionHasId(connection,timeout=1e4){return new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>timeout){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connection timed out:",er)})}0&&(module.exports={CMDService,Callable,E2EEService,ECSService,EventHandler,Graph,GraphNode,HTTPbackend,Router,SSEbackend,Service,SessionsService,WSSbackend,animate,backprop,bindListener,branching,connectionHasId,defaultManifest,defaultServiceWorker,getAllProperties,getCallbackFromString,htmlBodyBoilerPlate,instanceObject,isFunction,isNativeClass,isTypedArray,loaders,loop,methodstrings,nodeTemplates,recursivelyAssign,remoteGraphRoutes,scriptBoilerPlate,spliceTypedArray,state,substitute__operator,transformListenerResult,triggerListenerOncreate,wrapArgs}); diff --git a/dist/src/core/EventHandler.d.ts b/dist/src/core/EventHandler.d.ts deleted file mode 100644 index 2f00b243..00000000 --- a/dist/src/core/EventHandler.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -export declare class EventHandler { - data: { - [key: string]: any; - }; - triggers: { - [key: string]: { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - }; - ctr: number; - constructor(data?: { - [key: string]: any; - }); - setState: (updateObj: { - [key: string]: any; - }) => { - [key: string]: any; - }; - setValue: (key: any, value: any) => void; - triggerEvent: (key: any, value: any) => void; - subscribeState: (onchange: (res: any) => void) => number; - unsubscribeState: (sub: number) => boolean; - subscribeEvent: (key: string, onchange: (res: any) => void, refObject?: { - [key: string]: any; - }, refKey?: string) => number; - unsubscribeEvent: (key: string, sub?: number) => boolean; - subscribeEventOnce: (key: string, onchange: (res: any) => void) => any; - getEvent: (key: any, sub?: any) => { - [key: string]: any; - sub: number; - onchange: Function; - } | { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - getSnapshot: () => void; - onRemoved: (trigger: { - sub: number; - onchange: Function; - }) => void; -} diff --git a/dist/src/core/Graph.d.ts b/dist/src/core/Graph.d.ts deleted file mode 100644 index f77b09bd..00000000 --- a/dist/src/core/Graph.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { EventHandler } from "./EventHandler"; -export declare const state: EventHandler; -export type GraphNodeProperties = { - __props?: Function | { - [key: string]: any; - } | GraphNodeProperties | GraphNode; - __operator?: ((...args: any[]) => any) | string; - __children?: { - [key: string]: any; - }; - __listeners?: { - [key: string]: true | string | ((result: any) => void) | { - __callback: string | ((result: any) => void) | true; - subInput?: boolean; - [key: string]: any; - }; - } | { - [key: string]: ((result: any) => void) | true | string; - }; - __onconnected?: ((node: any) => void | ((node: any) => void)[]); - __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); - __node?: { - tag?: string; - state?: EventHandler; - [key: string]: any; - }; - __args?: any[]; - __callable?: boolean; - [key: string]: any; -}; -export type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; -export type Roots = { - [key: string]: any; -}; -export type GraphOptions = { - roots?: Roots; - loaders?: { - [key: string]: Loader | { - init?: Loader; - connected?: (node: any) => void; - disconnected?: (node: any) => void; - }; - }; - state?: EventHandler; - mapGraphs?: false; - [key: string]: any; -}; -export type argObject = { - __input?: string | ((...args: any[]) => any); - __callback: string | ((...args: any[]) => any); - __args?: any[]; - __output?: string | argObject | ((...args: any[]) => any); -}; -export type Listener = { - __callback?: string; - __args?: (argObject | Function | string)[]; - sub: number; - node: GraphNode; - graph: Graph; - source?: string; - key?: string; - target?: string; - tkey?: string; - arguments?: Function[]; - subInput?: boolean; - onchange: Function; -}; -export declare class Callable extends Function { - __bound: Callable; - __call: ((...args: any[]) => any); - [key: string]: any; - constructor(); -} -export declare class GraphNode { - __node: { - tag: string; - unique: string; - state: EventHandler; - [key: string]: any; - }; - __children?: { - [key: string]: GraphNode; - }; - __parent?: Graph | GraphNode; - __operator?: any; - __listeners?: any; - __props?: any; - __args: any[]; - [key: string]: any; - constructor(properties: GraphNodeProperties, parent?: { - [key: string]: any; - }, graph?: Graph); - get __graph(): any; - set __graph(graph: any); - __setProperties: (properties: any, parent: any, graph: any) => void; - __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, target?: string, tkey?: string, args?: any[], callbackStr?: string) => any; - __unsubscribe: (sub?: number, key?: string, unsubInput?: boolean) => boolean; - __setOperator: (fn: (...args: any[]) => any) => any; - __addLocalState: (props?: { - [key: string]: any; - }, key?: string) => void; - __proxyObject: (obj: any) => void; - __addOnconnected(callback: (node: any) => void): void; - __addOndisconnected(callback: (node: any) => void): void; - __callConnected(node?: this): void; - __callDisconnected(node?: this): void; -} -export declare class Graph { - [key: string]: any; - __node: { - tag: string; - unique: string; - state: EventHandler; - nodes: Map; - roots: { - [key: string]: any; - }; - mapGraphs?: boolean; - [key: string]: any; - }; - constructor(options?: GraphOptions); - init: (options?: GraphOptions) => void; - load: (roots: { - [key: string]: any; - }, overwrite?: boolean) => { - [key: string]: any; - }; - setLoaders: (loaders: { - [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, props: any, key: string) => void; - }, replace?: boolean) => any; - runLoaders: (node: any, parent: any, properties: any, key: any) => void; - add: (properties: any, parent?: GraphNode | string, overwrite?: boolean) => GraphNode; - recursiveSet: (originCpy: any, parent: any, listeners: any, origin: any, overwrite?: boolean) => any; - remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; - run: (node: string | GraphNode, ...args: any[]) => any; - /** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners: (listeners: { - [key: string]: { - [key: string]: any; - }; - }) => void; - clearListeners: (node: GraphNode | string, listener?: string) => void; - get: (tag: string) => any; - getByUnique: (unique: string) => any; - set: (tag: string, node: GraphNode) => Map; - delete: (tag: string) => boolean; - list: () => string[]; - getListener: (nodeTag: string, key?: string, sub?: number) => Listener; - getProps: (node: GraphNode | string, getInitial?: boolean) => void; - subscribe: (nodeEvent: GraphNode | string, onEvent: string | GraphNode | ((...res: any) => void), args?: any[], key?: string | undefined, subInput?: boolean, target?: string | GraphNode, tkey?: string) => number; - unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; - setState: (update: { - [key: string]: any; - }) => void; -} -export declare function getAllProperties(obj: any): any[]; -export declare function instanceObject(obj: any): any; -export declare function isNativeClass(thing: any): boolean; -export declare function isFunction(x: any): "function" | "class" | "async" | "arrow" | ""; -export declare let getCallbackFromString: (a: any, graph: any) => (...inp: any[]) => any; -export declare const wrapArgs: (callback: any, argOrder: any, graph: any) => { - __callback: any; - __args: any[]; -}; diff --git a/dist/src/loaders/html/DOMElement.d.ts b/dist/src/loaders/html/DOMElement.d.ts deleted file mode 100644 index f0ad10a8..00000000 --- a/dist/src/loaders/html/DOMElement.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -export function addCustomElement(cls: any, tag: any, extend?: any): void; -export function randomId(tag?: string): string; -export function parseFunctionFromText(method: any): any; -export class DOMElement extends HTMLElement { - static get tag(): string; - static addElement(tag?: string, cls?: typeof DOMElement, extend?: any): void; - useShadow: boolean; - FRAGMENT: any; - STYLE: any; - attachedShadow: boolean; - obsAttributes: string[]; - props: {}; - attributeChangedCallback: (name: any, old: any, val: any) => void; - onchanged: any; - ONRESIZE: ((ev: any) => void) | ((ev: any) => void); - ondelete: (() => void) | ((props?: {}) => void); - oncreate: any; - renderonchanged: number; - template: any; - connectedCallback(): void; - delete: () => void; - render: (props?: {}) => void; - templateResult: any; - state: { - pushToState: {}; - data: {}; - triggers: {}; - setState(updateObj: any): {}; - subscribeTrigger(key: any, onchanged?: (res: any) => void): number; - unsubscribeTrigger(key: any, sub: any): boolean; - subscribeTriggerOnce(key?: any, onchanged?: (value: any) => void): void; - }; -} diff --git a/dist/src/loaders/html/html.d.ts b/dist/src/loaders/html/html.d.ts deleted file mode 100644 index b7261cfd..00000000 --- a/dist/src/loaders/html/html.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -export declare function html(strings: TemplateStringsArray, ...args: any[]): (elm?: HTMLElement) => HTMLElement | DocumentFragment; -/** - * - * let htmlfunction = html`` //e.g. some html - * htmlfunction(document.body); //append the template string to the desired element, or just return the prepared template element - * - * Syntax highlighting with lit-html plugin: https://open-vsx.org/extension/meganrogge/template-string-converter - - // Example usage of the html function - document.addEventListener("DOMContentLoaded", () => { - const app = document.getElementById('app'); - - const title = document.createElement('h1'); - title.textContent = "Welcome to HTML Function Test"; - - const paragraph = document.createElement('p'); - paragraph.textContent = "This is a paragraph element created using native DOM API."; - - // Creating HTML structure using the html function - const content = html` -
-

This is a test

- ${title} -

This is a paragraph element created using the html function.

- ${paragraph} -
- `(); - - app.appendChild(content); - }); - -*/ -export declare function xml(strings: TemplateStringsArray, ...args: any[]): (elm?: Node, namespace?: string) => string; -/** Test: - * - * - const testXmlFunction = () => { - const namespace = "http://www.example.com/test"; - const resultContainer = document.createElement('div'); - - const testElement = document.createElementNS(namespace, 'testElement'); - testElement.textContent = "Test Content"; - - const xmlAppender = xml`Hello, ${'World'}! This is a ${testElement}.`; - const xmlString = xmlAppender(resultContainer, namespace); - - resultContainer.innerHTML += `
${xmlString}
`; - - console.log(xmlString); - document.body.appendChild(resultContainer); - }; - - testXmlFunction(); - * - * - */ diff --git a/dist/src/loaders/html/html.loader.d.ts b/dist/src/loaders/html/html.loader.d.ts deleted file mode 100644 index 3bb97ea3..00000000 --- a/dist/src/loaders/html/html.loader.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { GraphNode, GraphNodeProperties, Graph } from '../../core/Graph'; -export type HTMLNodeProperties = GraphNodeProperties & { - __props?: HTMLElement; - __onresize?: (elm: HTMLElement) => void; - __onremove?: (elm: HTMLElement) => void; - __onrender?: (elm: HTMLElement) => void; - tagName?: string; - parentNode?: string | HTMLElement; - style?: Partial; - __template?: string | ((...args: any[]) => string); - __renderonchanged?: (elm: HTMLElement) => void; - useShadow?: boolean; - __css?: string; - __element?: string | HTMLElement; - __attributes?: { - [key: string]: any; - }; -}; -export declare const htmlloader: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; diff --git a/dist/src/loaders/html/wc.loader.d.ts b/dist/src/loaders/html/wc.loader.d.ts deleted file mode 100644 index 26a594dc..00000000 --- a/dist/src/loaders/html/wc.loader.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { GraphNode, GraphNodeProperties, Graph } from '../../core/Graph'; -export { HTMLNodeProperties } from './html.loader'; -export declare const wchtmlloader: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; diff --git a/dist/src/loaders/index.d.ts b/dist/src/loaders/index.d.ts deleted file mode 100644 index 229b9ec7..00000000 --- a/dist/src/loaders/index.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; -/** - * setting nodeA.__node.backward:true propagates operator results to parent - */ -export declare const backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** - * - * Specify a timer loop, will stop when node is popped or nodeA.__node.isLooping is set false - * nodeA.__node.loop = 100 will loop the operator every 100 milliseconds - * - * Or - * nodeA.__node.delay will delay the operator by specified millisecond number and resolve the result as a promise - * nodeA.__node.frame will use requestAnimationFrame to call the function and resolve the result as a promise - * - * Use in combination with: - * nodeA.__node.repeat will repeat the operator the specified number of times - * nodeA.__node.recursive will do the same as repeat but will pass in the previous operator call's results - * - * - */ -export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Animations - * - * nodeA.__node.animate = true; - * then __operator becomes a requestAnimationFrame function - * start with a call the __operator or by setting node.__node.animating = true; - * - * or node.__animation = (...args) => {} - * - */ -export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Branching operations - * - * //runs a function or node if the if-conditions are satisfied, which can be a function that returns a true or false - * nodeA.__branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} - * - * nodeA.__listeners['nodeB.x'] = { - * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } - * } - * - */ -export declare const branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Trigger listeners oncreate with specific arguments - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, oncreate:any } - * - */ -export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Bind listeners to a specific object instead of the node that owns it - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } - * - */ -export declare const bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, transform:(result)=>any } - * - */ -export declare const transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -export declare const substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; -export declare const loaders: { - backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; -}; diff --git a/dist/src/loaders/methodstrings.d.ts b/dist/src/loaders/methodstrings.d.ts deleted file mode 100644 index 978aabc8..00000000 --- a/dist/src/loaders/methodstrings.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function methodstrings(node: any): void; diff --git a/dist/src/services/Service.d.ts b/dist/src/services/Service.d.ts deleted file mode 100644 index a5558998..00000000 --- a/dist/src/services/Service.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Graph, GraphNode, GraphOptions } from "../../src/core/Graph"; -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export type ServiceMessage = { - route?: string; - args?: any; - method?: string; - node?: string | GraphNode; - [key: string]: any; -}; -export type ServiceOptions = GraphOptions & { - services?: { - [key: string]: Service | Function | { - [key: string]: any; - }; - }; - restrict?: { - [key: string]: boolean; - }; -}; -export declare class Service extends Graph { - name: string; - restrict?: { - [key: string]: boolean; - }; - constructor(options?: ServiceOptions); - addServices: (services: { - [key: string]: Function | Graph | Service | { - [key: string]: any; - }; - }) => void; - handleMethod: (route: string, method: string, args?: any) => any; - handleServiceMessage(message: ServiceMessage): any; - handleGraphNodeCall(route: string | GraphNode, args: any): any; - transmit: (...args: any[]) => any | void; - receive: (...args: any[]) => any | void; - pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => number; - pipeOnce: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; - terminate: (...args: any) => void; - isTypedArray: typeof isTypedArray; - recursivelyAssign: (target: any, obj: any) => any; - spliceTypedArray: typeof spliceTypedArray; - ping: () => string; - echo: (...args: any) => any; - log: (...args: any) => boolean; - error: (...args: any) => boolean; -} -export declare function isTypedArray(x: any): boolean; -export declare const recursivelyAssign: (target: any, obj: any) => any; -export declare function spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; diff --git a/dist/src/services/cmd/CMD.node.d.ts b/dist/src/services/cmd/CMD.node.d.ts deleted file mode 100644 index 6cf50902..00000000 --- a/dist/src/services/cmd/CMD.node.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -/// -/// -import { ChildProcess, Serializable } from 'child_process'; -import { Service, ServiceMessage, ServiceOptions } from '../Service'; -import { Graph, GraphNode, GraphNodeProperties } from '../../core/Graph'; -export type CMDRoute = { - command: string | ChildProcess; - args?: string[]; - options?: { - shell: true; - stdio: 'inherit'; - [key: string]: any; - }; - env?: any; - cwd?: any; - signal?: any; - stdout?: (data: any) => void; - onerror?: (error: Error) => void; - onclose?: (code: number | null, signal: NodeJS.Signals | null) => void; -} & GraphNodeProperties; -export type CMDInfo = { - process: ChildProcess; - _id: string; - controller: AbortController; - send: (data: Serializable) => boolean; - request: (message: ServiceMessage | any, method?: string) => Promise; - post: (route: string, args: any, method?: string) => boolean; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => number; - unsubscribe: (route: any, sub: number) => Promise; -} & CMDRoute; -export declare class CMDService extends Service { - processes: { - [key: string]: { - _id: string; - process: ChildProcess; - controller: AbortController; - } & CMDRoute; - }; - connections: { - processes: any; - }; - subprocessloader: { - process: (node: CMDRoute & GraphNode, parent: GraphNode, graph: Graph, roots: any, properties: any) => void; - }; - constructor(options?: ServiceOptions); - createProcess: (properties: CMDRoute) => CMDRoute; - open: (properties: CMDRoute) => CMDRoute; - abort: (childprocess: ChildProcess | CMDInfo) => boolean; - send: (childprocess: ChildProcess, data: Serializable) => boolean; - request: (message: ServiceMessage | any, processId: string, method?: string) => Promise; - runRequest: (message: any, callbackId: string | number, childprocess?: ChildProcess | string) => any; - subscribeProcess(route: string, childprocess: ChildProcess | string, args?: any[], key?: string, subInput?: boolean): number; - subscribeToProcess(route: string, processId: string, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean): any; -} diff --git a/dist/src/services/e2ee/E2EE.service.d.ts b/dist/src/services/e2ee/E2EE.service.d.ts deleted file mode 100644 index 559759b0..00000000 --- a/dist/src/services/e2ee/E2EE.service.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export declare class E2EEService extends Service { - name: string; - keys: { - [key: string]: { - key: string; - _id: string; - }; - }; - securedKeys: boolean; - encryptedkeys?: string; - secret?: string; - constructor(options?: ServiceOptions, keys?: { - [key: string]: { - key: string; - _id?: string; - }; - }, secureKeys?: boolean, secret?: string); - addKey: (key: string, _id?: string) => string | { - key: string; - _id: string; - }; - static generateSecret(): string; - encrypt(message: string, key: string): string; - decrypt(message: string, key: string): string; - encryptRoute: (message: ServiceMessage | string, keyId: string) => ServiceMessage; - decryptRoute: (message: ServiceMessage | string, keyId: string) => string | ServiceMessage; - transmit: (message: ServiceMessage | string, keyId?: string) => any; - receive: (message: ServiceMessage | string, keyId?: string) => any; -} diff --git a/dist/src/services/ecs/ECS.service.d.ts b/dist/src/services/ecs/ECS.service.d.ts deleted file mode 100644 index cb3252b8..00000000 --- a/dist/src/services/ecs/ECS.service.d.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { GraphNode, GraphNodeProperties } from '../../core/Graph'; -import { Service, ServiceOptions } from '../Service'; -export type EntityProps = { - components: { - [key: string]: any; - }; -} & (GraphNodeProperties | GraphNode); -export type SystemProps = (GraphNodeProperties & { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; -}) | GraphNode; -export type Entity = { - components: { - [key: string]: any; - }; - [key: string]: any; -} & GraphNode; -export type System = { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - remove?: (entity: Entity, entitities: { - [key: string]: Entity; - }) => Entity; - entities: { - [key: string]: Entity; - }; - entityKeys: string[]; -} & GraphNode; -export type ECSOptions = { - entities: { - [key: string]: EntityProps; - }; - systems: { - [key: string]: SystemProps; - }; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class ECSService extends Service { - entities: { - [key: string]: Entity; - }; - systems: { - [key: string]: System; - }; - entityMap: Map; - entityKeyMap: Map; - order: string[]; - animating: boolean; - entityCt: number; - systemCt: number; - constructor(options?: ECSOptions); - updateEntities: (order?: string[], filter?: boolean, debug?: any) => void; - animateEntities: (filter?: boolean, order?: string[]) => void; - stop: () => void; - start: (filter?: boolean) => void; - addEntities: (prototype: EntityProps, components?: { - [key: string]: any; - }, count?: number) => string[]; - addEntity: (prototype?: EntityProps, components?: { - [key: string]: any; - }) => Entity; - addSystems: (systems?: { - [key: string]: SystemProps; - }, order?: string[]) => { - [key: string]: System; - }; - addSystem: (prototype: SystemProps, setupEntities?: (entities: { - [key: string]: Entity; - }) => any, setupEntity?: (entity: Entity) => any, operator?: (entities: any) => any, remove?: (entities: any) => any, order?: string[]) => System; - setupEntity: (entity: Entity) => void; - removeEntity: (tag: string) => string | GraphNode; - removeEntities(entities: string[] | { - [key: string]: Entity; - }): void; - removeSystem: (tag: string) => string | GraphNode; - filterObject(o: { - [key: string]: any; - }, filter: (string: any, any: any) => boolean | undefined): { - [k: string]: any; - }; - setEntities: (entities: string[] | { - [key: string]: Entity; - }, props: { - [key: string]: any; - }) => boolean; - setEntity: (entity: Entity, props: { - [key: string]: any; - }) => any; - bufferValues: (entities: { - [key: string]: Entity; - }, property: string, keys?: string[] | { - [key: string]: any; - }, buffer?: ArrayBufferLike) => ArrayBufferLike; -} diff --git a/dist/src/services/http/HTTP.browser.d.ts b/dist/src/services/http/HTTP.browser.d.ts deleted file mode 100644 index 556840b4..00000000 --- a/dist/src/services/http/HTTP.browser.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type RequestOptions = { - method: string; - url: string | URL; - data?: Document | string | Blob | BufferSource | FormData | URLSearchParams; - responseType?: XMLHttpRequestResponseType; - mimeType?: string | undefined; - onload?: (ev: any) => void; - onprogress?: (ev: any) => void; - onabort?: (ev: any) => void; - onerror?: (er: any) => void; - onloadend?: (ev: any) => void; - user?: string; - pass?: string; -}; -export declare class HTTPfrontend extends Service { - name: string; - fetchProxied: boolean; - listening: {}; - constructor(options?: ServiceOptions, path?: string, fetched?: (clone: Response, args: any[], response: Response) => Promise); - static request: (options: RequestOptions) => XMLHttpRequest; - GET: (url?: string | URL, type?: XMLHttpRequestResponseType, mimeType?: string | undefined) => Promise; - POST: (message: any | ServiceMessage, url?: string | URL, type?: XMLHttpRequestResponseType, mimeType?: string | undefined) => Promise; - transmit: (message: any | ServiceMessage, url: string | URL) => Promise; - transponder: (url: string | URL, message: any | ServiceMessage | undefined, type?: XMLHttpRequestResponseType, mimeType?: string) => Promise; - listen: (path?: string | undefined | '0', fetched?: (clone: Response, args: any[], response: Response) => Promise) => string; - stopListening: (path: string | 0 | undefined, listener?: string) => void; -} diff --git a/dist/src/services/http/HTTP.node.d.ts b/dist/src/services/http/HTTP.node.d.ts deleted file mode 100644 index 5e0dc480..00000000 --- a/dist/src/services/http/HTTP.node.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -/// -/// -/// -/// -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import * as http from 'http'; -import * as https from 'https'; -import * as path from 'path'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export * from './boilerplate/index'; -export type ServerProps = { - host: string; - port: number; - certpath?: string; - keypath?: string; - passphrase?: string; - startpage?: string; - errpage?: string; - pages?: { - [key: 'all' | string]: string | ({ - headers?: { - [key: string]: any; - }; - template?: string; - onrequest?: GraphNode | string | ((self: HTTPbackend, node: GraphNode, request: http.IncomingMessage, response: http.ServerResponse) => void); - redirect?: string; - inject?: { - [key: string]: any; - } | any[] | string | ((...args: any) => any); - } & GraphNodeProperties); - }; - protocol?: 'http' | 'https'; - type?: 'httpserver' | string; - keepState?: boolean; - onopen?: (served: ServerInfo) => void; - onerror?: (er: Error, served: ServerInfo) => void; - onclose?: (served: ServerInfo) => void; - onupgrade?: (request: any, socket: any, head: any, served: ServerInfo) => void; - timeout?: number; - _id?: string; - debug?: boolean; - [key: string]: any; -}; -export type ServerInfo = { - server: https.Server | http.Server; - address: string; - terminate: () => void; - graph: HTTPbackend; - _id: string; -} & ServerProps; -export type ReqOptions = { - protocol: 'http' | 'https' | string; - host: string; - port: number; - method: string; - path?: string; - headers?: { - [key: string]: any; - 'Content-Type'?: string; - 'Content-Length'?: number; - }; -}; -export declare class HTTPbackend extends Service { - name: string; - server: any; - debug: boolean; - servers: { - [key: string]: ServerInfo; - }; - mimeTypes: { - [key: string]: string; - }; - constructor(options?: ServiceOptions, settings?: ServerProps); - onStarted: (protocol: 'http' | 'https' | string, host: string, port: number) => void; - setupServer: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => void; - open: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => void; - setupHTTPserver: (options?: (ServerProps & { - certpath?: string; - keypath?: string; - passphrase?: string; - }), requestListener?: http.RequestListener, onStarted?: () => void) => Promise; - transmit: (message: any | ServiceMessage, options: string | { - protocol: 'http' | 'https' | string; - host: string; - port: number; - method: string; - path?: string; - headers?: { - [key: string]: any; - 'Content-Type'?: string; - 'Content-Length'?: number; - }; - }, ondata?: (chunk: any) => void, onend?: () => void) => Promise | http.ClientRequest; - withResult: (response: http.ServerResponse, result: any, message: { - route: string; - args: { - request: http.IncomingMessage; - response: http.ServerResponse; - }; - method?: string; - served?: ServerInfo; - }) => void; - injectPageCode: (templateString: string, url: string, served: ServerInfo) => { - templateString: string; - headers: { - [key: string]: any; - }; - }; - receive: (message: { - route: string; - args: { - request: http.IncomingMessage; - response: http.ServerResponse; - }; - method?: string; - node?: string; - served?: ServerInfo; - redirect?: string; - }) => Promise; - responseOnErrorPromiseHandler: (response: http.ServerResponse, reject: any, err: any) => void; - getFailedPromiseHandler: (resolve: any, reject: any, requestURL: any, message: any, response: http.ServerResponse, served: any) => void; - handleBufferedPostBodyPromiseHandler: (resolve: any, body: any, message: any, response: http.ServerResponse, served: any) => void; - onRequestFileReadPromiseHandler: (error: any, content: any, resolve: any, reject: any, requestURL: any, response: http.ServerResponse, message: any, served: ServerInfo) => void; - responsePromiseHandler: (resolve: any, reject: any, message: any, request: http.IncomingMessage, response: http.ServerResponse, method: string, served: ServerInfo) => void; - request: (options: ReqOptions | any, send?: any, ondata?: (chunk: any) => void, onend?: () => void) => http.ClientRequest; - POST: (url: string | URL, data: any, headers?: { - [key: string]: any; - 'Content-Type'?: string; - 'Content-Length'?: number; - }) => http.ClientRequest; - GET: (url: string | URL | http.RequestOptions) => Promise; - terminate: (served: string | ServerInfo) => void; - getRequestBody(req: http.IncomingMessage): Promise; - addPage: (path: string, template: string) => void; - addHTML: (path: string, template: string) => void; - buildPage: (pageStructure: string | string[] | { - [key: string]: any; - } | ((...args: any) => any), baseTemplate: string) => string; - hotreload: (socketURL?: string | URL, esbuild_cssFileName?: string) => string; - pwa: (pwaName?: string, cacheExpirationDays?: number, serviceWorkerUrl?: string) => string; -} diff --git a/dist/src/services/http/boilerplate/index.d.ts b/dist/src/services/http/boilerplate/index.d.ts deleted file mode 100644 index 9e5b4a36..00000000 --- a/dist/src/services/http/boilerplate/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare function htmlBodyBoilerPlate(html: string | string[]): string; -export declare function scriptBoilerPlate(scripts: string | string[]): string; -export declare const defaultServiceWorker: (cacheExpirationDays?: number) => string; -export declare const defaultManifest: (pwaName?: string) => string; diff --git a/dist/src/services/remote/remote.routes.d.ts b/dist/src/services/remote/remote.routes.d.ts deleted file mode 100644 index cabf37e7..00000000 --- a/dist/src/services/remote/remote.routes.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -export declare const nodeTemplates: {}; -export declare const remoteGraphRoutes: { - transferNode: (properties: string | Function | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), connection: any | Worker | WebSocket, name?: string) => any; - setNode: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), name?: string) => any; - makeNodeTransferrable: (properties: GraphNodeProperties, name?: string) => {}; - getListenerJSON: () => any; - makeRootTransferrable: () => {}; - setTemplate: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), name?: string) => string | false; - loadFromTemplate: (templateName: string, name?: string, properties?: { - [key: string]: any; - }) => any; - setMethod: (nodeTag: string, fn: string | (() => any), methodKey?: string) => boolean; - assignNode: (nodeTag: string, source: { - [key: string]: any; - }) => void; - getNodeProperties: (nodeTag: string) => {}; - proxyRemoteNode: (name: string, connection: any) => Promise; - transferClass: (classObj: any, connection: any | Worker | WebSocket, className?: string) => any; - receiveClass: (stringified: string, className?: string) => boolean; - transferFunction: (fn: Function, connection: any | Worker | WebSocket, fnName?: string) => any; - setGlobal: (key: string, value: any) => boolean; - assignGlobalObject: (target: string, source: { - [key: string]: any; - }) => boolean; - setValue: (key: string, value: any) => boolean; - assignObject: (target: string, source: { - [key: string]: any; - }) => boolean; - setGlobalFunction: (fn: any, fnName?: string) => boolean; - setGraphFunction: (fn: any, fnName?: string) => boolean; -}; diff --git a/dist/src/services/router/Router.d.ts b/dist/src/services/router/Router.d.ts deleted file mode 100644 index 3d6e0348..00000000 --- a/dist/src/services/router/Router.d.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { Graph, GraphNode } from "../../core/Graph"; -import { Service, ServiceOptions } from "../Service"; -export type User = { - _id: string; - send: (...args: any[]) => any; - request: (...args: any[]) => Promise | Promise[] | undefined; - post: (...args: any[]) => void; - run: (...args: any[]) => Promise | Promise[] | undefined; - subscribe: (...args: any[]) => Promise | Promise[] | undefined; - unsubscribe: (...args: any[]) => Promise | Promise[] | undefined; - sendAll?: (...args: any[]) => any; - requestAll?: (...args: any[]) => Promise | undefined; - postAll?: (...args: any[]) => void; - runAll?: (...args: any[]) => Promise | undefined; - subscribeAll?: (...args: any[]) => Promise | undefined; - unsubscribeAll?: (...args: any[]) => Promise | undefined; - terminate: (...args: any[]) => boolean; - onmessage?: (...args: any[]) => void; - onerror?: (...args: any[]) => void; - onclose?: ((user: User) => void) | ((...args: any[]) => void); - [key: string]: any; -}; -export type ConnectionProps = { - connection: GraphNode | Graph | { - [key: string]: any; - } | string; - service?: string | Graph | Service; - source?: string; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type ConnectionInfo = { - connection: GraphNode | Graph | { - [key: string]: any; - }; - service?: string | Service | Graph; - _id: string; - source: string; - connectionType?: string; - connectionsKey?: string; - send?: (message: any, ...a: any[]) => any; - request?: (message: any, method?: any, ...a: any[]) => Promise | Promise[]; - post?: (route: any, args?: any, method?: string, ...a: any[]) => void; - run?: (route: any, args?: any, method?: string, ...a: any[]) => Promise | Promise[]; - subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | undefined; - unsubscribe?: (route: any, sub: number, ...arrayBuffer: any[]) => Promise | Promise[]; - terminate: (...a: any[]) => boolean; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type RouterOptions = { - graph?: { - [key: string]: Service | Graph | any | { - service: Service | Graph | any; - connections: string[] | { - [key: string]: any; - }; - config?: { - [key: string]: { - _id?: string; - source?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - [key: string]: any; - }; - }; - }; - }; - timeout?: number; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class Router extends Service { - name: string; - connections: { - [key: string]: ConnectionInfo; - }; - sources: { - [key: string]: { - [key: string]: ConnectionInfo; - }; - }; - services: { - [key: string]: Service; - }; - serviceConnections: { - [key: string]: { - [key: string]: { - [key: string]: any; - }; - }; - }; - users: { - [key: string]: User; - }; - userTimeout: number; - order: string[]; - constructor(options?: RouterOptions); - addUser: (info: { - _id: string; - } & { - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; - }, connections?: { - [key: string]: string | ConnectionInfo | ConnectionProps; - }, config?: { - [key: string]: { - [key: string]: any; - service: Service; - _id?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - }; - }, receiving?: boolean) => Promise; - removeUser(profile: string | User | { - _id: string; - [key: string]: any; - }, terminate?: boolean): boolean; - getConnection: (sourceId: string, hasMethod?: string, connectionId?: string) => User | ConnectionInfo | undefined; - getConnections: (sourceId: string, hasMethod?: string, props?: {}) => {}; - runConnection: (userId: string, method: 'run' | 'post' | 'subscribe' | 'unsubscribe' | 'terminate' | 'send' | 'request' | 'runAll' | 'postAll' | 'subscribeAll' | 'unsubscribeAll' | 'sendAll' | 'requestAll', args: any[], connectionId?: string) => Promise; - subscribeThroughConnection: (route: string, remoteRelay: string | ConnectionInfo, remoteEndpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; - addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string, autoRemove?: boolean) => ConnectionInfo; - removeConnection: (connection: string | ConnectionInfo | { - [key: string]: any; - _id: string; - }, terminate?: boolean) => boolean; - routeService: (service: Service, connections?: any, source?: string, order?: string[]) => void; - addServiceConnections: (service: Service | string, connectionsKey: any, source?: string) => {}; - openConnection: (service: string | Service, options: { - [key: string]: any; - }, source?: string, ...args: any[]) => Promise; - terminate: (connection: string | ConnectionInfo) => boolean; - routeConnections: (route: string, transmitter: string | ConnectionInfo, receiver: string | ConnectionInfo, ...args: any[]) => Promise; - setUserData: (user: string | User, data: string | { - [key: string]: any; - }) => boolean; -} -export declare function connectionHasId(connection: { - _id?: string; - [key: string]: any; -}, timeout?: number): Promise; diff --git a/dist/src/services/sessions/sessions.service.d.ts b/dist/src/services/sessions/sessions.service.d.ts deleted file mode 100644 index 2ee6d805..00000000 --- a/dist/src/services/sessions/sessions.service.d.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { Service, ServiceOptions } from "../Service"; -import { User } from "../router/Router"; -/** - * Sessions are a way to run a loop that monitors data structures to know procedurally when and what to update - * - * OneWaySession: source sends props to listener, define listener, source default is creating user - * SharedSession: two modes: - * Hosted: Host receives props from all users based on propnames, users receive hostprops - * Shared: All users receive the same props based on their own updates - * - * There's also these older stream API functions that are more pure for monitoring objects/arrays and updating new data e.g. out of a buffer. - * Need to esplain/demo all that too.... @@__@@ - */ -export type OneWaySessionProps = { - _id?: string; - settings?: { - listener: string; - source: string; - propnames: { - [key: string]: boolean; - }; - admins?: { - [key: string]: boolean; - }; - moderators?: { - [key: string]: boolean; - }; - password?: string; - ownerId?: string; - onopen?: (session: OneWaySessionProps) => void; - onhasupdate?: (session: OneWaySessionProps, updated: any) => void; - onmessage?: (session: OneWaySessionProps, updated: any) => void; - onclose?: (session: OneWaySessionProps) => void; - [key: string]: any; - }; - data?: { - [key: string]: any; - }; - lastTransmit?: string | number; - [key: string]: any; -}; -export type SessionUser = { - _id: string; - sessions: { - [key: string]: any; - }; - sessionSubs: { - [key: string]: { - onopenSub?: number; - onmessage?: (session: SharedSessionProps, update: any, user: SessionUser) => void; - onopen?: (session: SharedSessionProps, user: SessionUser) => void; - onclose?: (session: SharedSessionProps, user: SessionUser) => void; - }; - }; - [key: string]: any; -} & User; -export type SharedSessionProps = { - _id?: string; - settings?: { - name: string; - propnames: { - [key: string]: boolean; - }; - users?: { - [key: string]: boolean; - }; - host?: string; - hostprops?: { - [key: string]: boolean; - }; - inheritHostData?: boolean; - admins?: { - [key: string]: boolean; - }; - moderators?: { - [key: string]: boolean; - }; - spectators?: { - [key: string]: boolean; - }; - banned?: { - [key: string]: boolean; - }; - password?: string; - ownerId?: string; - onhasupdate?: (session: SharedSessionProps, updated: any) => void; - onopen?: (session: SharedSessionProps) => void; - onmessage?: (session: SharedSessionProps, updated: any) => void; - onclose?: (session: SharedSessionProps) => void; - [key: string]: any; - }; - data?: { - shared: { - [key: string]: { - [key: string]: any; - }; - }; - oneWay?: { - [key: string]: any; - }; - [key: string]: any; - }; - lastTransmit?: string | number; - [key: string]: any; -}; -export type StreamInfo = { - [key: string]: { - object: { - [key: string]: any; - }; - settings: { - keys?: string[]; - callback?: 0 | 1 | Function; - lastRead?: number; - [key: string]: any; - }; - onupdate?: (data: any, streamSettings: any) => void; - onclose?: (streamSettings: any) => void; - }; -}; -export declare class SessionsService extends Service { - name: string; - users: { - [key: string]: SessionUser; - }; - sessions: { - oneWay: { - [key: string]: OneWaySessionProps; - }; - shared: { - [key: string]: SharedSessionProps; - }; - }; - invites: { - [key: string]: { - [key: string]: { - session: OneWaySessionProps | SharedSessionProps | string; - endpoint?: string; - }; - }; - }; - constructor(options?: ServiceOptions, users?: { - [key: string]: SessionUser; - }); - getSessionInfo: (sessionIdOrName?: string, userId?: string) => {}; - openOneWaySession: (options?: OneWaySessionProps, sourceUserId?: string, listenerUserId?: string) => any; - openSharedSession: (options: SharedSessionProps, userId?: string) => any; - open: (options: any, userId?: string) => void; - updateSession: (options: OneWaySessionProps | SharedSessionProps, userId?: string) => any; - joinSession: (sessionId: string, userId: string, options?: SharedSessionProps | OneWaySessionProps, remoteUser?: boolean) => SharedSessionProps | OneWaySessionProps | false; - inviteToSession: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, inviteEndpoint?: string, remoteUser?: boolean) => void; - receiveSessionInvite: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, endpoint?: string) => string; - acceptInvite: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, remoteUser?: boolean) => Promise; - rejectInvite: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, remoteUser?: boolean) => boolean; - leaveSession: (session: OneWaySessionProps | SharedSessionProps | string, userId: string, clear?: boolean, remoteUser?: boolean) => boolean; - deleteSession: (session: string | OneWaySessionProps | SharedSessionProps, userId: string, remoteUsers?: boolean) => boolean; - getFirstMatch(obj1: { - [key: string]: any; - }, obj2: { - [key: string]: any; - }): string | false; - swapHost: (session: OneWaySessionProps | SharedSessionProps | string, newHostId?: string, adoptData?: boolean, remoteUser?: boolean) => boolean; - subscribeToSession: (session: SharedSessionProps | OneWaySessionProps | string, userId: string, onmessage?: (session: SharedSessionProps | OneWaySessionProps, update: any, user: SessionUser) => void, onopen?: (session: SharedSessionProps | OneWaySessionProps, user: SessionUser) => void, onclose?: (session: SharedSessionProps | OneWaySessionProps, user: SessionUser) => void) => OneWaySessionProps | SharedSessionProps; - unsubsribeFromSession: (session: SharedSessionProps | OneWaySessionProps | string, userId?: string, clear?: boolean) => any; - sessionUpdateCheck: (sessionHasUpdate?: (session: OneWaySessionProps | SharedSessionProps, update: { - shared?: any; - oneWay?: any; - }) => void, transmit?: boolean) => any; - transmitSessionUpdates: (updates: { - oneWay: { - [key: string]: any; - }; - shared: { - [key: string]: any; - }; - }) => {}; - receiveSessionUpdates: (origin: any, update: string | { - oneWay: { - [key: string]: any; - }; - shared: { - [key: string]: any; - }; - }) => SessionUser; - getUpdatedUserData: (user: SessionUser) => {}; - userUpdateCheck: (user: SessionUser, onupdate?: (user: SessionUser, updateObj: { - [key: string]: any; - }) => void) => {}; - setUserProps: (user: string | SessionUser, props: string | { - [key: string]: any; - }) => boolean; - userUpdateLoop: { - __operator: (user: SessionUser, onupdate?: (user: SessionUser, updateObj: { - [key: string]: any; - }) => void) => {}; - __node: { - loop: number; - }; - }; - sessionLoop: { - __operator: (sessionHasUpdate?: (session: OneWaySessionProps | SharedSessionProps, update: { - shared?: any; - oneWay?: any; - }) => void, transmit?: boolean) => any; - __node: { - loop: number; - }; - }; - STREAMLATEST: number; - STREAMALLLATEST: number; - streamSettings: StreamInfo; - streamFunctions: any; - setStreamFunc: (name: string, key: string, callback?: 0 | 1 | Function) => boolean; - addStreamFunc: (name: any, callback?: (data: any) => void) => void; - setStream: (object?: {}, settings?: { - keys?: string[]; - callback?: Function; - }, streamName?: string, onupdate?: (update: any, settings: any) => void, onclose?: (settings: any) => void) => { - object: { - [key: string]: any; - }; - settings: { - [key: string]: any; - keys?: string[]; - callback?: 0 | Function | 1; - lastRead?: number; - }; - onupdate?: (data: any, streamSettings: any) => void; - onclose?: (streamSettings: any) => void; - }; - removeStream: (streamName: any, key: any) => boolean; - updateStreamData: (streamName: any, data?: {}) => false | { - [key: string]: any; - }; - getStreamUpdate: (streamName: string) => {}; - getAllStreamUpdates: () => {}; - streamLoop: { - __operator: () => {}; - __node: { - loop: number; - }; - }; -} diff --git a/dist/src/services/sse/SSE.browser.d.ts b/dist/src/services/sse/SSE.browser.d.ts deleted file mode 100644 index 46111a03..00000000 --- a/dist/src/services/sse/SSE.browser.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type EventSourceProps = { - url: string; - events: { - message?: (ev: any, sseinfo?: EventSourceInfo) => void; - open?: (ev: any, sseinfo?: EventSourceInfo) => void; - close?: (ev: any, sseinfo?: EventSourceInfo) => void; - error?: (ev: any, sseinfo?: EventSourceInfo) => void; - [key: string]: any; - }; - onmessage?: (ev: any, sseinfo?: EventSourceInfo) => void; - onopen?: (ev: any, sseinfo?: EventSourceInfo) => void; - onclose?: (ev: any, sseinfo?: EventSourceInfo) => void; - onerror?: (ev: any, sseinfo?: EventSourceInfo) => void; - evoptions?: boolean | AddEventListenerOptions; - type?: 'eventsource' | string; - _id?: string; - keepState?: boolean; -}; -export type EventSourceInfo = { - source: EventSource; - send: (message: any) => any; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => any; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => void; - graph: SSEfrontend; -} & EventSourceProps; -export declare class SSEfrontend extends Service { - name: string; - eventsources: { - [key: string]: EventSourceInfo; - }; - connections: { - eventsources: { - [key: string]: EventSourceInfo; - }; - }; - constructor(options?: ServiceOptions); - openSSE: (options: EventSourceProps) => EventSourceInfo; - open: (options: EventSourceProps) => EventSourceInfo; - POST: (message: any | ServiceMessage, url?: string | URL, type?: XMLHttpRequestResponseType, mimeType?: string | undefined) => Promise; - transmit: (message: any | ServiceMessage, url: string | URL) => Promise; - request: (message: ServiceMessage | any, url: string, method?: string, sessionId?: string) => Promise; - runRequest: (message: any, url: string | any, callbackId: string | number, sessionId?: string) => any; - subscribeSSE: (route: string, url: string, args?: any[], key?: string, subInput?: boolean) => number; - subscribeToSSE: (route: string, url: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, sessionId?: string) => Promise; - terminate: (sse: EventSourceInfo | EventSource | string) => void; -} diff --git a/dist/src/services/sse/SSE.node.d.ts b/dist/src/services/sse/SSE.node.d.ts deleted file mode 100644 index f4adbc3a..00000000 --- a/dist/src/services/sse/SSE.node.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// -/// -/// -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import { Session, Channel } from 'better-sse'; -import http from 'http'; -import https from 'https'; -import { Readable } from "node:stream"; -export type SSEProps = { - server: http.Server | https.Server; - path: string; - channels?: string[]; - onconnection?: (session: any, sseinfo: any, _id: string, req: http.IncomingMessage, res: http.ServerResponse) => void; - onclose?: (sse: any) => void; - onconnectionclose?: (session: any, sseinfo: any, _id: string, req: http.IncomingMessage, res: http.ServerResponse) => void; - type?: 'sse' | string; - _id?: string; - [key: string]: any; -}; -export type SSEChannelInfo = { - channel: Channel>; - sessions: { - [key: string]: Session; - }; - requests: { - [key: string]: Function; - }; - send: (message: any, eventName?: string, sessionId?: string) => any; - request: (message: any, method?: string, sessionId?: string, eventName?: string) => Promise | Promise[]; - post: (route: any, args?: any, method?: string, sessionId?: string, eventName?: string) => void; - run: (route: any, args?: any, method?: string, sessionId?: string, eventName?: string) => Promise | Promise[]; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => Promise | Promise[] | undefined; - unsubscribe: (route: any, sub: number, sessionId?: string, eventName?: string) => Promise | Promise[]; - terminate: () => boolean; - _id: string; - graph: SSEbackend; -} & SSEProps; -export type SSEClientInfo = { - _id: string; - session: Session; - served: SSEChannelInfo; - send: (message: any, eventName?: string) => any; - request: (message: any, method?: string, eventName?: string) => Promise; - post: (route: any, args?: any, method?: string, eventName?: string) => void; - run: (route: any, args?: any, method?: string, eventName?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => any; - unsubscribe: (route: any, sub: number, eventName?: string) => Promise; - terminate: () => boolean; - onclose?: (session: any, sseinfo: any, _id: string, req: http.IncomingMessage, res: http.ServerResponse) => void; - graph: SSEbackend; -}; -export declare class SSEbackend extends Service { - name: string; - debug: boolean; - servers: { - [key: string]: SSEChannelInfo; - }; - eventsources: { - [key: string]: SSEClientInfo; - }; - connections: { - servers: { - [key: string]: SSEChannelInfo; - }; - eventsources: { - [key: string]: SSEClientInfo; - }; - }; - constructor(options?: ServiceOptions); - openSSE: (options: SSEProps) => false | SSEChannelInfo; - open: (options: SSEProps) => false | SSEChannelInfo; - streamIterable: (path: string, iterable: Iterable | AsyncIterable, sessionId?: string, eventName?: string) => Promise | Promise[]; - streamReadable: (path: string, readable: Readable, sessionId?: string, eventName?: string) => Promise | Promise[]; - transmit: (data: string | ServiceMessage, path?: string, eventName?: string, sessionId?: string) => boolean; - request: (message: any, path: string, method?: string, sessionId?: string, eventName?: string) => Promise; - runRequest: (message: any, path: string, callbackId: string | number, sessionId?: string) => any; - subscribeSSE: (route: string, path: string, args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => number; - subscribeToSSE: (route: string, path: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => Promise | Promise[]; - terminate: (sse: string | SSEChannelInfo) => boolean; -} diff --git a/dist/src/services/utils.d.ts b/dist/src/services/utils.d.ts deleted file mode 100644 index 9efee154..00000000 --- a/dist/src/services/utils.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export declare let recursivelyStringifyFunctions: (obj: { - [key: string]: any; -}) => {}; -export declare function getFnParamNames(fn: any): any; -export declare let getFunctionHead: (methodString: any) => any; -export declare function parseFunctionFromText(method?: string): any; -export declare function reconstructObject(json?: string | { - [x: string]: any; -}): any; -export declare const stringifyWithCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyWithFunctionsAndCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyFast: (obj: any, space?: any) => string; diff --git a/dist/src/services/webrtc/WebRTC.browser.d.ts b/dist/src/services/webrtc/WebRTC.browser.d.ts deleted file mode 100644 index 74a711f8..00000000 --- a/dist/src/services/webrtc/WebRTC.browser.d.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type WebRTCProps = { - _id?: string; - channels?: { - [key: string]: (true | RTCDataChannelInit | RTCDataChannel); - }; - config?: RTCConfiguration; - description?: RTCSessionDescription | string; - offer?: RTCOfferOptions; - hostcandidates?: { - [key: string]: RTCIceCandidate; - }; - peercandidates?: { - [key: string]: RTCIceCandidate; - }; - candidates?: { - [key: string]: RTCIceCandidate; - }; - answer?: RTCAnswerOptions; - ontrack?: (ev: RTCTrackEvent) => void; - removetrack?: (ev: MediaStreamTrackEvent) => void; - onicecandidate?: (ev: RTCPeerConnectionIceEvent) => void; - onicecandidateerror?: (ev: Event) => void; - onnegotiationneeded?: (ev: Event, description: RTCSessionDescription) => void; - ondatachannel?: (ev: RTCDataChannelEvent) => void; - ondata?: (ev: MessageEvent, channel: RTCDataChannel, room: any) => void; - onconnectionstatechange?: (ev: Event) => void; - oniceconnectionstatechange?: (ev: Event) => void; - onclose?: (rtc: WebRTCInfo) => void; - caller?: string; - remoteId?: string; - [key: string]: any; -}; -export type WebRTCInfo = { - _id: string; - rtc: RTCPeerConnection; - senders?: (RTCRtpSender | undefined)[]; - receivers?: (RTCRtpReceiver | undefined)[]; - streams?: (MediaStream | undefined)[]; - polite?: boolean; - videoSender?: RTCRtpSender; - audioSender?: RTCRtpSender; - videoStream?: MediaStream; - audioStream?: MediaStream; - send: (message: any) => void; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, channelId?: string) => Promise; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => boolean; - graph: WebRTCfrontend; -} & WebRTCProps; -export declare class WebRTCfrontend extends Service { - name: string; - rtc: { - [key: string]: WebRTCInfo; - }; - unanswered: { - [key: string]: WebRTCProps; - }; - iceServers: RTCIceServer[]; - connections: { - rtc: { - [key: string]: WebRTCInfo; - }; - }; - constructor(options?: ServiceOptions, iceServers?: RTCIceServer[]); - openRTC: (options?: WebRTCProps) => Promise; - open: (options?: WebRTCProps) => Promise; - addIceCandidate: (rtc: RTCPeerConnection | string, candidate: RTCIceCandidate) => Promise; - receiveCallInformation: (options: WebRTCProps) => Promise; - answerCall: (options: WebRTCProps | string) => Promise; - rejectCall: (options: WebRTCProps | string) => boolean; - negotiateCall: (rtc: RTCPeerConnection | string, description: string | RTCSessionDescription, polite?: boolean) => Promise; - createOffer(rtc: RTCPeerConnection | string, options: WebRTCProps | string): Promise; - createAnswer(rtc: RTCPeerConnection | string, options: WebRTCProps | string): Promise; - answerPeer: (rtc: RTCPeerConnection | string, options: WebRTCProps | string) => Promise; - createStream: (options: { - [key: string]: { - track: MediaStreamTrack | MediaTrackConstraints; - onended: (ev: any) => void; - onmute: (ev: any) => void; - onunmute: (ev: any) => void; - }; - }) => MediaStream; - addUserMedia: (rtc: RTCPeerConnection, options?: MediaStreamConstraints, info?: WebRTCInfo) => Promise; - addTrack: (rtc: RTCPeerConnection, track: MediaStreamTrack, stream: MediaStream) => RTCRtpSender; - removeTrack: (rtc: RTCPeerConnection, sender: RTCRtpSender) => boolean; - addDataChannel: (rtc: RTCPeerConnection, name: string, options?: RTCDataChannelInit) => RTCDataChannel; - enableAudio: (call: WebRTCInfo, audioOptions?: boolean | (MediaTrackConstraints & { - deviceId?: string; - })) => Promise; - enableVideo: (call: WebRTCInfo, videoOptions?: (MediaTrackConstraints & { - deviceId?: string; - optional?: { - minWidth: number; - }[]; - }), includeAudio?: boolean | (MediaTrackConstraints & { - deviceId?: string; - })) => Promise; - disableAudio(call: WebRTCInfo): void; - disableVideo(call: WebRTCInfo): void; - transmit: (data: ServiceMessage | any, id?: string, channel?: string | RTCDataChannel) => boolean; - terminate: (rtc: RTCPeerConnection | WebRTCInfo | string) => boolean; - request: (message: ServiceMessage | any, channel: RTCDataChannel, _id: string, method?: string) => Promise; - runRequest: (message: any, channelOrRtcId: RTCDataChannel | string, callbackId: string | number) => any; - subscribeRTC: (route: string, rtcId: string, args?: any[], key?: string, subInput?: boolean, channel?: string | RTCDataChannel) => number; - subscribeToRTC: (route: string, rtcId: string, channelId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => Promise; -} diff --git a/dist/src/services/worker/ProxyListener.d.ts b/dist/src/services/worker/ProxyListener.d.ts deleted file mode 100644 index 104c3c8b..00000000 --- a/dist/src/services/worker/ProxyListener.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -declare function focusEventHandler(event: any, sendFn: any): void; -declare function wheelEventHandler(event: any, sendFn: any, preventDefault: any): void; -declare function preventDefaultHandler(event: any, sendFn: any, preventDefault: any): void; -declare function touchEventHandler(event: any, sendFn: any, preventDefault: any): void; -declare function filteredKeydownEventHandler(event: any, sendFn: any, preventDefault: any): void; -export declare const eventHandlers: { - contextmenu: typeof preventDefaultHandler; - mousedown: (event: any, sendFn: any) => void; - mousemove: (event: any, sendFn: any) => void; - mouseup: (event: any, sendFn: any) => void; - pointerdown: (event: any, sendFn: any) => void; - pointermove: (event: any, sendFn: any) => void; - pointerup: (event: any, sendFn: any) => void; - pointerlockchange: (event: any, sendFn: any) => void; - webkitpointerlockchange: (event: any, sendFn: any) => void; - focus: typeof focusEventHandler; - blur: typeof focusEventHandler; - pointerout: (event: any, sendFn: any) => void; - touchstart: typeof touchEventHandler; - touchmove: typeof touchEventHandler; - touchend: typeof touchEventHandler; - wheel: typeof wheelEventHandler; - keydown: typeof filteredKeydownEventHandler; - keyup: typeof filteredKeydownEventHandler; -}; -export declare function initProxyElement(element: any, worker: any, id: any, preventDefault?: boolean): any; -export declare class EventDispatcher { - __listeners: any; - addEventListener(type: any, listener: any): void; - hasEventListener(type: any, listener: any): boolean; - removeEventListener(type: any, listener: any): void; - dispatchEvent(event: any, target: any): void; -} -export declare class ElementProxyReceiver extends EventDispatcher { - __listeners: any; - proxied: any; - style: any; - width: any; - left: any; - right: any; - top: any; - height: any; - constructor(); - get clientWidth(): any; - get clientHeight(): any; - setPointerCapture: () => void; - releasePointerCapture: () => void; - getBoundingClientRect: () => { - left: any; - top: any; - width: any; - height: any; - right: any; - bottom: any; - }; - handleEvent: (data: any) => void; - focus(): void; - blur(): void; -} -export declare class ProxyManager { - targets: any; - constructor(); - makeProxy: (id: any, addTo?: any) => void; - getProxy: (id: any) => any; - handleEvent: (data: any, id: any) => boolean; -} -declare function makeProxy(id: any, elm?: any): any; -declare function handleProxyEvent(data: any, id: any): any; -export declare const proxyElementWorkerRoutes: { - initProxyElement: typeof initProxyElement; - makeProxy: typeof makeProxy; - handleProxyEvent: typeof handleProxyEvent; -}; -export {}; diff --git a/dist/src/services/worker/Subprocess.d.ts b/dist/src/services/worker/Subprocess.d.ts deleted file mode 100644 index 97eea0a8..00000000 --- a/dist/src/services/worker/Subprocess.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { WorkerInfo, WorkerService } from './Worker.service'; -import { GraphNodeProperties } from '../../core/Graph'; -export declare type Subprocess = (context: SubprocessContext, data: { - [key: string]: any; -} | any) => { - [key: string]: any; -} | undefined; -export declare type SubprocessContextProps = { - ondata: Subprocess; - oncreate?: (context: SubprocessContext) => void; - structs?: { - [key: string]: any; - }; - [key: string]: any; -}; -export declare type SubprocessContext = { - ondata: Subprocess; - oncreate?: (context: SubprocessContext) => void; - run?: (data: { - [key: string]: any; - } | any) => any; - [key: string]: any; -}; -export declare type SubprocessWorkerProps = { - subprocess: string | { - name: string; - structs: {}; - oncreate: string | ((ctx: SubprocessContext) => void); - ondata: string | ((context: any, data: { - [key: string]: any; - } | any) => { - [key: string]: any; - } | undefined); - props?: { - [key: string]: any; - }; - }; - subscribeRoute: string; - source?: WorkerInfo; - route: string; - init?: string; - initArgs?: any[]; - otherArgs?: any[]; - callback?: string | ((data: any) => any); - pipeTo?: { - worker?: WorkerInfo; - portId?: string; - route: string; - otherArgs?: any[]; - init?: string; - initArgs?: any[]; - }; - worker?: WorkerInfo; - url?: any; - stopped?: boolean; -}; -export declare type SubprocessWorkerInfo = { - sub: number; - blocking?: boolean; - stop: () => void; - start: () => void; - terminate: () => void; - setArgs: (args: any[] | { - [key: string]: any; - }) => void; -} & SubprocessWorkerProps; -export declare const algorithms: { - [key: string]: SubprocessContextProps; -}; -export declare const loadAlgorithms: (settings: { - [key: string]: SubprocessContextProps; -}) => { - [key: string]: SubprocessContextProps; -} & { - [key: string]: SubprocessContextProps; -}; -export declare function createSubprocess(options: SubprocessContextProps, inputs?: { - [key: string]: any; -}): SubprocessContext; -export declare const subprocessRoutes: { - loadAlgorithms: (settings: { - [key: string]: SubprocessContextProps; - }) => { - [key: string]: SubprocessContextProps; - } & { - [key: string]: SubprocessContextProps; - }; - initSubprocesses: (subprocesses: { - [key: string]: SubprocessWorkerProps; - }, service?: WorkerService) => Promise<{ - [key: string]: SubprocessWorkerInfo; - }>; - addSubprocessTemplate: (name: string, structs: {}, oncreate: string | ((ctx: SubprocessContext) => void), ondata: string | ((context: any, data: any) => { - [key: string]: any; - }), props?: { - [key: string]: any; - }) => boolean; - updateSubprocess: (structs: {}, _id?: string) => void; - createSubprocess: (options: SubprocessContextProps | string, inputs?: { - [key: string]: any; - }) => any; - runSubprocess: (data: { - [key: string]: any; - }, _id?: string) => any; - transferNode: (properties: string | Function | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), connection: any, name?: string) => any; - setNode: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - })) => any; - proxyRemoteNode: (name: string, connection: any) => Promise; - makeNodeTransferrable: (properties: GraphNodeProperties, name?: string) => {}; - setTemplate: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), name?: string) => string | false; - loadFromTemplate: (templateName: string, name?: string) => any; - setMethod: (route: string, fn: string | (() => any), methodKey?: string) => boolean; - assignNode: (nodeTag: string, source: { - [key: string]: any; - }) => void; - getNodeProperties: (nodeTag: string) => {}; - transferClass: (classObj: any, connection: any, className?: string) => any; - receiveClass: (stringified: string, className?: string) => boolean; - transferFunction: (fn: Function, connection: any, fnName?: string) => any; - setGlobal: (key: string, value: any) => boolean; - assignGlobalObject: (target: string, source: { - [key: string]: any; - }) => boolean; - setValue: (key: string, value: any) => boolean; - assignObject: (target: string, source: { - [key: string]: any; - }) => boolean; - setGlobalFunction: (fn: any, fnName?: string) => boolean; - setGraphFunction: (fn: any, fnName?: string) => boolean; -}; diff --git a/dist/src/services/worker/Worker.service.d.ts b/dist/src/services/worker/Worker.service.d.ts deleted file mode 100644 index 9539bb89..00000000 --- a/dist/src/services/worker/Worker.service.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import Worker from 'web-worker'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export type WorkerRoute = { - worker?: WorkerInfo; - workerUrl?: string | URL | Blob; - transferFunctions?: { - [key: string]: Function; - }; - transferClasses?: { - [key: string]: Function; - }; - parentRoute?: string; - portId?: string; - callback?: string; - stopped?: boolean; - blocking?: boolean; - init?: string; - initArgs?: any[]; - initTransfer?: any[]; -} & GraphNodeProperties & WorkerProps; -export type WorkerProps = { - worker?: WorkerInfo; - workerUrl?: string | URL | Blob; - url?: URL | string | Blob; - _id?: string; - port?: MessagePort; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - onclose?: (worker: Worker | MessagePort) => void; -}; -export type WorkerInfo = { - worker: Worker | MessagePort; - send: (message: any, transfer?: any) => void; - request: (message: any, method?: string, transfer?: any) => Promise; - post: (route: any, args?: any, method?: string, transfer?: any) => void; - run: (route: any, args?: any, method?: string, transfer?: any) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; - unsubscribe: (route: any, sub: number) => Promise; - start: (route?: any, portId?: string, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; - stop: (route?: string, portId?: string) => Promise; - workerSubs: { - [key: string]: { - sub: number | false; - route: string; - portId: string; - callback?: ((res: any) => void) | string; - blocking?: boolean; - }; - }; - terminate: () => boolean; - postMessage: (message: any, transfer?: any[]) => void; - graph: WorkerService; - _id: string; -} & WorkerProps & WorkerRoute; -export declare class WorkerService extends Service { - name: string; - workers: { - [key: string]: WorkerInfo; - }; - threadRot: number; - connections: any; - constructor(options?: ServiceOptions); - loadWorkerRoute: (node: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; - workerloader: any; - addDefaultMessageListener: () => void; - postMessage: (message: any, target: string, transfer?: Transferable[]) => void; - addWorker: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - open: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - close: () => void; - toObjectURL: (scriptTemplate: string) => string; - getTransferable(message: any): any; - transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: StructuredSerializeOptions) => any; - terminate: (worker: Worker | MessagePort | string | WorkerInfo) => boolean; - establishMessageChannel: (worker: Worker | string | MessagePort | WorkerInfo, worker2?: Worker | string | MessagePort | WorkerInfo) => string | false; - request: (message: ServiceMessage | any, workerId: string, transfer?: any, method?: string) => Promise; - runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number, getTransferable?: boolean) => any; - subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => number; - subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; - triggerSubscription: (route: string, workerId: string, result: any) => Promise; - pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, args?: any[], key?: any, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; - unpipeWorkers: (sourceRoute: string, sourceWorker: WorkerInfo | string, sub?: number) => Promise; -} diff --git a/dist/src/services/worker/WorkerCanvas.d.ts b/dist/src/services/worker/WorkerCanvas.d.ts deleted file mode 100644 index a4526480..00000000 --- a/dist/src/services/worker/WorkerCanvas.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { initProxyElement } from './ProxyListener'; -export type WorkerCanvasTransferProps = { - canvas: HTMLCanvasElement; - context?: string; - _id?: string; - draw?: string | ((self: any, canvas: any, context: any) => void); - update?: string | ((self: any, canvas: any, context: any, input: any) => void); - init?: string | ((self: any, canvas: any, context: any) => void); - clear?: string | ((self: any, canvas: any, context: any) => void); - transfer?: any[]; - animating?: boolean; - [key: string]: any; -}; -export type CanvasProps = { - canvas: any; - context?: string | CanvasRenderingContext2D | WebGL2RenderingContext | WebGLRenderingContext; - _id: string; - width?: number; - height?: number; - draw?: string | ((self: any, canvas: any, context: any) => void); - update?: string | ((self: any, canvas: any, context: any, input: any) => void); - init?: string | ((self: any, canvas: any, context: any) => void); - clear?: string | ((self: any, canvas: any, context: any) => void); - animating?: boolean; - preventDefault?: boolean; - [key: string]: any; -}; -export type CanvasControls = { - _id: string; - draw: (props?: any, transfer?: any) => void; - update: (props: { - [key: string]: any; - }, transfer?: any) => void; - clear: () => void; - init: () => void; - stop: () => void; - start: () => void; - set: (newDrawProps: CanvasProps, transfer?: any) => void; -}; -export type WorkerCanvasControls = { - worker: Worker | MessagePort; - terminate: () => void; -} & CanvasControls; -export type WorkerCanvas = { - graph: any; - canvas: any; - context?: CanvasRenderingContext2D | WebGL2RenderingContext | WebGLRenderingContext; - _id: string; - draw?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); - update?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context'], input: any) => void); - init?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); - clear?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); - stop: () => void; - start: () => void; - set: (newDrawProps: CanvasProps, transfer?: any) => void; - terminate: () => void; - animating: boolean; - [key: string]: any; -}; -export declare function Renderer(options: CanvasProps & { - worker?: Worker | string | Blob | MessagePort | true; - route?: string; -}): string | CanvasControls | Promise; -export declare function transferCanvas(worker: Worker | MessagePort, options: WorkerCanvasTransferProps, route?: string): WorkerCanvasControls; -export declare function setDraw(settings: CanvasProps, _id?: string): string; -export declare function setupCanvas(options: CanvasProps): string | CanvasControls | Promise; -export declare function drawFrame(props?: { - [key: string]: any; -}, _id?: string): string; -export declare function clearCanvas(_id?: string): string; -export declare function initCanvas(_id?: string): string; -export declare function updateCanvas(input?: any, _id?: string): string; -export declare function setProps(props?: { - [key: string]: any; -}, _id?: string): string; -export declare function startAnim(_id?: string, draw?: string | ((this: any, canvas: any, context: any) => void)): string; -export declare function stopAnim(_id: string): string; -export declare function getCanvas(_id?: string): any; -export declare const workerCanvasRoutes: { - Renderer: typeof Renderer; - transferCanvas: typeof transferCanvas; - setupCanvas: typeof setupCanvas; - setDraw: typeof setDraw; - drawFrame: typeof drawFrame; - clearCanvas: typeof clearCanvas; - initCanvas: typeof initCanvas; - updateCanvas: typeof updateCanvas; - setProps: typeof setProps; - startAnim: typeof startAnim; - stopAnim: typeof stopAnim; - getCanvas: typeof getCanvas; - initProxyElement: typeof initProxyElement; - makeProxy: (id: any, elm?: any) => any; - handleProxyEvent: (data: any, id: any) => any; -}; diff --git a/dist/src/services/worker/canvas.worker.d.ts b/dist/src/services/worker/canvas.worker.d.ts deleted file mode 100644 index 5298df7f..00000000 --- a/dist/src/services/worker/canvas.worker.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _default: any; -export default _default; diff --git a/dist/src/services/wss/WSS.browser.d.ts b/dist/src/services/wss/WSS.browser.d.ts deleted file mode 100644 index e232e404..00000000 --- a/dist/src/services/wss/WSS.browser.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type WSSRoute = { - socket?: WebSocketInfo; - transferFunctions?: { - [key: string]: Function; - }; - transferClasses?: { - [key: string]: Function; - }; - parentRoute?: string; - callback?: string; - stopped?: boolean; - blocking?: boolean; - init?: string; - initArgs?: any[]; -} & GraphNodeProperties & WebSocketProps; -export type WebSocketProps = { - host: string; - port: number; - path?: string; - debug?: boolean; - onmessage?: (data: string | ArrayBufferLike | Blob | ArrayBufferView, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onopen?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onclose?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onerror?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - protocol?: 'ws' | 'wss'; - keepState?: boolean; - type?: 'socket'; - _id?: string; - [key: string]: any; -} & GraphNodeProperties; -export type WebSocketInfo = { - socket: WebSocket; - address: string; - send: (message: any) => void; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => any; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => boolean; - _id?: string; - graph: WSSfrontend; -} & WebSocketProps & GraphNode; -export declare class WSSfrontend extends Service { - name: string; - sockets: { - [key: string]: WebSocketInfo & GraphNode; - }; - connections: { - sockets: { - [key: string]: { - socket: WebSocket; - address: string; - send: (message: any) => void; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => any; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => boolean; - _id?: string; - graph: WSSfrontend; - } & { - [key: string]: any; - host: string; - port: number; - path?: string; - debug?: boolean; - onmessage?: (data: string | ArrayBufferView | ArrayBufferLike | Blob, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onopen?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onclose?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onerror?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - protocol?: "ws" | "wss"; - keepState?: boolean; - type?: "socket"; - _id?: string; - } & GraphNodeProperties & GraphNode; - }; - }; - constructor(options?: ServiceOptions); - loadWebSocketRoute: (node: WebSocketProps & GraphNode) => WebSocketInfo; - socketloader: { - websockets: (node: WebSocketProps & GraphNode, parent: WebSocketProps & GraphNode, graph: WSSfrontend, roots: any) => void; - }; - openWS: (options?: WebSocketProps) => WebSocketInfo; - open: (options?: WebSocketProps) => WebSocketInfo; - transmit: (data: string | ArrayBufferLike | Blob | ArrayBufferView | ServiceMessage, ws: WebSocket) => boolean; - terminate: (ws: WebSocket | string) => boolean; - request: (message: ServiceMessage | any, ws: WebSocket, _id: string, method?: string) => Promise; - runRequest: (message: any, ws: WebSocket | string, callbackId: string | number) => any; - subscribeSocket: (route: string, socket: WebSocket | string, args?: any[], key?: string, subInput?: boolean) => number; - subscribeToSocket: (route: string, socketId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => Promise; -} diff --git a/dist/src/services/wss/WSS.node.d.ts b/dist/src/services/wss/WSS.node.d.ts deleted file mode 100644 index 3417b055..00000000 --- a/dist/src/services/wss/WSS.node.d.ts +++ /dev/null @@ -1,100 +0,0 @@ -/// -/// -/// -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import WebSocket, { PerMessageDeflateOptions, WebSocketServer } from 'ws'; -import http from 'http'; -import https from 'https'; -import { GraphNodeProperties } from "../../core/Graph"; -export type SocketServerProps = { - server?: http.Server | https.Server | true; - port?: 7000 | number; - path?: 'wss' | 'hotreload' | 'python' | string; - noServer?: boolean; - host?: 'localhost' | '127.0.0.1' | string; - perMessageDeflate?: PerMessageDeflateOptions; - onmessage?: (data: any, ws: WebSocket, serverinfo: SocketServerInfo) => void; - onclose?: (wss: WebSocketServer, serverinfo: SocketServerInfo) => void; - onconnection?: (ws: WebSocket, request: http.IncomingMessage, serverinfo: SocketServerInfo, clientId: string) => void; - onconnectionclosed?: (code: number, reason: Buffer, ws: WebSocket, serverinfo: SocketServerInfo, clientId: string) => void; - onerror?: (err: Error, wss: WebSocketServer, serverinfo: SocketServerInfo) => void; - onupgrade?: (ws: WebSocket, serverinfo: SocketServerInfo, request: http.IncomingMessage, socket: any, head: Buffer) => void; - keepState?: boolean; - type?: 'wss'; - debug?: boolean; - serverOptions?: WebSocket.ServerOptions; - [key: string]: any; -} & GraphNodeProperties; -export type SocketServerInfo = { - wss: WebSocketServer; - clients: { - [key: string]: WebSocket; - }; - address: string; - send: (message: any, socketId?: string) => void; - request: (message: any, method?: string, socketId?: string) => Promise | Promise[]; - post: (route: any, args?: any, method?: string, socketId?: string) => void; - run: (route: any, args?: any, method?: string, socketId?: string) => Promise | Promise[]; - subscribe: (route: any, callback?: ((res: any) => void) | string, socketId?: string) => Promise | Promise[] | undefined; - unsubscribe: (route: any, sub: number, socketId?: string) => Promise | Promise[]; - terminate: (socketId?: string) => boolean; - graph: WSSbackend; -} & SocketServerProps; -export type SocketProps = { - host?: string; - port?: number; - path?: string; - socket?: WebSocket; - address?: string; - debug?: boolean; - serverOptions?: WebSocket.ServerOptions; - onmessage?: (data: string | ArrayBufferLike | Blob | ArrayBufferView | Buffer[], ws: WebSocket, wsinfo: SocketProps) => void; - onopen?: (ws: WebSocket, wsinfo: SocketProps) => void; - onclose?: (code: any, reason: any, ws: WebSocket, wsinfo: SocketProps) => void; - onerror?: (er: Error, ws: WebSocket, wsinfo: SocketProps) => void; - protocol?: 'ws' | 'wss'; - type?: 'socket'; - _id?: string; - keepState?: boolean; -} & GraphNodeProperties; -export type SocketInfo = { - socket: WebSocket; - address?: string; - send: (message: any) => void; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any, method?: string) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => any; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => void; - graph: WSSbackend; -} & SocketProps; -export declare class WSSbackend extends Service { - name: string; - debug: boolean; - servers: { - [key: string]: SocketServerInfo; - }; - sockets: { - [key: string]: SocketInfo; - }; - connections: { - servers: { - [key: string]: SocketServerInfo; - }; - sockets: { - [key: string]: SocketInfo; - }; - }; - constructor(options?: ServiceOptions); - open: (options: SocketServerProps | SocketProps) => SocketServerInfo | SocketInfo; - setupWSS: (options: SocketServerProps) => SocketServerInfo; - openWS: (options: SocketProps) => SocketInfo; - transmit: (message: string | ArrayBufferLike | Blob | ArrayBufferView | Buffer[] | ServiceMessage, ws: WebSocketServer | WebSocket) => void; - closeWS: (ws: WebSocket | string) => boolean; - terminate: (ws: WebSocketServer | WebSocket | string) => boolean; - request: (message: ServiceMessage | any, ws: WebSocket, _id: string, method?: string) => Promise; - runRequest: (message: any, ws: WebSocket | string, callbackId: string | number) => any; - subscribeSocket: (route: string, socket: WebSocket | string, args?: any[], key?: string, subInput?: boolean) => number; - subscribeToSocket: (route: string, socketId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => Promise; -} diff --git a/docs/Graph.md b/docs/Graph.md index dc371f39..8c377c5d 100644 --- a/docs/Graph.md +++ b/docs/Graph.md @@ -5,7 +5,7 @@ The Graph and GraphNode classes are an implementation of the acyclic graphs and ### First Steps -To create a Graph, simply declare an object as your "roots" or your program hierarchy with lists of node definitions, then load it into the graph. After that your nodes become interactive through both the definition objects and through accessors on the Graph instance. +To create a Graph, simply declare an object as your "tree" or your program hierarchy with lists of node definitions, then load it into the graph. After that your nodes become interactive through both the definition objects and through accessors on the Graph instance. ```ts @@ -40,12 +40,12 @@ let nodeB = { } }; -let roots = { +let tree = { nodeA, nodeB }; -let graph = new Graph({ roots }); +let graph = new Graph({tree}); nodeB.x += 1; //should trigger nodeA listener 'nodeB.x' @@ -70,19 +70,18 @@ Graph nodes can have many properties, and even more if you specify loaders on th ```ts type GraphNodeProperties = { - __props?:Function|{[key:string]:any}|GraphNodeProperties|GraphNode, //Proxy objects or from a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. + __props?:Function|GraphNodeProperties, //a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. __operator?:((...args:any[])=>any)|string, //The 'main' function of the graph node, children will call this function if triggered by a parent. Functions passed as graphnodeproperties become the operator which can set state. - __children?:{[key:string]:any}, //child nodes belonging to this node, e.g. for propagating results - __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true, subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs + __children?:{[key:string]:GraphNodeProperties}, //child nodes belonging to this node, e.g. for propagating results + __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true,subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs __onconnected?:((node)=>void|((node)=>void)[]), //what happens once the node is created? __ondisconnected?:((node)=>void|((node)=>void)[]), //what happens when the node is deleted? __node?:{ //node specific properties, can contain a lot more things tag?:string, state?:EventHandler, //by default has a global shared state + inputState?:boolean //we can track inputs on a node, subscribe to state with 'input' on the end of the tag or 'tag.prop' [key:string]:any }, - __args?:any[], //can structure input arguments, include '__result' when generically calling operators for where to pass the original input in in a set of arguments - __callable?:boolean, //we can have the graphnode return itself as a callable function with private properties [key:string]:any } ``` @@ -96,7 +95,6 @@ When a node is subscribed to it enhances itself with getters and setters that al The `__operator` is where default functions for nodes are stored. This lets you pass class methods in for instance as node definitions and then they can gain state and listener access across the program. Arrow functions on classes are nice because they will remain bound to their parent class instance even when applied to nodes. We use this extensively to subscribe across remote endpoints to outputs of specific methods or arbitrary states e.g. a game state. -The `__callable` property will be applied to nodes when functions are provided as property definitions, this means nodes will appear as if they are functions and all properties will be private (but still there and subscribable on trees!). This can help you make your node trees look more functional and call operators like `node(1)`. ### Graph Options diff --git a/docs/graphex.png b/docs/assets/graphex.png similarity index 100% rename from docs/graphex.png rename to docs/assets/graphex.png diff --git a/gs_logo_min.png b/docs/assets/gs_logo_min.png similarity index 100% rename from gs_logo_min.png rename to docs/assets/gs_logo_min.png diff --git a/docs/services/cmd/cmd.service.md b/docs/services/cmd/cmd.service.md index add66f63..7717b34e 100644 --- a/docs/services/cmd/cmd.service.md +++ b/docs/services/cmd/cmd.service.md @@ -34,10 +34,10 @@ type CMDInfo = { import { CMDService } from "./CMD.node"; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; const service = new CMDService({ - routes:[remoteGraphRoutes] + routes:[unsafeRoutes] }); //now we can send/receive messages console.log("Child process listening...") @@ -51,10 +51,10 @@ Then create childprocess.js in your root (for this example) ```ts import { CMDService } from "./CMD.node"; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; const service = new CMDService({ - routes:[remoteGraphRoutes] + routes:[unsafeRoutes] }); //now we can send/receive messages console.log("Child process listening...") diff --git a/docs/services/http/http.browser.md b/docs/services/http/http.browser.md index 31be4ff7..14a34698 100644 --- a/docs/services/http/http.browser.md +++ b/docs/services/http/http.browser.md @@ -16,8 +16,4 @@ http.listen() ``` -You can listen to specific paths independently and customize the fetch responses using cloned responses (so normal page flow is not disturbed). - -To call a node on the HTTPbackend, you can specify any url e.g. `https://localhost:8080/ping` and a method e.g. GET, POST, or any arbitrary method with inputs in the body. This will return results or if a string template is specified on a GET request then it will return a page response to you. You can easily specify site redirects this way, too, or specify as many different custom methods on a single URL as you want. - -Pretty cool! Lots of untapped potential here. +You can listen to specific paths independently and customize the fetch responses using cloned responses (so normal page flow is not disturbed). \ No newline at end of file diff --git a/docs/services/http/http.node.md b/docs/services/http/http.node.md index 32efa9c5..20f9c248 100644 --- a/docs/services/http/http.node.md +++ b/docs/services/http/http.node.md @@ -2,8 +2,6 @@ The HTTPbackend service puts the power of graphs and services into a full featured HTTP or HTTPS server. This lets you serve static assets or dynamic content straight from routes all through standard or customizable http fetch calls. This means you can implement your entire own http protocols and state machines willy nilly and feel like a backend master, it's a lot of fun! -To call a node on the HTTPbackend, you can specify any url e.g. https://localhost:8080/ping and a method e.g. GET, POST, or any arbitrary method with inputs in the body. This will return results or if a string template is specified on a GET request then it will return a page response to you. You can easily specify site redirects this way, too, or specify as many different custom methods on a single URL as you want. - See `examples/httpserver` to get started with a simple implementation. The extended `RouteProp` when declaring routes/nodes in Service.ts was made for this: @@ -108,10 +106,8 @@ http.setupServer( Easy! -The page specification lets you quickly set up static and dynamic page behaviors, if you pass an object then the routes are interpreted as node definitions which you can make as complicated as you want to run graph trees. Then a REST API can make any common or custom HTTP requests with any jsonifiable inputs in the request body. - -If a node's .get/.template string returns a findable file path or remote url, it will see if it can load the file on the server. This is a nice way for dynamic file routing. +The page specification lets you quickly set up static and dynamic page behaviors, if you pass an object then the routes are interpreted as node definitions which you can make as complicated as you want to run graph trees. -Later we need to implement security features but you can easily add custom features into the onrequest functions in each URL, e.g. to require passwords in the request body. +If a node's .get/.template returns a file path it will see if it can load the file on the server, just a nice way for dynamic file routing. -From here we can apply websocket, sse, and other services to build efficient web servers. See `examples/httpserver` for a quick implementation +From here we can apply websocket, sse, and other services to build efficient web servers. See `examples/httpserver` for a quick implementation \ No newline at end of file diff --git a/docs/services/router/Router.md b/docs/services/router/Router.md index 636d73ff..12241468 100644 --- a/docs/services/router/Router.md +++ b/docs/services/router/Router.md @@ -109,34 +109,23 @@ router.addUser({_id:'me'},{socketId:'socket12345678'}) //which returns via promise: export type User = { //users have macros to call grouped connections generically, based on what's available _id:string, - - //work with an available connection, you can set the preferred order (e.g. sse, websockets, http) send:(...args:any[])=>any, request:(...args:any[])=>Promise|Promise[]|undefined, post:(...args:any[])=>void, run:(...args:any[])=>Promise|Promise[]|undefined, subscribe:(...args:any[])=>Promise|Promise[]|undefined, unsubscribe:(...args:any[])=>Promise|Promise[]|undefined, - - //work with all of the connections associated with a user - sendAll:(...args:any[])=>any, - requestAll:(...args:any[])=>Promise|Promise[]|undefined, - postAll:(...args:any[])=>void, - runAll:(...args:any[])=>Promise|Promise[]|undefined, - subscribeAll:(...args:any[])=>Promise|Promise[]|undefined, - unsubscribeAll:(...args:any[])=>Promise|Promise[]|undefined, - terminate:(...args:any[]) => boolean, onclose?:(user:User)=>void, [key:string]:any -} +} & Partial ``` The user's send/post/etc. handles will search available connections sourced to that user and use the best connection that has the available functionality based on matching methods. The services we have all follow the same straightforward, fully functional (including all of the source API features for each type of protocol still on-hand), and reproducible format for pooling and matching connections for easier high level integration and a fairly limited learning curve for the amount of features you can pack together in a few dozen lines. It's very performant, while you still have full control over your servers and services as you need deeper specifications. -All together now with sessions and mixed SSE + Websocket connections and a configurable http/https server... See backend.ts in `examples/advanced/webrtcrouter` +All together now with sessions and mixed SSE + Websocket connections and a configurable http/https server... See backend.ts in `examples/webrtcrouter` ```ts diff --git a/docs/services/worker/worker.md b/docs/services/worker/worker.md index fdd1278e..e911dd40 100644 --- a/docs/services/worker/worker.md +++ b/docs/services/worker/worker.md @@ -5,7 +5,7 @@ To use workers within our graph hierarchy, we need to establish a worker service e.g. worker.ts ```ts //functionality -import { WorkerService, workerCanvasRoutes, workerCanvasRoutes, remoteGraphRoutes, ECSService } from 'graphscript'; +import { WorkerService, workerCanvasRoutes, workerCanvasRoutes, unsafeRoutes, ECSService } from 'graphscript'; //wonder if we can have a scheme to dynamic import within the services? e.g. to bring in node-only or browser-only services without additional workers @@ -19,7 +19,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope } roots:{ ...workerCanvasRoutes, - ...remoteGraphRoutes //allows dynamic route loading + ...unsafeRoutes //allows dynamic route loading }, includeClassName:false }); @@ -35,4 +35,4 @@ This worker implements several useful services including a dedicated gpu.js inst Now you can post commands and subscribe to results easily, or chain threads via message ports easily (see worker.service.md). -Note the remoteGraphRoutes allow writing functions, properties, and classes to the thread from another thread. Use with caution! \ No newline at end of file +Note the unsafeRoutes allow writing functions, properties, and classes to the thread from another thread. Use with caution! \ No newline at end of file diff --git a/docs/services/worker/worker.service.md b/docs/services/worker/worker.service.md index 5e1a2675..49e933e5 100644 --- a/docs/services/worker/worker.service.md +++ b/docs/services/worker/worker.service.md @@ -83,7 +83,7 @@ let worker2 = workers.addWorker({url:worker}); const portId = workers.establishMessageChannel(worker1.worker,worker2.worker) -//if the remoteGraphRoutes are enabled on the worker you can quickly write in functions from the main thread +//if unsafeService is enabled on the worker you can quickly write in functions from the main thread workers.transferFunction( worker1, function add1(input) { @@ -203,7 +203,7 @@ Worker: ```ts import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, //GPUService } from 'graphscript'/////"../../GraphServiceRouter/index";//from 'graphscript' @@ -216,7 +216,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope roots:[ //GPUService as any, ...workerCanvasRoutes, - ...remoteGraphRoutes //allows dynamic route loading + ...unsafeRoutes //allows dynamic route loading ], includeClassName:false }); @@ -471,7 +471,7 @@ And to set up the worker, we add an intermediate function to the worker's `setup import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, ECSService, Systems @@ -494,7 +494,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope routes:[ //GPUService, ECSService, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading { ...workerCanvasRoutes, receiveThreeCanvas:function(options:WorkerCanvasReceiveProps){ //modified canvas receiver that installs desired threejs modules diff --git a/examples/advanced/audiofeedback/index.html b/examples/3dmodel/index.html similarity index 100% rename from examples/advanced/audiofeedback/index.html rename to examples/3dmodel/index.html diff --git a/examples/loaders/3dmodel/index.ts b/examples/3dmodel/index.ts similarity index 88% rename from examples/loaders/3dmodel/index.ts rename to examples/3dmodel/index.ts index 2f0481c5..5aed8362 100644 --- a/examples/loaders/3dmodel/index.ts +++ b/examples/3dmodel/index.ts @@ -1,5 +1,5 @@ import * as B from 'babylonjs' -import { Graph, htmlloader } from '../../../index'; +import { Graph, htmlloader } from '../../build/main/index'; let canvas = document.createElement('canvas'); @@ -28,6 +28,7 @@ let model = { __props:scene }, + // Good camera: { __props:camera, __transition:{ @@ -82,26 +83,32 @@ let model = { } } -let modelLoader = (node, parent, graph) => { +let modelLoader = (node) => { + + const parent = node.__parent if(node.__props instanceof B.Mesh) { if(parent.__props instanceof B.Mesh) { + if(parent.position) { - node.__localPosition = (node.position as B.Vector3).clone(); + node.localPosition = (node.position as B.Vector3).clone(); node.position = (node.position as B.Vector3).add(parent.position); } if(parent.rotation) { - node.__localRotation = (node.rotation as B.Vector3).clone(); + node.localRotation = (node.rotation as B.Vector3).clone(); node.rotation = (node.rotation as B.Vector3).add(parent.rotation); } - - let __listeners = { - [parent.__node.tag+'.position']:function(newP) {node.position = (node.__localPosition as B.Vector3).add(newP);}, - [parent.__node.tag+'.rotation']:function(newR) {node.rotation = (node.__localRotation as B.Vector3).add(newR);}, - - }; - if(node.__listeners) Object.assign(node.__listeners,__listeners); - else node.__listeners = __listeners; + const root = node.__node; + root.listeners.set({ + [node.__node.tag]:{ + [parent.__node.tag+'.position']:function(newP) { + node.position = (node.localPosition as B.Vector3).add(newP); + }, + [parent.__node.tag+'.rotation']:function(newR) { + node.rotation = (node.localRotation as B.Vector3).add(newR); + }, + } + }); } } } @@ -117,20 +124,25 @@ type __transition = { } //very rudimentary camera tracking example. Better would be spring movement and better timing to remove judder at end of transition -let cameraLoader = (node, parent, graph) => { +let cameraLoader = (node) => { + const parent = node.__parent let animating = true; - if(!node.__props && parent.__props instanceof B.FreeCamera) {node.__props = parent.__props; node.__proxyObject(node.__props); } + if(!node.__props && parent.__props instanceof B.FreeCamera) node.__props = parent.__props; if(node.__props instanceof B.FreeCamera) { if(node.__transition) { - node.__setOperator(()=>{ + + node.__operator = ()=> { + let lastTime = performance.now()*0.001; let startTime = lastTime; let startPos = (node.position as B.Vector3).clone(); let startRot = (node.rotation as B.Vector3).clone(); + if(node.__transition.position && !(node.__transition.position instanceof B.Vector3)) node.__transition.position = new B.Vector3(node.__transition.position.x,node.__transition.position.y,node.__transition.position.z); if(node.__transition.rotation && !(node.__transition.rotation instanceof B.Vector3)) node.__transition.rotation = new B.Vector3(node.__transition.rotation.x,node.__transition.rotation.y,node.__transition.rotation.z); let transition = async () => { + if(animating === false) return undefined; //aborts else if (lastTime - startTime >= node.__transition.duration) { if(node.__transition.position) { @@ -156,6 +168,7 @@ let cameraLoader = (node, parent, graph) => { } } else { + if(node.__transition.rotation) { let newRot = startRot.add((node.__transition.rotation as B.Vector3).subtract(startRot).scale(dT)) if(node.__transition.rinterp) newRot = node.__transition.rinterp(newRot,node.rotation,currTime,startTime); @@ -178,7 +191,7 @@ let cameraLoader = (node, parent, graph) => { if(node.__transition.delay) { return new Promise ((res) => {setTimeout(async()=>{ res(await transition()); }, node.__transition.delay);}); } else return new Promise (async (res) => {res(await transition()); }); - }); + } } } @@ -197,10 +210,11 @@ let graph = new Graph({ } }); +console.log('graph', graph) + engine.runRenderLoop(function(){ scene.render(); graph.get('snowman').position = new B.Vector3(0, Math.sin(performance.now()*0.001)*5, 0); - }); // the canvas/window resize event handler window.addEventListener('resize', function(){ @@ -210,4 +224,5 @@ window.addEventListener('resize', function(){ setTimeout(()=>{ engine.resize(); graph.run('camera'); + },0.1) diff --git a/examples/loaders/3dmodel/package-lock.json b/examples/3dmodel/package-lock.json similarity index 97% rename from examples/loaders/3dmodel/package-lock.json rename to examples/3dmodel/package-lock.json index e3132522..9e6994c0 100644 --- a/examples/loaders/3dmodel/package-lock.json +++ b/examples/3dmodel/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp5631", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "babylonjs": "^5.34.0", "web-worker": "^1.2.0" diff --git a/examples/loaders/3dmodel/package.json b/examples/3dmodel/package.json similarity index 94% rename from examples/loaders/3dmodel/package.json rename to examples/3dmodel/package.json index 880ac2df..2845d601 100644 --- a/examples/loaders/3dmodel/package.json +++ b/examples/3dmodel/package.json @@ -20,9 +20,9 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "babylonjs": "^5.34.0", + "babylonjs": "^5.39.0", "web-worker": "^1.2.0" }, "nodemonConfig": { diff --git a/examples/editing/tinybuild.config.js b/examples/3dmodel/tinybuild.config.js similarity index 95% rename from examples/editing/tinybuild.config.js rename to examples/3dmodel/tinybuild.config.js index 1f475b48..6a131f9b 100644 --- a/examples/editing/tinybuild.config.js +++ b/examples/3dmodel/tinybuild.config.js @@ -1,7 +1,7 @@ const config = { bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" + "index.ts" ], outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags //outdir:[] //exit point files, define for multiple bundle files @@ -20,10 +20,10 @@ const config = { debug: false, protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 + port: 8081, //e.g. port 80, 443, 8000 startpage: "index.html", //home page socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 2020, //hotreload websocket server port + hotreload: 5001, //hotreload websocket server port //watch: ['../'], //watch additional directories other than the current working directory pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) python: false,//7000, //quart server port (configured via the python server script file still) diff --git a/examples/advanced/webrtc/.gitignore b/examples/advanced/webrtc/.gitignore deleted file mode 100644 index ac756779..00000000 --- a/examples/advanced/webrtc/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ - -dist -**/node_modules/** -**/*.pem -**/*.pfxs -**/*.key -**/*.lock -**/package-lock.json -**/*.key -**/*.log diff --git a/examples/advanced/webrtc/backend/package.json b/examples/advanced/webrtc/backend/package.json deleted file mode 100644 index 0e734865..00000000 --- a/examples/advanced/webrtc/backend/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "tinybuildapp1477", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "type": "module", - "scripts": { - "start": "tinybuild && node dist/server.js", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \"npm run python\" \"npm start\"", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "", - "dependencies": {}, - "devDependencies": {}, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} \ No newline at end of file diff --git a/examples/advanced/webrtc/backend/server.ts b/examples/advanced/webrtc/backend/server.ts deleted file mode 100644 index 0030ad35..00000000 --- a/examples/advanced/webrtc/backend/server.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { Router, HTTPbackend, WSSbackend, ServerProps, SSEbackend, SessionsService, SocketServerProps, SSEProps, User, OneWaySessionProps, SharedSessionProps } from '../../../../index.node' - - -const router = new Router({ - graph:{ - sessions:SessionsService, - wss:WSSbackend, - sse:SSEbackend, - http: { - service: HTTPbackend, - config:{ - protocol:'http', - host:'localhost', - port:8081, - pages:{ - '/':{ - template:'./index.html' - } - }, - onopen:(served) => { - router.openConnection( - 'wss', - { - server:served.server, - host:served.host, - port:8081, - path:'wss', - onconnection:(ws,req,serverinfo,id)=>{ - ws.send('Hello from WSS!'); - } - } as SocketServerProps - ) - - router.openConnection( - 'wss', - { - server:served.server, - host:served.host, - port:7000, - path:'hotreload', - onconnection:(ws)=>{ - ws.send('Hot reload port opened!'); - } - } as SocketServerProps - ) - - router.openConnection( - 'sse', - { - server:served.server, - path:'sse', - channels:['test'], - onconnection:(session,sseinfo,id,req,res)=>{ - console.log('pushing sse!') - session.push('Hello from SSE!'); - sseinfo.channels.forEach( - (c:string) => sseinfo.channel.broadcast( - 'SSE connection at '+req.headers.host+'/'+req.url, c - ) - ); - } - } as SSEProps - ) - } - } as ServerProps - } - } -}); - - - -router.addUser({ - _id:'admin' -}); - -let session = (router.services.sessions as SessionsService).openSharedSession( - { - _id:'webrtcrooms', - settings:{ - name:'webrtcrooms', - propnames:{ - rooms:true //if these props are updated on the user object we'll return them - }, - onopen:(session)=>{ - console.log("Session Started:",session); - }, - onhasupdate:(session, update)=>{ - console.log("Session Has Update:", update, session); - }, - onclose:(session)=>{ - console.log("Session closed!", session); - } - } - }, - 'admin' -); - -//fires when a session in the loop has an update -function sessionHasUpdate ( - session:OneWaySessionProps|SharedSessionProps, - update:{shared?:any,oneWay?:any} -){ - console.log("Session Update:",session,update); -} - -router.run('sessionLoop',sessionHasUpdate); - -//add users to a global session -router.subscribe('addUser', (user:User) => { - console.log('new user!', user._id); - if(typeof user === 'object') { - let joined = (router.services.sessions as SessionsService).joinSession('webrtcrooms', user._id, undefined, true); - } -}); \ No newline at end of file diff --git a/examples/advanced/webrtc/backend/tinybuild.config.js b/examples/advanced/webrtc/backend/tinybuild.config.js deleted file mode 100644 index 7811957e..00000000 --- a/examples/advanced/webrtc/backend/tinybuild.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "server.ts" - ], - outfile: "dist/server", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:'dist' //exit point folder, define for multiple entryPoints - bundleBrowser: false, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files // { platform:'node' } //etc you can also supply an object here to add more specific esbuild settings - bundleTypes: false, //create .d.ts files, //you need a .tsconfig for this to work - bundleNode: true, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - //bundleIIFE:false, //create an iife build, this is compiled temporarily to create the types files and only saved with bundleIIFE:true - //bundleCommonJS:false, //cjs format outputted as .cjs - minify: true, - sourcemap: false, - //plugins:{} //custom esbuild plugins? e.g. esbuild-sass-plugin for scss support - //includeDefaultPlugins:true //true by default, includes the presets for the streaming imports, worker bundling, and auto npm install - //blobWorkers:true, //package workers as blobs or files? blobs are faster but inflate the main package size - //workerBundler:{minifyWhitespace:true} //bundler settings specific to the worker. e.g. apply platform:'node' when bundling node workers, - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } - // outputs:{ //overwrites main config settings for specific use cases - // node:{ //e.g. for bundleNode - // // external:[] //externals for node environment builds - // }, - // //commonjs:{} //bundleCommonJS - // //browser:{} - // //esm:{} - // iife:{ - // // external:[] //we only use the iife for types so it doesn't really matter if it bundles node, just note otherwise if you need iife for some obscure reason - // } - // }, - - //refer to esbuild docs for more settings - }, - server: false// { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - // debug: false, - // protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - // host: "localhost", //'localhost' or '127.0.0.1' etc. - // port: 8080, //e.g. port 80, 443, 8000 - // //redirect: 'http://localhost:8082' //instead of serving the default content, redirect ot another url e.g. another server - // startpage: "index.html", //home page - // socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - // hotreload: 5000, //hotreload websocket server port - // reloadscripts: false, //hot swap scripts, can break things if script handles initializations, otherwise css, link, srcs all hot swap without page reloading fairly intelligently - // //delay: 50, //millisecond delay on the watch command for hot reloading - // //pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - // //watch: ['../'], //watch additional directories other than the current working directory - // python: false,//7000, //quart server port (configured via the python server script file still) - // python_node:7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - // errpage: 'node_modules/tinybuild/tinybuild/node_server/other/404.html', //default error page, etc. - // certpath:'node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem',//if using https, this is required. See cert.pfx.md for instructions - // keypath:'node_modules/tinybuild/tinybuild/node_server/ssl/key.pem'//if using https, this is required. See cert.pfx.md for instructions - // } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.css b/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.css deleted file mode 100644 index 79393f29..00000000 --- a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.css +++ /dev/null @@ -1,78 +0,0 @@ -body { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - height: 100vh; - margin: 0; - background-color: #f7f7f7; - font-family: Arial, sans-serif; -} - -.container { - width: 100%; - max-width: 800px; - padding: 20px; - box-sizing: border-box; - background-color: white; - border-radius: 10px; - box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); -} - -.canvas-container { - overflow: hidden; -} - -.canvas-container canvas { - border:1px solid black; - width:99%; -} - -.controls { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 10px; - margin-bottom: 20px; -} - -.input-group { - display: flex; - align-items: center; - gap: 5px; -} - -#toggle-mode-button, -#clear-button, -#recenter-button { - background-color: #4caf50; - border: none; - color: white; - padding: 10px 20px; - text-align: center; - text-decoration: none; - font-size: 16px; - cursor: pointer; - border-radius: 5px; - transition: background-color 0.3s ease; -} - -#toggle-mode-button:hover, -#clear-button:hover, -#recenter-button:hover { - background-color: #45a049; -} - -.controls input[type="number"] { - width: 50px; - padding: 8px; - border-radius: 5px; - border: 1px solid #ccc; -} - -.controls input[type="color"] { - width: 40px; - height: 40px; - border-radius: 50%; - border: none; -} diff --git a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.html b/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.html deleted file mode 100644 index 1cc31778..00000000 --- a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.html +++ /dev/null @@ -1,20 +0,0 @@ -
-
- - - -
- - -
- - -
- - -
-
-
- -
-
\ No newline at end of file diff --git a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.js b/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.js deleted file mode 100644 index fe6be80a..00000000 --- a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.js +++ /dev/null @@ -1,333 +0,0 @@ -// import css from "./CanvasWithControls.css" //uncomment if using bundler and comment out the fetch operations -// import html from "./CanvasWithControls.html" - -let css, html; //comment out if importing above - -export class CanvasWithControls extends HTMLElement { - - ondraw; - - constructor() { - super(); - - this.canvasWidth = 800; - this.canvasHeight = 600; - this.lineWidth = 5; - - this.attachShadow({ mode: "open" }); - - } - - static get observedAttributes() { - return ['width', 'height','controls']; - } - - attributeChangedCallback(name, oldValue, newValue) { - if (name === 'width') { - this.canvasWidth = parseInt(newValue); - if(this.canvas) { - this.canvas.width = this.canvasWidth; - this.ctx.lineWidth = this.lineWidth; - } - } else if (name === 'height') { - this.canvasHeight = parseInt(newValue); - if(this.canvas) - { - this.canvas.height = this.canvasHeight; - this.ctx.lineWidth = this.lineWidth; - } - } else if(name === 'controls') { - if(newValue && newValue !== 'false') { - this.shadowRoot.getElementById('controls-container').style.display = ''; - } else { - this.shadowRoot.getElementById('controls-container').style.display = 'none'; - } - } - } - - // Additional methods or event handlers can be defined here - setup = async () => { - if(this.fetch) await this.fetch; - - this.canvas = this.shadowRoot.getElementById("canvas"); - this.ctx = this.canvas.getContext("2d"); - const canvas = this.canvas; - const ctx = this.ctx; - - const maxScale = 5; - // Set initial canvas width and height - canvas.width = this.canvasWidth; - canvas.height = this.canvasHeight; - - let cursorStyle = 'crosshair'; - - canvas.style.cursor = cursorStyle; - - let color = "#000000"; - // Initialize canvas properties - ctx.strokeStyle = "#000000"; - this.ctx.lineWidth = this.lineWidth; - - // Your existing event listeners can be added here - const colorPicker = this.shadowRoot.getElementById("color-picker"); - colorPicker.addEventListener("input", (event) => { - color = event.target.value; - this.ctx.strokeStyle = event.target.value; - }); - - - const clearButton = this.shadowRoot.getElementById("clear-button"); - clearButton.addEventListener("click", () => { - ctx.clearRect(0, 0, canvas.width, canvas.height); - }); - - const zoomRange = this.shadowRoot.getElementById("zoom-range"); - zoomRange.addEventListener("input", (event) => { - const scale = parseFloat(event.target.value); - canvas.style.transform = `scale(${scale})`; - }); - - let isDrawing = false; - let lastX = 0; - let lastY = 0; - - let isPanning = false; - let scale = 1; // Initialize the scale factor - let translateX = 0; // Initialize the horizontal translation - let translateY = 0; // Initialize the vertical translation - let initialX = 0; // Store initial X coordinate for panning - let initialY = 0; // Store initial Y coordinate for panning - - let recenter = false; - - let onzoomEvent = (event) => { - const rect = canvas.getBoundingClientRect(); - let newScale, offsetXBefore, offsetXAfter, offsetYBefore, offsetYAfter; - - // Calculate the new scale value based on the scroll direction - if(event) { - const delta = event.deltaY > 0 ? -0.1 : 0.1; - newScale = Math.min(Math.max(0.1, scale + delta), maxScale); - } - - if(!event || recenter || newScale < 1) { - newScale = 1; - translateX = 0; - translateY = 0; - offsetXBefore = 0; - offsetYBefore = 0; - offsetXAfter = 0; - offsetYAfter = 0; - recenter = false; - } else { - // Calculate the mouse position relative to the canvas before scaling - offsetXBefore = (event.clientX - rect.left) / scale - translateX; - offsetYBefore = (event.clientY - rect.top) / scale - translateY; - - // Calculate the mouse position relative to the canvas after scaling - offsetXAfter = (event.clientX - rect.left) / newScale - translateX; - offsetYAfter = (event.clientY - rect.top) / newScale - translateY; - } - // Adjust the translation to maintain the zooming point - translateX += offsetXBefore - offsetXAfter; - translateY += offsetYBefore - offsetYAfter; - - // Apply the new transform with both scale and translation - canvas.style.transform = `translate(${translateX}px, ${translateY}px) scale(${newScale})`; - - // Update the scale variable for future calculations - scale = newScale; - zoomRange.value = newScale; - } - - - const recenterButton = this.shadowRoot.getElementById("recenter-button"); - recenterButton.addEventListener("click", () => { - recenter = true; - onzoomEvent(); - }); - - - canvas.parentElement.addEventListener("wheel", (event) => { - event.preventDefault(); - onzoomEvent(event); - }); - - canvas.addEventListener("mousedown", (event) => { - // Check if the middle mouse button is pressed or the Alt key is held down - if (event.button === 1 || event.altKey) { - canvas.style.cursor = "move"; - } else { - [lastX, lastY] = [event.offsetX * (this.canvasWidth / canvas.clientWidth), event.offsetY * (this.canvasHeight / canvas.clientHeight)]; - } - }); - - let drawPixel = (event) => { - const x = event.offsetX * (this.canvasWidth / canvas.clientWidth); - const y = event.offsetY * (this.canvasHeight / canvas.clientHeight); - ctx.fillRect( - x - this.lineWidth / 2, - y - this.lineWidth / 2, - this.lineWidth, - this.lineWidth - ); - if(this.ondraw) { - this.ondraw({x,y,color,isLineDrawingMode,lineWidth}); - } - }; - - canvas.parentElement.addEventListener("mousedown", (event) => { - // Check if the middle mouse button is pressed or the Alt key is held down - if (event.button === 1 || event.altKey) { - isPanning = true; - initialX = event.clientX - translateX; - initialY = event.clientY - translateY; - canvas.parentElement.style.cursor = "move"; - } else { - isDrawing = true; - if (isLineDrawingMode) { //need to move to trigger lines - ctx.strokeStyle = color; - } else { - // Pixel drawing mode - ctx.fillStyle = color; // Set fill style to the selected color - //thrice because it grays out on first draw for some reason - drawPixel(event); - drawPixel(event); - drawPixel(event); - } - } - - - }); - - let draw = (event) => { - if (isLineDrawingMode) { - ctx.lineCap = "round"; - ctx.beginPath(); - ctx.moveTo( - typeof lastX === 'number' ? lastX : event.offsetX * (this.canvasWidth / canvas.clientWidth), - typeof lastY === 'number' ? lastY : event.offsetY * (this.canvasHeight / canvas.clientHeight) - ); - const x = event.offsetX * (this.canvasWidth / canvas.clientWidth); - const y = event.offsetY * (this.canvasHeight / canvas.clientHeight); - ctx.lineTo(x, y); - ctx.stroke(); - if(this.ondraw) { - this.ondraw({x,y,lastX,lastY,color,isLineDrawingMode,lineWidth}) - } - [lastX, lastY] = [x, y]; - } else { - // Pixel drawing mode - ctx.fillStyle = color; - drawPixel(event); - } - } - - canvas.addEventListener("mousemove", (event) => { - if (isDrawing) { - draw(event); - } - }); - - canvas.parentElement.addEventListener("mousemove", (event) => { - if (isPanning) { - if (event.clientX - initialX !== 0 || event.clientY - initialY !== 0) { - translateX = event.clientX - initialX; - translateY = event.clientY - initialY; - canvas.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`; - } - } - }); - - - canvas.addEventListener("mouseup", () => { - isDrawing = false; - lastX = undefined; lastY = undefined; - canvas.style.cursor = cursorStyle; - }); - - canvas.addEventListener("mouseout", () => { - isDrawing = false; - }); - - canvas.parentElement.addEventListener("mouseup", () => { - isPanning = false; - canvas.parentElement.style.cursor = "default"; - }); - - canvas.parentElement.addEventListener("mouseout", () => { - isPanning = false; - }); - - - let isLineDrawingMode = true; // Flag for line drawing mode - let lineWidthLabel = this.shadowRoot.getElementById('line-label'); - let lineWidthInput = this.shadowRoot.getElementById("line-width"); // Line width input element - - // Event listener for the line mode toggle button - const toggleModeButton = this.shadowRoot.getElementById("toggle-mode-button"); - toggleModeButton.addEventListener("click", () => { - isLineDrawingMode = !isLineDrawingMode; // Toggle line drawing mode - if (isLineDrawingMode) { - toggleModeButton.innerHTML = "Line Mode"; - lineWidthLabel.innerHTML = "Line Width:"; - cursorStyle = "crosshair"; // Set cursor to crosshair in line drawing mode - } else { - toggleModeButton.innerHTML = "Pixel Mode"; - lineWidthLabel.innerHTML = "Pixel Size:"; - cursorStyle = "default"; // Set cursor to default in pixel drawing mode - } - canvas.style.cursor = cursorStyle; - }); - - // Event listener for line width input - lineWidthInput.addEventListener("input", (event) => { - this.lineWidth = parseInt(event.target.value); // Update line width based on user input - ctx.lineWidth = this.lineWidth; // Apply the new line width to the context - }); - - } - - connectedCallback() { - // Code to run when the element is added to the DOM - - //Fetch HTML and CSS files asynchronously (comment out if bundling html and css instead) - if(!css || !html) { - this.fetch = Promise.all([ - fetch("CanvasWithControls.html").then(response => response.text()), - fetch("CanvasWithControls.css").then(response => response.text()) - ]).then(([h, c]) => { - html = h; css = c; //should only fetch once - this.shadowRoot.innerHTML = ` - - ${html} - `; - - // Your component's logic and event listeners here - // ... - }).catch(error => { - console.error("Error fetching resources:", error); - }); - - } else { - this.shadowRoot.innerHTML = ` - - ${html} - `; - } - - this.setup(); - } - - disconnectedCallback() { - // Code to run when the element is removed from the DOM - } - - // Define other lifecycle callbacks and methods as needed -} - -customElements.define("canvas-with-controls", CanvasWithControls); \ No newline at end of file diff --git a/examples/advanced/webrtc/components/chatdraw.html b/examples/advanced/webrtc/components/chatdraw.html deleted file mode 100644 index 725b653e..00000000 --- a/examples/advanced/webrtc/components/chatdraw.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` - - - - - - - - - - - - - - - `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var Math2=class _Math2{constructor(){}static TWO_PI=Math.PI*2;static C=299792458;static G=66743e-15;static h=662607015e-42;static R=8314.32;static Ra=287;static H=69.3;static kbar=1054571817e-43;static kB=1380649e-29;static ke=89875517923e-1;static me=91093837015e-41;static mp=167262192369e-38;static mn=167492749804e-38;static P0=101325;static T0=288.15;static p0=1.225;static Na=60220978e16;static y=1.405;static M0=28.96643;static g0=9.80665;static Re=6378100;static B=1458e-9;static S=110.4;static Sigma=365e-12;static imgkernels={edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]};static HSLToRGB=(h,s,l,scalar=255)=>{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x22=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x22;b=0}else if(60<=h&&h<120){r=x22;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x22}else if(180<=h&&h<240){r=0;g=x22;b=c}else if(240<=h&&h<300){r=x22;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x22}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v2=>v2===a).length-arr.filter(v2=>v2===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean=void 0)=>{let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d2=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean=this.mean(arr);let std=this.std(arr,mean);let z=new Array(arr.length);for(let i=0;ia+(b-mean)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean=this.mean(arr);let std=this.std(arr,mean);return populationMean?std/populationMean:std/mean};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y2)=>acc+Math.pow(y2-meanY,2),0);const ssResidual=observed.reduce((acc,y2,i)=>acc+Math.pow(y2-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p2)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p2*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x22)=>sum+x22,0);const sumY=yCoords.reduce((sum,y2)=>sum+y2,0);const sumXY=xCoords.reduce((sum,x22,i)=>sum+x22*yCoords[i],0);const sumX2=xCoords.reduce((sum,x22)=>sum+x22*x22,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{return vec.map((v2,i)=>v2-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v2,i)=>v2/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x22,y2,z)=>{var r=Math.sqrt(x22*x22+y2*y2+z*z);var theta=Math.atan2(y2,x22);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v2=>(v2-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x22=>{return Math.pow(x22,5)+x22*x22-x22-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y2=x22;return y2},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x22+y2;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w2=x22+y2+z;return w2},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x22;return y2},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x22=Math.cos(t);return x22},yFunc=t=>{let y2=Math.sin(t);return y2},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u2,v2)=>u2,yFunc=(u2,v2)=>v2,zFunc=(u2,v2)=>u2+v2,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u2=rangeU[0];u2{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v2,i,x22,y2)=>{return v2+x22+y2})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v2}, idx:${idx}, x:${i},y:${j}`);return v2+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x22,y2)=>{return[x22*10,y2*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value,index)=>{const row=Array(values.length).fill(0);row[index]=value;return row})};static householderMatrix=v2=>{const size=v2.length;const vvT=v2.map(rowVal=>v2.map(colVal=>rowVal*colVal));const vTv=this.normalize(v2)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A2,B)=>{return A2.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix22*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value=>(value-min)/(max-min))};static garroteThreshold=(data,value)=>{return data.map(x22=>{if(Math.abs(x22)<=value){return 0}else{return x22-value*value/x22}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean1=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v2,i)=>(v2-mean1)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x22,x22),this.cov1d(x22,y2),this.cov1d(x22,z)],[this.cov1d(y2,x22),this.cov1d(y2,y2),this.cov1d(y2,z)],[this.cov1d(z,x22),this.cov1d(z,y2),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v2=>v2-mean)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N2=signalA.length;const M2=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N2=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N2;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x22=arr.filter((element,index)=>{return index%factor===0});return x22};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y2=>y2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x22)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A2,numIter=100)=>{let b=Array(A2.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A2[0].length>A2.length){A2=this.transpose(A2)}const m=A2.length;const n=A2[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A2);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x22):this.normalize(x22);const u2=this.vecsub(x22,e);const normU=this.normalize(u2);const v2=u2.map(val=>val/normU);const Qk=this.householderMatrix(v2);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p2=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p2[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p2[0]=this.matscale(p2[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p2[0]),p2[0]));p2[0]=this.matscale(p2[0],1/p_length);let t_new=this.matmul(mat,p2[0]);let pp=this.matmul(this.transpose(p2[0]),p2[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{ax=ax*this.accelConstant;ay=ay*this.accelConstant;az=az*this.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+this.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+this.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v2,i)=>{return apass(v2,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-this.lastGyroTime;this.lastGyroTime=timestamp;gx=gx*this.gyroConstant+this.gyroXError;gy=gy*this.gyroConstant+this.gyroYError;gz=gz*this.gyroConstant+this.gyroZError;this.gyroXAngle+=gx*elapsed;this.gyroYAngle+=gy*elapsed;this.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:this.gyroXAngle,pitch:this.gyroYAngle,yaw:this.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v2,i)=>{if(result){let r=gpass(v2,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v2,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(this.gyroXAngle||this.gyroYAngle||this.gyroZAngle){result.roll=result.roll*.04+this.gyroXAngle*.96;result.pitch=result.pitch*.04+this.gyroYAngle*.96;result.yaw=this.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-this.lastAccelTime;this.lastAccelTime=timestamp;this.px+=result2.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*.005555555555);this.py+=result2.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*.005555555555);this.pz+=result2.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*.005555555555);result2.px=this.px;result2.py=this.py;result2.pz=this.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{type;freq;sps;Q;dbGain;a0=0;a1=0;a2=0;b0=0;b1=0;b2=0;x1=0;x2=0;y1=0;y2=0;constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A2=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A2+A2);this[type](A2,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A2,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A2,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A2,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A2,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A2,sn,cs,alpha,beta){this.b0=1+alpha*A2;this.b1=-2*cs;this.b2=1-alpha*A2;this.a0=1+alpha/A2;this.a1=-2*cs;this.a2=1-alpha/A2}lowshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1-(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1-(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1+(A2+1)*cs+beta*sn;this.a1=2*(A2-1+(A2+1)*cs);this.a2=A2+1+(A2-1)*cs-beta*sn}highshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1+(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1+(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1-(A2+1)*cs-beta*sn;this.a1=2*(A2-1-(A2+1)*cs);this.a2=A2+1-(A2-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10,__onconnected:function(){if(!this.lowpass){let freq=this.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;this.lowpass=new Biquad("lowpass",this.maxFreq,this.sps);this.peakFinderWindow=Math.floor(this.sps/this.maxFreq);if(this.peakFinderWindow%2===0)this.peakFinderWindow+=1;if(this.peakFinderWindow<5)this.peakFinderWindow=5;this.midpoint=Math.round(this.peakFinderWindow*.5)}},__operator:function(data){if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*this.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){this.refdata.push(amplitude)}this.timestamp.push(timestamp);let beat;if(this.refdata.length>this.peakFinderWindow){this.refdata.shift();this.timestamp.shift()}this.smoothed.push(this.lowpass.applyFilter(this.refdata[this.refdata.length-1]));if(this.smoothed.length>this.peakFinderWindow){this.smoothed.shift()}if(this.smoothed.length===this.peakFinderWindow){if(Math2.isExtrema(this.smoothed,"valley")){this.valleys.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}else if(Math2.isExtrema(this.smoothed,"peak")){this.peaks.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}if(this.valleys.length>2&&this.peaks.length>2){if(this.valleys[this.valleys.length-1].timestamp1&&this.valley_distances.length>1){if(this.lastPeakthis.peak_distances[this.peak_distances.length-1].timestamp){let bpm,change=0;if(this.beats.length<1){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].distance+this.valley_distances[this.valley_distances.length-1].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-1].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].dt+this.valley_distances[this.valley_distances.length-1].dt));change=Math.abs(bpm-this.beats[this.beats.length-1].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-1].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-1].peak0-this.valley_distances[this.valley_distances.length-1].peak0,height1:this.peak_distances[this.peak_distances.length-1].peak1-this.valley_distances[this.valley_distances.length-1].peak1};this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}else{let bpm,change=0;if(this.beats.length<2){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-2].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance));change=Math.abs(bpm-this.beats[this.beats.length-2].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-2].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0,height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1};if(Array.isArray(beat.timestamp))beat.timestamp=beat.timestamp[0];this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}}}if(this.peaks.length>this.limit){this.peaks.shift()}if(this.valleys.length>this.limit){this.valleys.shift()}if(this.peak_distances.length>this.limit){this.peak_distances.shift()}if(this.valley_distances.length>this.limit){this.valley_distances.shift()}if(this.beats.length>this.limit){this.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)result=data.red.map((v2,i)=>{return pass(v2+data.ir[i],data.timestamp[i])}).filter(v2=>{if(v2)return true});else result=data.red.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}}};var blink_detect={sps:250,intervals:{},watch:["0"],tolerance:.2,__onconnected:node=>{node.watch.forEach(ch=>node.intervals[ch]={lowpass:new Biquad("lowpass",20,node.sps),filtered:[],averaged:[]})},__operator:function(data){let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=this.intervals[key].lowpass.applyFilter(n);this.intervals[key].filtered.push(next);this.intervals[key].averaged.push(next);if(this.intervals[key].filtered.length>checkCt){if(this.intervals[key].averaged.length>averageCt){this.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(this.intervals[key].averaged);if(Math.abs(Math.min(...this.intervals[key].filtered))>Math.abs(mean)+this.tolerance){this.intervals[key].filtered.length=0;passed=true;found[key]=true}}else this.intervals[key].filtered.shift()}};for(const key in this.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var ArrayManip=class _ArrayManip{static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,...newEntries.slice(newEntries.length-len))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d2={};data.forEach((arr,i)=>{d2[i]=arr});data=d2;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}static bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target};spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var rechk=/^([<>])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v2,o,c)=>String.fromCharCode(...new Uint8Array(v2.buffer,v2.byteOffset+o,c));var rts=(v2,o,c,s)=>new Uint8Array(v2.buffer,v2.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v2,o,c)=>str(v2,o+1,Math.min(v2.getUint8(o),c-1));var tsp=(v2,o,c,s)=>{v2.setUint8(o,s.length);rts(v2,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v2=>str(v2,o,1),p:(v2,c2)=>rts(v2,o,1,c2)})],"?":c=>[c,1,o=>({u:v2=>Boolean(v2.getUint8(o)),p:(v2,B)=>v2.setUint8(o,B)})],b:c=>[c,1,o=>({u:v2=>v2.getInt8(o),p:(v2,b)=>v2.setInt8(o,b)})],B:c=>[c,1,o=>({u:v2=>v2.getUint8(o),p:(v2,B)=>v2.setUint8(o,B)})],h:c=>[c,2,o=>({u:v2=>v2.getInt16(o,le),p:(v2,h)=>v2.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v2=>v2.getUint16(o,le),p:(v2,H)=>v2.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v2=>v2.getInt32(o,le),p:(v2,i)=>v2.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v2=>v2.getUint32(o,le),p:(v2,I)=>v2.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v2=>v2.getFloat32(o,le),p:(v2,f)=>v2.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v2=>v2.getFloat64(o,le),p:(v2,d2)=>v2.setFloat64(o,d2,le)})],s:c=>[1,c,o=>({u:v2=>str(v2,o,c),p:(v2,s)=>rts(v2,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v2=>pst(v2,o,c),p:(v2,s)=>tsp(v2,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var ByteParser=class _ByteParser extends ArrayManip{static codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x22){let int24=(255&x0)<<16|(255&x1)<<8|255&x22;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x22){return x0*65536+x1*256+x22}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x22,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x22)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x22,x3){return x0*16777216+x1*65536+x22*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M2=pattern.length;if(M2===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R2=256;var rightmost_positions=new Int32Array(R2);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v2=new DataView(arrb,offs|0);return fns.map(f=>f.u(v2))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v2,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var rms={sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{},__operator:function(data){this.watch.forEach(key=>{if(data[key]){if(!this.data[key]){if(Array.isArray(data[key])){this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0])}else this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key])}ByteParser.circularBuffer(this.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){this.rms.timestamp=data.timestamp[data.timestamp.length-1]}else this.rms.timestamp=data.timestamp}else this.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(this.watch.map(async key=>{if(this.data[key])this.rms[key]=Math.sqrt(Math.abs(this.data[key].reduce((p2,v2,i)=>p2+v2*v2)/this.data[key].length));else delete this.rms[key]}));res(this.rms)})}};var circularBuffer2d={bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false,__onconnected:function(node){for(const key in node.watch){node.data[key]=new Array(node.bufferSize).fill(0)}},__operator:function(data){let buffer2d=[];this.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(this.data[key],data[key]);buffer2d.push(this.data[key])}});return buffer2d}};var algorithms={beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d};algorithms["breath"].maxFreq=.2;export{StructBackend,StructFrontend,Systems,S as WebglLinePlotUtil,algorithms,defaultSpecifiers,genTimeSpecifiers,genTimestampFromString,getStringId,pseudoObjectId,randomId,setSignalControls,toObjectId,webglPlotRoutes}; diff --git a/src/extras/dist/index.services.js b/src/extras/dist/index.services.js deleted file mode 100644 index 1f46d0eb..00000000 --- a/src/extras/dist/index.services.js +++ /dev/null @@ -1,50 +0,0 @@ -(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x3=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x3,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x3)(function(x3){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x3+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_bson=__commonJS({"struct/datastructures/bson.cjs"(exports){"use strict";var BSON_MAJOR_VERSION=5;var BSON_INT32_MAX=2147483647;var BSON_INT32_MIN=-2147483648;var BSON_INT64_MAX=Math.pow(2,63)-1;var BSON_INT64_MIN=-Math.pow(2,63);var JS_INT_MAX=Math.pow(2,53);var JS_INT_MIN=-Math.pow(2,53);var BSON_DATA_NUMBER=1;var BSON_DATA_STRING=2;var BSON_DATA_OBJECT=3;var BSON_DATA_ARRAY=4;var BSON_DATA_BINARY=5;var BSON_DATA_UNDEFINED=6;var BSON_DATA_OID=7;var BSON_DATA_BOOLEAN=8;var BSON_DATA_DATE=9;var BSON_DATA_NULL=10;var BSON_DATA_REGEXP=11;var BSON_DATA_DBPOINTER=12;var BSON_DATA_CODE=13;var BSON_DATA_SYMBOL=14;var BSON_DATA_CODE_W_SCOPE=15;var BSON_DATA_INT=16;var BSON_DATA_TIMESTAMP=17;var BSON_DATA_LONG=18;var BSON_DATA_DECIMAL128=19;var BSON_DATA_MIN_KEY=255;var BSON_DATA_MAX_KEY=127;var BSON_BINARY_SUBTYPE_DEFAULT=0;var BSON_BINARY_SUBTYPE_UUID_NEW=4;var BSONType=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});var BSONError=class extends Error{get bsonError(){return true}get name(){return"BSONError"}constructor(message){super(message)}static isBSONError(value){return value!=null&&typeof value==="object"&&"bsonError"in value&&value.bsonError===true&&"name"in value&&"message"in value&&"stack"in value}};var BSONVersionError=class extends BSONError{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`)}};var BSONRuntimeError=class extends BSONError{get name(){return"BSONRuntimeError"}constructor(message){super(message)}};function nodejsMathRandomBytes(byteLength){return nodeJsByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var nodejsRandomBytes=(()=>{try{return __require("crypto").randomBytes}catch{return nodejsMathRandomBytes}})();var nodeJsByteUtils={toLocalBufferType(potentialBuffer){if(Buffer.isBuffer(potentialBuffer)){return potentialBuffer}if(ArrayBuffer.isView(potentialBuffer)){return Buffer.from(potentialBuffer.buffer,potentialBuffer.byteOffset,potentialBuffer.byteLength)}const stringTag=potentialBuffer?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialBuffer);if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return Buffer.from(potentialBuffer)}throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`)},allocate(size){return Buffer.alloc(size)},equals(a,b){return nodeJsByteUtils.toLocalBufferType(a).equals(b)},fromNumberArray(array){return Buffer.from(array)},fromBase64(base64){return Buffer.from(base64,"base64")},toBase64(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64")},fromISO88591(codePoints){return Buffer.from(codePoints,"binary")},toISO88591(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary")},fromHex(hex){return Buffer.from(hex,"hex")},toHex(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex")},fromUTF8(text){return Buffer.from(text,"utf8")},toUTF8(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8")},utf8ByteLength(input){return Buffer.byteLength(input,"utf8")},encodeUTF8Into(buffer2,source,byteOffset){return nodeJsByteUtils.toLocalBufferType(buffer2).write(source,byteOffset,void 0,"utf8")},randomBytes:nodejsRandomBytes};function isReactNative(){const{navigator}=globalThis;return typeof navigator==="object"&&navigator.product==="ReactNative"}function webMathRandomBytes(byteLength){if(byteLength<0){throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`)}return webByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var webRandomBytes=(()=>{const{crypto}=globalThis;if(crypto!=null&&typeof crypto.getRandomValues==="function"){return byteLength=>{return crypto.getRandomValues(webByteUtils.allocate(byteLength))}}else{if(isReactNative()){const{console:console2}=globalThis;console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return webMathRandomBytes}})();var HEX_DIGIT=/(\d|[a-f])/i;var webByteUtils={toLocalBufferType(potentialUint8array){const stringTag=potentialUint8array?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialUint8array);if(stringTag==="Uint8Array"){return potentialUint8array}if(ArrayBuffer.isView(potentialUint8array)){return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset,potentialUint8array.byteOffset+potentialUint8array.byteLength))}if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return new Uint8Array(potentialUint8array)}throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`)},allocate(size){if(typeof size!=="number"){throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`)}return new Uint8Array(size)},equals(a,b){if(a.byteLength!==b.byteLength){return false}for(let i=0;ic.charCodeAt(0))},toBase64(uint8array){return btoa(webByteUtils.toISO88591(uint8array))},fromISO88591(codePoints){return Uint8Array.from(codePoints,c=>c.charCodeAt(0)&255)},toISO88591(uint8array){return Array.from(Uint16Array.from(uint8array),b=>String.fromCharCode(b)).join("")},fromHex(hex){const evenLengthHex=hex.length%2===0?hex:hex.slice(0,hex.length-1);const buffer2=[];for(let i=0;ibyte.toString(16).padStart(2,"0")).join("")},fromUTF8(text){return new TextEncoder().encode(text)},toUTF8(uint8array){return new TextDecoder("utf8",{fatal:false}).decode(uint8array)},utf8ByteLength(input){return webByteUtils.fromUTF8(input).byteLength},encodeUTF8Into(buffer2,source,byteOffset){const bytes=webByteUtils.fromUTF8(source);buffer2.set(bytes,byteOffset);return bytes.byteLength},randomBytes:webRandomBytes};var hasGlobalBuffer=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==true;var ByteUtils=hasGlobalBuffer?nodeJsByteUtils:webByteUtils;var BSONDataView=class extends DataView{static fromUint8Array(input){return new DataView(input.buffer,input.byteOffset,input.byteLength)}};var VALIDATION_REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;var uuidValidateString=str2=>typeof str2==="string"&&VALIDATION_REGEX.test(str2);var uuidHexStringToBuffer=hexString=>{if(!uuidValidateString(hexString)){throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".')}const sanitizedHexString=hexString.replace(/-/g,"");return ByteUtils.fromHex(sanitizedHexString)};function bufferToUuidHexString(buffer2,includeDashes=true){if(includeDashes){return[ByteUtils.toHex(buffer2.subarray(0,4)),ByteUtils.toHex(buffer2.subarray(4,6)),ByteUtils.toHex(buffer2.subarray(6,8)),ByteUtils.toHex(buffer2.subarray(8,10)),ByteUtils.toHex(buffer2.subarray(10,16))].join("-")}return ByteUtils.toHex(buffer2)}function isAnyArrayBuffer(value){return["[object ArrayBuffer]","[object SharedArrayBuffer]"].includes(Object.prototype.toString.call(value))}function isUint8Array(value){return Object.prototype.toString.call(value)==="[object Uint8Array]"}function isRegExp(d2){return Object.prototype.toString.call(d2)==="[object RegExp]"}function isMap(d2){return Object.prototype.toString.call(d2)==="[object Map]"}function isDate(d2){return Object.prototype.toString.call(d2)==="[object Date]"}var BSONValue=class{get[Symbol.for("@@mdb.bson.version")](){return BSON_MAJOR_VERSION}};var Binary=class _Binary extends BSONValue{get _bsontype(){return"Binary"}constructor(buffer2,subType){super();if(!(buffer2==null)&&!(typeof buffer2==="string")&&!ArrayBuffer.isView(buffer2)&&!(buffer2 instanceof ArrayBuffer)&&!Array.isArray(buffer2)){throw new BSONError("Binary can only be constructed from string, Buffer, TypedArray, or Array")}this.sub_type=subType??_Binary.BSON_BINARY_SUBTYPE_DEFAULT;if(buffer2==null){this.buffer=ByteUtils.allocate(_Binary.BUFFER_SIZE);this.position=0}else{if(typeof buffer2==="string"){this.buffer=ByteUtils.fromISO88591(buffer2)}else if(Array.isArray(buffer2)){this.buffer=ByteUtils.fromNumberArray(buffer2)}else{this.buffer=ByteUtils.toLocalBufferType(buffer2)}this.position=this.buffer.byteLength}}put(byteValue){if(typeof byteValue==="string"&&byteValue.length!==1){throw new BSONError("only accepts single character String")}else if(typeof byteValue!=="number"&&byteValue.length!==1)throw new BSONError("only accepts single character Uint8Array or Array");let decodedByte;if(typeof byteValue==="string"){decodedByte=byteValue.charCodeAt(0)}else if(typeof byteValue==="number"){decodedByte=byteValue}else{decodedByte=byteValue[0]}if(decodedByte<0||decodedByte>255){throw new BSONError("only accepts number in a valid unsigned byte range 0-255")}if(this.buffer.byteLength>this.position){this.buffer[this.position++]=decodedByte}else{const newSpace=ByteUtils.allocate(_Binary.BUFFER_SIZE+this.buffer.length);newSpace.set(this.buffer,0);this.buffer=newSpace;this.buffer[this.position++]=decodedByte}}write(sequence,offset){offset=typeof offset==="number"?offset:this.position;if(this.buffer.byteLengththis.position?offset+sequence.length:this.position}else if(typeof sequence==="string"){const bytes=ByteUtils.fromISO88591(sequence);this.buffer.set(bytes,offset);this.position=offset+sequence.length>this.position?offset+sequence.length:this.position}}read(position,length){length=length&&length>0?length:this.position;return this.buffer.slice(position,position+length)}value(asRaw){asRaw=!!asRaw;if(asRaw&&this.buffer.length===this.position){return this.buffer}if(asRaw){return this.buffer.slice(0,this.position)}return ByteUtils.toISO88591(this.buffer.subarray(0,this.position))}length(){return this.position}toJSON(){return ByteUtils.toBase64(this.buffer)}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.buffer);if(encoding==="base64")return ByteUtils.toBase64(this.buffer);if(encoding==="utf8"||encoding==="utf-8")return ByteUtils.toUTF8(this.buffer);return ByteUtils.toUTF8(this.buffer)}toExtendedJSON(options){options=options||{};const base64String=ByteUtils.toBase64(this.buffer);const subType=Number(this.sub_type).toString(16);if(options.legacy){return{$binary:base64String,$type:subType.length===1?"0"+subType:subType}}return{$binary:{base64:base64String,subType:subType.length===1?"0"+subType:subType}}}toUUID(){if(this.sub_type===_Binary.SUBTYPE_UUID){return new UUID(this.buffer.slice(0,this.position))}throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`)}static fromExtendedJSON(doc,options){options=options||{};let data;let type;if("$binary"in doc){if(options.legacy&&typeof doc.$binary==="string"&&"$type"in doc){type=doc.$type?parseInt(doc.$type,16):0;data=ByteUtils.fromBase64(doc.$binary)}else{if(typeof doc.$binary!=="string"){type=doc.$binary.subType?parseInt(doc.$binary.subType,16):0;data=ByteUtils.fromBase64(doc.$binary.base64)}}}else if("$uuid"in doc){type=4;data=uuidHexStringToBuffer(doc.$uuid)}if(!data){throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`)}return type===BSON_BINARY_SUBTYPE_UUID_NEW?new UUID(data):new _Binary(data,type)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`}};Binary.BSON_BINARY_SUBTYPE_DEFAULT=0;Binary.BUFFER_SIZE=256;Binary.SUBTYPE_DEFAULT=0;Binary.SUBTYPE_FUNCTION=1;Binary.SUBTYPE_BYTE_ARRAY=2;Binary.SUBTYPE_UUID_OLD=3;Binary.SUBTYPE_UUID=4;Binary.SUBTYPE_MD5=5;Binary.SUBTYPE_ENCRYPTED=6;Binary.SUBTYPE_COLUMN=7;Binary.SUBTYPE_USER_DEFINED=128;var UUID_BYTE_LENGTH=16;var UUID=class _UUID extends Binary{constructor(input){let bytes;let hexStr;if(input==null){bytes=_UUID.generate()}else if(input instanceof _UUID){bytes=ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));hexStr=input.__id}else if(ArrayBuffer.isView(input)&&input.byteLength===UUID_BYTE_LENGTH){bytes=ByteUtils.toLocalBufferType(input)}else if(typeof input==="string"){bytes=uuidHexStringToBuffer(input)}else{throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).")}super(bytes,BSON_BINARY_SUBTYPE_UUID_NEW);this.__id=hexStr}get id(){return this.buffer}set id(value){this.buffer=value;if(_UUID.cacheHexString){this.__id=bufferToUuidHexString(value)}}toHexString(includeDashes=true){if(_UUID.cacheHexString&&this.__id){return this.__id}const uuidHexString=bufferToUuidHexString(this.id,includeDashes);if(_UUID.cacheHexString){this.__id=uuidHexString}return uuidHexString}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.id);if(encoding==="base64")return ByteUtils.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(!otherId){return false}if(otherId instanceof _UUID){return ByteUtils.equals(otherId.id,this.id)}try{return ByteUtils.equals(new _UUID(otherId).id,this.id)}catch{return false}}toBinary(){return new Binary(this.id,Binary.SUBTYPE_UUID)}static generate(){const bytes=ByteUtils.randomBytes(UUID_BYTE_LENGTH);bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return bytes}static isValid(input){if(!input){return false}if(input instanceof _UUID){return true}if(typeof input==="string"){return uuidValidateString(input)}if(isUint8Array(input)){if(input.byteLength!==UUID_BYTE_LENGTH){return false}return(input[6]&240)===64&&(input[8]&128)===128}return false}static createFromHexString(hexString){const buffer2=uuidHexStringToBuffer(hexString);return new _UUID(buffer2)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new UUID("${this.toHexString()}")`}};var Code=class _Code extends BSONValue{get _bsontype(){return"Code"}constructor(code,scope){super();this.code=code.toString();this.scope=scope??null}toJSON(){if(this.scope!=null){return{code:this.code,scope:this.scope}}return{code:this.code}}toExtendedJSON(){if(this.scope){return{$code:this.code,$scope:this.scope}}return{$code:this.code}}static fromExtendedJSON(doc){return new _Code(doc.$code,doc.$scope)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const codeJson=this.toJSON();return`new Code("${String(codeJson.code)}"${codeJson.scope!=null?`, ${JSON.stringify(codeJson.scope)}`:""})`}};function isDBRefLike(value){return value!=null&&typeof value==="object"&&"$id"in value&&value.$id!=null&&"$ref"in value&&typeof value.$ref==="string"&&(!("$db"in value)||"$db"in value&&typeof value.$db==="string")}var DBRef=class _DBRef extends BSONValue{get _bsontype(){return"DBRef"}constructor(collection,oid,db,fields){super();const parts=collection.split(".");if(parts.length===2){db=parts.shift();collection=parts.shift()}this.collection=collection;this.oid=oid;this.db=db;this.fields=fields||{}}get namespace(){return this.collection}set namespace(value){this.collection=value}toJSON(){const o=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)o.$db=this.db;return o}toExtendedJSON(options){options=options||{};let o={$ref:this.collection,$id:this.oid};if(options.legacy){return o}if(this.db)o.$db=this.db;o=Object.assign(o,this.fields);return o}static fromExtendedJSON(doc){const copy=Object.assign({},doc);delete copy.$ref;delete copy.$id;delete copy.$db;return new _DBRef(doc.$ref,doc.$id,doc.$db,copy)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const oid=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return`new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db?`, "${this.db}"`:""})`}};var wasm=void 0;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var TWO_PWR_16_DBL=1<<16;var TWO_PWR_24_DBL=1<<24;var TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL;var TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL;var TWO_PWR_63_DBL=TWO_PWR_64_DBL/2;var INT_CACHE={};var UINT_CACHE={};var MAX_INT64_STRING_LENGTH=20;var DECIMAL_REG_EX=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;var Long=class _Long extends BSONValue{get _bsontype(){return"Long"}get __isLong__(){return true}constructor(low=0,high,unsigned){super();if(typeof low==="bigint"){Object.assign(this,_Long.fromBigInt(low,!!high))}else if(typeof low==="string"){Object.assign(this,_Long.fromString(low,!!high))}else{this.low=low|0;this.high=high|0;this.unsigned=!!unsigned}}static fromBits(lowBits,highBits,unsigned){return new _Long(lowBits,highBits,unsigned)}static fromInt(value,unsigned){let obj,cachedObj,cache;if(unsigned){value>>>=0;if(cache=0<=value&&value<256){cachedObj=UINT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,(value|0)<0?-1:0,true);if(cache)UINT_CACHE[value]=obj;return obj}else{value|=0;if(cache=-128<=value&&value<128){cachedObj=INT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,value<0?-1:0,false);if(cache)INT_CACHE[value]=obj;return obj}}static fromNumber(value,unsigned){if(isNaN(value))return unsigned?_Long.UZERO:_Long.ZERO;if(unsigned){if(value<0)return _Long.UZERO;if(value>=TWO_PWR_64_DBL)return _Long.MAX_UNSIGNED_VALUE}else{if(value<=-TWO_PWR_63_DBL)return _Long.MIN_VALUE;if(value+1>=TWO_PWR_63_DBL)return _Long.MAX_VALUE}if(value<0)return _Long.fromNumber(-value,unsigned).neg();return _Long.fromBits(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0,unsigned)}static fromBigInt(value,unsigned){return _Long.fromString(value.toString(),unsigned)}static fromString(str2,unsigned,radix){if(str2.length===0)throw new BSONError("empty string");if(str2==="NaN"||str2==="Infinity"||str2==="+Infinity"||str2==="-Infinity")return _Long.ZERO;if(typeof unsigned==="number"){radix=unsigned,unsigned=false}else{unsigned=!!unsigned}radix=radix||10;if(radix<2||360)throw new BSONError("interior hyphen");else if(p2===0){return _Long.fromString(str2.substring(1),unsigned,radix).neg()}const radixToPower=_Long.fromNumber(Math.pow(radix,8));let result=_Long.ZERO;for(let i=0;i>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=addend.high>>>16;const b32=addend.high&65535;const b16=addend.low>>>16;const b00=addend.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}and(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low&other.low,this.high&other.high,this.unsigned)}compare(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.eq(other))return 0;const thisNeg=this.isNegative(),otherNeg=other.isNegative();if(thisNeg&&!otherNeg)return-1;if(!thisNeg&&otherNeg)return 1;if(!this.unsigned)return this.sub(other).isNegative()?-1:1;return other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}comp(other){return this.compare(other)}divide(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(divisor.isZero())throw new BSONError("division by zero");if(wasm){if(!this.unsigned&&this.high===-2147483648&&divisor.low===-1&&divisor.high===-1){return this}const low=(this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?_Long.UZERO:_Long.ZERO;let approx,rem,res;if(!this.unsigned){if(this.eq(_Long.MIN_VALUE)){if(divisor.eq(_Long.ONE)||divisor.eq(_Long.NEG_ONE))return _Long.MIN_VALUE;else if(divisor.eq(_Long.MIN_VALUE))return _Long.ONE;else{const halfThis=this.shr(1);approx=halfThis.div(divisor).shl(1);if(approx.eq(_Long.ZERO)){return divisor.isNegative()?_Long.ONE:_Long.NEG_ONE}else{rem=this.sub(divisor.mul(approx));res=approx.add(rem.div(divisor));return res}}}else if(divisor.eq(_Long.MIN_VALUE))return this.unsigned?_Long.UZERO:_Long.ZERO;if(this.isNegative()){if(divisor.isNegative())return this.neg().div(divisor.neg());return this.neg().div(divisor).neg()}else if(divisor.isNegative())return this.div(divisor.neg()).neg();res=_Long.ZERO}else{if(!divisor.unsigned)divisor=divisor.toUnsigned();if(divisor.gt(this))return _Long.UZERO;if(divisor.gt(this.shru(1)))return _Long.UONE;res=_Long.UZERO}rem=this;while(rem.gte(divisor)){approx=Math.max(1,Math.floor(rem.toNumber()/divisor.toNumber()));const log2=Math.ceil(Math.log(approx)/Math.LN2);const delta=log2<=48?1:Math.pow(2,log2-48);let approxRes=_Long.fromNumber(approx);let approxRem=approxRes.mul(divisor);while(approxRem.isNegative()||approxRem.gt(rem)){approx-=delta;approxRes=_Long.fromNumber(approx,this.unsigned);approxRem=approxRes.mul(divisor)}if(approxRes.isZero())approxRes=_Long.ONE;res=res.add(approxRes);rem=rem.sub(approxRem)}return res}div(divisor){return this.divide(divisor)}equals(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.unsigned!==other.unsigned&&this.high>>>31===1&&other.high>>>31===1)return false;return this.high===other.high&&this.low===other.low}eq(other){return this.equals(other)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative()){return this.eq(_Long.MIN_VALUE)?64:this.neg().getNumBitsAbs()}const val=this.high!==0?this.high:this.low;let bit;for(bit=31;bit>0;bit--)if((val&1<0}gt(other){return this.greaterThan(other)}greaterThanOrEqual(other){return this.comp(other)>=0}gte(other){return this.greaterThanOrEqual(other)}ge(other){return this.greaterThanOrEqual(other)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(other){return this.comp(other)<0}lt(other){return this.lessThan(other)}lessThanOrEqual(other){return this.comp(other)<=0}lte(other){return this.lessThanOrEqual(other)}modulo(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(wasm){const low=(this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}return this.sub(this.div(divisor).mul(divisor))}mod(divisor){return this.modulo(divisor)}rem(divisor){return this.modulo(divisor)}multiply(multiplier){if(this.isZero())return _Long.ZERO;if(!_Long.isLong(multiplier))multiplier=_Long.fromValue(multiplier);if(wasm){const low=wasm.mul(this.low,this.high,multiplier.low,multiplier.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(multiplier.isZero())return _Long.ZERO;if(this.eq(_Long.MIN_VALUE))return multiplier.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(multiplier.eq(_Long.MIN_VALUE))return this.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(this.isNegative()){if(multiplier.isNegative())return this.neg().mul(multiplier.neg());else return this.neg().mul(multiplier).neg()}else if(multiplier.isNegative())return this.mul(multiplier.neg()).neg();if(this.lt(_Long.TWO_PWR_24)&&multiplier.lt(_Long.TWO_PWR_24))return _Long.fromNumber(this.toNumber()*multiplier.toNumber(),this.unsigned);const a48=this.high>>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=multiplier.high>>>16;const b32=multiplier.high&65535;const b16=multiplier.low>>>16;const b00=multiplier.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}mul(multiplier){return this.multiply(multiplier)}negate(){if(!this.unsigned&&this.eq(_Long.MIN_VALUE))return _Long.MIN_VALUE;return this.not().add(_Long.ONE)}neg(){return this.negate()}not(){return _Long.fromBits(~this.low,~this.high,this.unsigned)}notEquals(other){return!this.equals(other)}neq(other){return this.notEquals(other)}ne(other){return this.notEquals(other)}or(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low|other.low,this.high|other.high,this.unsigned)}shiftLeft(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();if((numBits&=63)===0)return this;else if(numBits<32)return _Long.fromBits(this.low<>>32-numBits,this.unsigned);else return _Long.fromBits(0,this.low<>>numBits|this.high<<32-numBits,this.high>>numBits,this.unsigned);else return _Long.fromBits(this.high>>numBits-32,this.high>=0?0:-1,this.unsigned)}shr(numBits){return this.shiftRight(numBits)}shiftRightUnsigned(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();numBits&=63;if(numBits===0)return this;else{const high=this.high;if(numBits<32){const low=this.low;return _Long.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits,this.unsigned)}else if(numBits===32)return _Long.fromBits(high,0,this.unsigned);else return _Long.fromBits(high>>>numBits-32,0,this.unsigned)}}shr_u(numBits){return this.shiftRightUnsigned(numBits)}shru(numBits){return this.shiftRightUnsigned(numBits)}subtract(subtrahend){if(!_Long.isLong(subtrahend))subtrahend=_Long.fromValue(subtrahend);return this.add(subtrahend.neg())}sub(subtrahend){return this.subtract(subtrahend)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0);return this.high*TWO_PWR_32_DBL+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(le){return le?this.toBytesLE():this.toBytesBE()}toBytesLE(){const hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}toBytesBE(){const hi=this.high,lo=this.low;return[hi>>>24,hi>>>16&255,hi>>>8&255,hi&255,lo>>>24,lo>>>16&255,lo>>>8&255,lo&255]}toSigned(){if(!this.unsigned)return this;return _Long.fromBits(this.low,this.high,false)}toString(radix){radix=radix||10;if(radix<2||36>>0;let digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6)digits="0"+digits;result=""+digits+result}}}toUnsigned(){if(this.unsigned)return this;return _Long.fromBits(this.low,this.high,true)}xor(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low^other.low,this.high^other.high,this.unsigned)}eqz(){return this.isZero()}le(other){return this.lessThanOrEqual(other)}toExtendedJSON(options){if(options&&options.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(doc,options){const{useBigInt64=false,relaxed=true}={...options};if(doc.$numberLong.length>MAX_INT64_STRING_LENGTH){throw new BSONError("$numberLong string is too long")}if(!DECIMAL_REG_EX.test(doc.$numberLong)){throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`)}if(useBigInt64){const bigIntResult=BigInt(doc.$numberLong);return BigInt.asIntN(64,bigIntResult)}const longResult=_Long.fromString(doc.$numberLong);if(relaxed){return longResult.toNumber()}return longResult}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Long("${this.toString()}"${this.unsigned?", true":""})`}};Long.TWO_PWR_24=Long.fromInt(TWO_PWR_24_DBL);Long.MAX_UNSIGNED_VALUE=Long.fromBits(4294967295|0,4294967295|0,true);Long.ZERO=Long.fromInt(0);Long.UZERO=Long.fromInt(0,true);Long.ONE=Long.fromInt(1);Long.UONE=Long.fromInt(1,true);Long.NEG_ONE=Long.fromInt(-1);Long.MAX_VALUE=Long.fromBits(4294967295|0,2147483647|0,false);Long.MIN_VALUE=Long.fromBits(0,2147483648|0,false);var PARSE_STRING_REGEXP=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var PARSE_INF_REGEXP=/^(\+|-)?(Infinity|inf)$/i;var PARSE_NAN_REGEXP=/^(\+|-)?NaN$/i;var EXPONENT_MAX=6111;var EXPONENT_MIN=-6176;var EXPONENT_BIAS=6176;var MAX_DIGITS=34;var NAN_BUFFER=ByteUtils.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_NEGATIVE_BUFFER=ByteUtils.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_POSITIVE_BUFFER=ByteUtils.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var EXPONENT_REGEX=/^([-+])?(\d+)?$/;var COMBINATION_MASK=31;var EXPONENT_MASK=16383;var COMBINATION_INFINITY=30;var COMBINATION_NAN=31;function isDigit(value){return!isNaN(parseInt(value,10))}function divideu128(value){const DIVISOR=Long.fromNumber(1e3*1e3*1e3);let _rem=Long.fromNumber(0);if(!value.parts[0]&&!value.parts[1]&&!value.parts[2]&&!value.parts[3]){return{quotient:value,rem:_rem}}for(let i=0;i<=3;i++){_rem=_rem.shiftLeft(32);_rem=_rem.add(new Long(value.parts[i],0));value.parts[i]=_rem.div(DIVISOR).low;_rem=_rem.modulo(DIVISOR)}return{quotient:value,rem:_rem}}function multiply64x2(left,right){if(!left&&!right){return{high:Long.fromNumber(0),low:Long.fromNumber(0)}}const leftHigh=left.shiftRightUnsigned(32);const leftLow=new Long(left.getLowBits(),0);const rightHigh=right.shiftRightUnsigned(32);const rightLow=new Long(right.getLowBits(),0);let productHigh=leftHigh.multiply(rightHigh);let productMid=leftHigh.multiply(rightLow);const productMid2=leftLow.multiply(rightHigh);let productLow=leftLow.multiply(rightLow);productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productMid=new Long(productMid.getLowBits(),0).add(productMid2).add(productLow.shiftRightUnsigned(32));productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productLow=productMid.shiftLeft(32).add(new Long(productLow.getLowBits(),0));return{high:productHigh,low:productLow}}function lessThan(left,right){const uhleft=left.high>>>0;const uhright=right.high>>>0;if(uhleft>>0;const ulright=right.low>>>0;if(ulleft=7e3){throw new BSONError(""+representation+" not a valid Decimal128 string")}const stringMatch=representation.match(PARSE_STRING_REGEXP);const infMatch=representation.match(PARSE_INF_REGEXP);const nanMatch=representation.match(PARSE_NAN_REGEXP);if(!stringMatch&&!infMatch&&!nanMatch||representation.length===0){throw new BSONError(""+representation+" not a valid Decimal128 string")}if(stringMatch){const unsignedNumber=stringMatch[2];const e=stringMatch[4];const expSign=stringMatch[5];const expNumber=stringMatch[6];if(e&&expNumber===void 0)invalidErr(representation,"missing exponent power");if(e&&unsignedNumber===void 0)invalidErr(representation,"missing exponent base");if(e===void 0&&(expSign||expNumber)){invalidErr(representation,"missing e before exponent")}}if(representation[index]==="+"||representation[index]==="-"){isNegative=representation[index++]==="-"}if(!isDigit(representation[index])&&representation[index]!=="."){if(representation[index]==="i"||representation[index]==="I"){return new _Decimal128(isNegative?INF_NEGATIVE_BUFFER:INF_POSITIVE_BUFFER)}else if(representation[index]==="N"){return new _Decimal128(NAN_BUFFER)}}while(isDigit(representation[index])||representation[index]==="."){if(representation[index]==="."){if(sawRadix)invalidErr(representation,"contains multiple periods");sawRadix=true;index=index+1;continue}if(nDigitsStored<34){if(representation[index]!=="0"||foundNonZero){if(!foundNonZero){firstNonZero=nDigitsRead}foundNonZero=true;digits[digitsInsert++]=parseInt(representation[index],10);nDigitsStored=nDigitsStored+1}}if(foundNonZero)nDigits=nDigits+1;if(sawRadix)radixPosition=radixPosition+1;nDigitsRead=nDigitsRead+1;index=index+1}if(sawRadix&&!nDigitsRead)throw new BSONError(""+representation+" not a valid Decimal128 string");if(representation[index]==="e"||representation[index]==="E"){const match=representation.substr(++index).match(EXPONENT_REGEX);if(!match||!match[2])return new _Decimal128(NAN_BUFFER);exponent=parseInt(match[0],10);index=index+match[0].length}if(representation[index])return new _Decimal128(NAN_BUFFER);firstDigit=0;if(!nDigitsStored){firstDigit=0;lastDigit=0;digits[0]=0;nDigits=1;nDigitsStored=1;significantDigits=0}else{lastDigit=nDigitsStored-1;significantDigits=nDigits;if(significantDigits!==1){while(digits[firstNonZero+significantDigits-1]===0){significantDigits=significantDigits-1}}}if(exponent<=radixPosition&&radixPosition-exponent>1<<14){exponent=EXPONENT_MIN}else{exponent=exponent-radixPosition}while(exponent>EXPONENT_MAX){lastDigit=lastDigit+1;if(lastDigit-firstDigit>MAX_DIGITS){const digitsString=digits.join("");if(digitsString.match(/^0+$/)){exponent=EXPONENT_MAX;break}invalidErr(representation,"overflow")}exponent=exponent-1}while(exponent=5){roundBit=1;if(roundDigit===5){roundBit=digits[lastDigit]%2===1?1:0;for(i=firstNonZero+lastDigit+2;i=0;dIdx--){if(++digits[dIdx]>9){digits[dIdx]=0;if(dIdx===0){if(exponent>8&255;buffer2[index++]=dec.low.low>>16&255;buffer2[index++]=dec.low.low>>24&255;buffer2[index++]=dec.low.high&255;buffer2[index++]=dec.low.high>>8&255;buffer2[index++]=dec.low.high>>16&255;buffer2[index++]=dec.low.high>>24&255;buffer2[index++]=dec.high.low&255;buffer2[index++]=dec.high.low>>8&255;buffer2[index++]=dec.high.low>>16&255;buffer2[index++]=dec.high.low>>24&255;buffer2[index++]=dec.high.high&255;buffer2[index++]=dec.high.high>>8&255;buffer2[index++]=dec.high.high>>16&255;buffer2[index++]=dec.high.high>>24&255;return new _Decimal128(buffer2)}toString(){let biased_exponent;let significand_digits=0;const significand=new Array(36);for(let i=0;i>26&COMBINATION_MASK;if(combination>>3===3){if(combination===COMBINATION_INFINITY){return string.join("")+"Infinity"}else if(combination===COMBINATION_NAN){return"NaN"}else{biased_exponent=high>>15&EXPONENT_MASK;significand_msb=8+(high>>14&1)}}else{significand_msb=high>>14&7;biased_exponent=high>>17&EXPONENT_MASK}const exponent=biased_exponent-EXPONENT_BIAS;significand128.parts[0]=(high&16383)+((significand_msb&15)<<14);significand128.parts[1]=midh;significand128.parts[2]=midl;significand128.parts[3]=low;if(significand128.parts[0]===0&&significand128.parts[1]===0&&significand128.parts[2]===0&&significand128.parts[3]===0){is_zero=true}else{for(k=3;k>=0;k--){let least_digits=0;const result=divideu128(significand128);significand128=result.quotient;least_digits=result.rem.low;if(!least_digits)continue;for(j=8;j>=0;j--){significand[k*9+j]=least_digits%10;least_digits=Math.floor(least_digits/10)}}}if(is_zero){significand_digits=1;significand[index]=0}else{significand_digits=36;while(!significand[index]){significand_digits=significand_digits-1;index=index+1}}const scientific_exponent=significand_digits-1+exponent;if(scientific_exponent>=34||scientific_exponent<=-7||exponent>0){if(significand_digits>34){string.push(`${0}`);if(exponent>0)string.push(`E+${exponent}`);else if(exponent<0)string.push(`E${exponent}`);return string.join("")}string.push(`${significand[index++]}`);significand_digits=significand_digits-1;if(significand_digits){string.push(".")}for(let i=0;i0){string.push(`+${scientific_exponent}`)}else{string.push(`${scientific_exponent}`)}}else{if(exponent>=0){for(let i=0;i0){for(let i=0;i>8&255;buffer2[9]=inc>>16&255;return buffer2}toString(encoding){if(encoding==="base64")return ByteUtils.toBase64(this.id);if(encoding==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(otherId===void 0||otherId===null){return false}if(otherId instanceof _ObjectId){return this[kId][11]===otherId[kId][11]&&ByteUtils.equals(this[kId],otherId[kId])}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12&&isUint8Array(this.id)){return ByteUtils.equals(this.id,ByteUtils.fromISO88591(otherId))}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===24){return otherId.toLowerCase()===this.toHexString()}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12){return ByteUtils.equals(ByteUtils.fromUTF8(otherId),this.id)}if(typeof otherId==="object"&&"toHexString"in otherId&&typeof otherId.toHexString==="function"){const otherIdString=otherId.toHexString();const thisIdString=this.toHexString().toLowerCase();return typeof otherIdString==="string"&&otherIdString.toLowerCase()===thisIdString}return false}getTimestamp(){const timestamp=new Date;const time=BSONDataView.fromUint8Array(this.id).getUint32(0,false);timestamp.setTime(Math.floor(time)*1e3);return timestamp}static createPk(){return new _ObjectId}static createFromTime(time){const buffer2=ByteUtils.fromNumberArray([0,0,0,0,0,0,0,0,0,0,0,0]);BSONDataView.fromUint8Array(buffer2).setUint32(0,time,false);return new _ObjectId(buffer2)}static createFromHexString(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new BSONError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}return new _ObjectId(ByteUtils.fromHex(hexString))}static isValid(id){if(id==null)return false;try{new _ObjectId(id);return true}catch{return false}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(doc){return new _ObjectId(doc.$oid)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new ObjectId("${this.toHexString()}")`}};ObjectId2.index=Math.floor(Math.random()*16777215);function internalCalculateObjectSize(object,serializeFunctions,ignoreUndefined){let totalLength=4+1;if(Array.isArray(object)){for(let i=0;i=JS_INT_MIN&&value<=JS_INT_MAX){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(4+1)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}case"undefined":if(isArray||!ignoreUndefined)return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1;return 0;case"boolean":return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+1);case"object":if(value!=null&&typeof value._bsontype==="string"&&value[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(value==null||value._bsontype==="MinKey"||value._bsontype==="MaxKey"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1}else if(value._bsontype==="ObjectId"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(12+1)}else if(value instanceof Date||isDate(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(ArrayBuffer.isView(value)||value instanceof ArrayBuffer||isAnyArrayBuffer(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+4+1)+value.byteLength}else if(value._bsontype==="Long"||value._bsontype==="Double"||value._bsontype==="Timestamp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(value._bsontype==="Decimal128"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(16+1)}else if(value._bsontype==="Code"){if(value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+4+ByteUtils.utf8ByteLength(value.code.toString())+1+internalCalculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.code.toString())+1}}else if(value._bsontype==="Binary"){const binary=value;if(binary.sub_type===Binary.SUBTYPE_BYTE_ARRAY){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1+4)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1)}}else if(value._bsontype==="Symbol"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+ByteUtils.utf8ByteLength(value.value)+4+1+1}else if(value._bsontype==="DBRef"){const ordered_values=Object.assign({$ref:value.collection,$id:value.oid},value.fields);if(value.db!=null){ordered_values["$db"]=value.db}return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+internalCalculateObjectSize(ordered_values,serializeFunctions,ignoreUndefined)}else if(value instanceof RegExp||isRegExp(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.source)+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else if(value._bsontype==="BSONRegExp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.pattern)+1+ByteUtils.utf8ByteLength(value.options)+1}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+internalCalculateObjectSize(value,serializeFunctions,ignoreUndefined)+1}case"function":if(serializeFunctions){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.toString())+1}}return 0}function alphabetize(str2){return str2.split("").sort().join("")}var BSONRegExp=class _BSONRegExp extends BSONValue{get _bsontype(){return"BSONRegExp"}constructor(pattern,options){super();this.pattern=pattern;this.options=alphabetize(options??"");if(this.pattern.indexOf("\0")!==-1){throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`)}if(this.options.indexOf("\0")!==-1){throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`)}for(let i=0;i4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max")}if(low.i>4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max")}super(low.i.valueOf(),low.t.valueOf(),true)}else{throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}}toJSON(){return{$timestamp:this.toString()}}static fromInt(value){return new _Timestamp(Long.fromInt(value,true))}static fromNumber(value){return new _Timestamp(Long.fromNumber(value,true))}static fromBits(lowBits,highBits){return new _Timestamp({i:lowBits,t:highBits})}static fromString(str2,optRadix){return new _Timestamp(Long.fromString(str2,true,optRadix))}toExtendedJSON(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}}static fromExtendedJSON(doc){const i=Long.isLong(doc.$timestamp.i)?doc.$timestamp.i.getLowBitsUnsigned():doc.$timestamp.i;const t=Long.isLong(doc.$timestamp.t)?doc.$timestamp.t.getLowBitsUnsigned():doc.$timestamp.t;return new _Timestamp({t,i})}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`}};Timestamp.MAX_VALUE=Long.MAX_UNSIGNED_VALUE;var FIRST_BIT=128;var FIRST_TWO_BITS=192;var FIRST_THREE_BITS=224;var FIRST_FOUR_BITS=240;var FIRST_FIVE_BITS=248;var TWO_BIT_CHAR=192;var THREE_BIT_CHAR=224;var FOUR_BIT_CHAR=240;var CONTINUING_CHAR=128;function validateUtf8(bytes,start,end){let continuation=0;for(let i=start;i= 5, is ${size}`)}if(options.allowObjectSmallerThanBufferSize&&buffer2.length= bson size ${size}`)}if(!options.allowObjectSmallerThanBufferSize&&buffer2.length!==size){throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`)}if(size+index>buffer2.byteLength){throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`)}if(buffer2[index+size-1]!==0){throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(buffer2,index,options,isArray)}var allowedDBRefKeys=/^\$ref$|^\$id$|^\$db$/;function deserializeObject(buffer2,index,options,isArray=false){const fieldsAsRaw=options["fieldsAsRaw"]==null?null:options["fieldsAsRaw"];const raw=options["raw"]==null?false:options["raw"];const bsonRegExp=typeof options["bsonRegExp"]==="boolean"?options["bsonRegExp"]:false;const promoteBuffers=options.promoteBuffers??false;const promoteLongs=options.promoteLongs??true;const promoteValues=options.promoteValues??true;const useBigInt64=options.useBigInt64??false;if(useBigInt64&&!promoteValues){throw new BSONError("Must either request bigint or Long for int64 deserialization")}if(useBigInt64&&!promoteLongs){throw new BSONError("Must either request bigint or Long for int64 deserialization")}const validation=options.validation==null?{utf8:true}:options.validation;let globalUTFValidation=true;let validationSetting;const utf8KeysSet=new Set;const utf8ValidatedKeys=validation.utf8;if(typeof utf8ValidatedKeys==="boolean"){validationSetting=utf8ValidatedKeys}else{globalUTFValidation=false;const utf8ValidationValues=Object.keys(utf8ValidatedKeys).map(function(key){return utf8ValidatedKeys[key]});if(utf8ValidationValues.length===0){throw new BSONError("UTF-8 validation setting cannot be empty")}if(typeof utf8ValidationValues[0]!=="boolean"){throw new BSONError("Invalid UTF-8 validation option, must specify boolean values")}validationSetting=utf8ValidationValues[0];if(!utf8ValidationValues.every(item=>item===validationSetting)){throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}}if(!globalUTFValidation){for(const key of Object.keys(utf8ValidatedKeys)){utf8KeysSet.add(key)}}const startIndex=index;if(buffer2.length<5)throw new BSONError("corrupt bson message < 5 bytes long");const size=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(size<5||size>buffer2.length)throw new BSONError("corrupt bson message");const object=isArray?[]:{};let arrayIndex=0;const done=false;let isPossibleDBRef=isArray?false:null;const dataview=new DataView(buffer2.buffer,buffer2.byteOffset,buffer2.byteLength);while(!done){const elementType=buffer2[index++];if(elementType===0)break;let i=index;while(buffer2[i]!==0&&i=buffer2.byteLength)throw new BSONError("Bad BSON Document: illegal CString");const name=isArray?arrayIndex++:ByteUtils.toUTF8(buffer2.subarray(index,i));let shouldValidateKey=true;if(globalUTFValidation||utf8KeysSet.has(name)){shouldValidateKey=validationSetting}else{shouldValidateKey=!validationSetting}if(isPossibleDBRef!==false&&name[0]==="$"){isPossibleDBRef=allowedDBRefKeys.test(name)}let value;index=i+1;if(elementType===BSON_DATA_STRING){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}value=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize}else if(elementType===BSON_DATA_OID){const oid=ByteUtils.allocate(12);oid.set(buffer2.subarray(index,index+12));value=new ObjectId2(oid);index=index+12}else if(elementType===BSON_DATA_INT&&promoteValues===false){value=new Int32(buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24)}else if(elementType===BSON_DATA_INT){value=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24}else if(elementType===BSON_DATA_NUMBER&&promoteValues===false){value=new Double(dataview.getFloat64(index,true));index=index+8}else if(elementType===BSON_DATA_NUMBER){value=dataview.getFloat64(index,true);index=index+8}else if(elementType===BSON_DATA_DATE){const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;value=new Date(new Long(lowBits,highBits).toNumber())}else if(elementType===BSON_DATA_BOOLEAN){if(buffer2[index]!==0&&buffer2[index]!==1)throw new BSONError("illegal boolean type value");value=buffer2[index++]===1}else if(elementType===BSON_DATA_OBJECT){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;if(objectSize<=0||objectSize>buffer2.length-index)throw new BSONError("bad embedded document length in bson");if(raw){value=buffer2.slice(index,index+objectSize)}else{let objectOptions=options;if(!globalUTFValidation){objectOptions={...options,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,objectOptions,false)}index=index+objectSize}else if(elementType===BSON_DATA_ARRAY){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;let arrayOptions=options;const stopIndex=index+objectSize;if(fieldsAsRaw&&fieldsAsRaw[name]){arrayOptions={...options,raw:true}}if(!globalUTFValidation){arrayOptions={...arrayOptions,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,arrayOptions,true);index=index+objectSize;if(buffer2[index-1]!==0)throw new BSONError("invalid array terminator byte");if(index!==stopIndex)throw new BSONError("corrupted array bson")}else if(elementType===BSON_DATA_UNDEFINED){value=void 0}else if(elementType===BSON_DATA_NULL){value=null}else if(elementType===BSON_DATA_LONG){const dataview2=BSONDataView.fromUint8Array(buffer2.subarray(index,index+8));const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const long=new Long(lowBits,highBits);if(useBigInt64){value=dataview2.getBigInt64(0,true)}else if(promoteLongs&&promoteValues===true){value=long.lessThanOrEqual(JS_INT_MAX_LONG)&&long.greaterThanOrEqual(JS_INT_MIN_LONG)?long.toNumber():long}else{value=long}}else if(elementType===BSON_DATA_DECIMAL128){const bytes=ByteUtils.allocate(16);bytes.set(buffer2.subarray(index,index+16),0);index=index+16;value=new Decimal128(bytes)}else if(elementType===BSON_DATA_BINARY){let binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const totalBinarySize=binarySize;const subType=buffer2[index++];if(binarySize<0)throw new BSONError("Negative binary type element size found");if(binarySize>buffer2.byteLength)throw new BSONError("Binary type size larger than document size");if(buffer2["slice"]!=null){if(subType===Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(binarySize<0)throw new BSONError("Negative binary type element size found for subtype 0x02");if(binarySize>totalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySizetotalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySize=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;const optionsArray=new Array(regExpOptions.length);for(i=0;i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;value=new BSONRegExp(source,regExpOptions)}else if(elementType===BSON_DATA_SYMBOL){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const symbol=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=promoteValues?symbol:new BSONSymbol(symbol);index=index+stringSize}else if(elementType===BSON_DATA_TIMESTAMP){const i2=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);const t=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);value=new Timestamp({i:i2,t})}else if(elementType===BSON_DATA_MIN_KEY){value=new MinKey}else if(elementType===BSON_DATA_MAX_KEY){value=new MaxKey}else if(elementType===BSON_DATA_CODE){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=new Code(functionString);index=index+stringSize}else if(elementType===BSON_DATA_CODE_W_SCOPE){const totalSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(totalSize<4+4+4+1){throw new BSONError("code_w_scope total size shorter minimum expected length")}const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize;const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;const scopeObject=deserializeObject(buffer2,_index,options,false);index=index+objectSize;if(totalSize<4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too short, truncating scope")}if(totalSize>4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too long, clips outer document")}value=new Code(functionString,scopeObject)}else if(elementType===BSON_DATA_DBPOINTER){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0)throw new BSONError("bad string length in bson");if(validation!=null&&validation.utf8){if(!validateUtf8(buffer2,index,index+stringSize-1)){throw new BSONError("Invalid UTF-8 string in BSON document")}}const namespace=ByteUtils.toUTF8(buffer2.subarray(index,index+stringSize-1));index=index+stringSize;const oidBuffer=ByteUtils.allocate(12);oidBuffer.set(buffer2.subarray(index,index+12),0);const oid=new ObjectId2(oidBuffer);index=index+12;value=new DBRef(namespace,oid)}else{throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`)}if(name==="__proto__"){Object.defineProperty(object,name,{value,writable:true,enumerable:true,configurable:true})}else{object[name]=value}}if(size!==index-startIndex){if(isArray)throw new BSONError("corrupt array bson");throw new BSONError("corrupt object bson")}if(!isPossibleDBRef)return object;if(isDBRefLike(object)){const copy=Object.assign({},object);delete copy.$ref;delete copy.$id;delete copy.$db;return new DBRef(object.$ref,object.$id,object.$db,copy)}return object}function getValidatedString(buffer2,start,end,shouldValidateUtf8){const value=ByteUtils.toUTF8(buffer2.subarray(start,end));if(shouldValidateUtf8){for(let i=0;i>24&255;buffer2[index+2]=size+1>>16&255;buffer2[index+1]=size+1>>8&255;buffer2[index]=size+1&255;index=index+4+size;buffer2[index++]=0;return index}var NUMBER_SPACE=new DataView(new ArrayBuffer(8),0,8);var FOUR_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,4);var EIGHT_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,8);function serializeNumber(buffer2,key,value,index){const isNegativeZero=Object.is(value,-0);const type=!isNegativeZero&&Number.isSafeInteger(value)&&value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN?BSON_DATA_INT:BSON_DATA_NUMBER;if(type===BSON_DATA_INT){NUMBER_SPACE.setInt32(0,value,true)}else{NUMBER_SPACE.setFloat64(0,value,true)}const bytes=type===BSON_DATA_INT?FOUR_BYTE_VIEW_ON_NUMBER:EIGHT_BYTE_VIEW_ON_NUMBER;buffer2[index++]=type;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(bytes,index);index+=bytes.byteLength;return index}function serializeBigInt(buffer2,key,value,index){buffer2[index++]=BSON_DATA_LONG;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index+=numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setBigInt64(0,value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index+=EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;return index}function serializeNull(buffer2,key,_,index){buffer2[index++]=BSON_DATA_NULL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeBoolean(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BOOLEAN;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value?1:0;return index}function serializeDate(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DATE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const dateInMilis=Long.fromNumber(value.getTime());const lowBits=dateInMilis.getLowBits();const highBits=dateInMilis.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.source&&value.source.match(regexp)!=null){throw new BSONError("value "+value.source+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.source,index);buffer2[index++]=0;if(value.ignoreCase)buffer2[index++]=105;if(value.global)buffer2[index++]=115;if(value.multiline)buffer2[index++]=109;buffer2[index++]=0;return index}function serializeBSONRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.pattern.match(regexp)!=null){throw new BSONError("pattern "+value.pattern+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.pattern,index);buffer2[index++]=0;const sortedOptions=value.options.split("").sort().join("");index=index+ByteUtils.encodeUTF8Into(buffer2,sortedOptions,index);buffer2[index++]=0;return index}function serializeMinMax(buffer2,key,value,index){if(value===null){buffer2[index++]=BSON_DATA_NULL}else if(value._bsontype==="MinKey"){buffer2[index++]=BSON_DATA_MIN_KEY}else{buffer2[index++]=BSON_DATA_MAX_KEY}const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeObjectId(buffer2,key,value,index){buffer2[index++]=BSON_DATA_OID;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(isUint8Array(value.id)){buffer2.set(value.id.subarray(0,12),index)}else{throw new BSONError("object ["+JSON.stringify(value)+"] is not a valid ObjectId")}return index+12}function serializeBuffer(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=value.length;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=BSON_BINARY_SUBTYPE_DEFAULT;buffer2.set(value,index);index=index+size;return index}function serializeObject(buffer2,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined,path){if(path.has(value)){throw new BSONError("Cannot convert circular structure to BSON")}path.add(value);buffer2[index++]=Array.isArray(value)?BSON_DATA_ARRAY:BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const endIndex=serializeInto(buffer2,value,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);path.delete(value);return endIndex}function serializeDecimal128(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DECIMAL128;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(value.bytes.subarray(0,16),index);return index+16}function serializeLong(buffer2,key,value,index){buffer2[index++]=value._bsontype==="Long"?BSON_DATA_LONG:BSON_DATA_TIMESTAMP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const lowBits=value.getLowBits();const highBits=value.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeInt32(buffer2,key,value,index){value=value.valueOf();buffer2[index++]=BSON_DATA_INT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value&255;buffer2[index++]=value>>8&255;buffer2[index++]=value>>16&255;buffer2[index++]=value>>24&255;return index}function serializeDouble(buffer2,key,value,index){buffer2[index++]=BSON_DATA_NUMBER;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setFloat64(0,value.value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index=index+8;return index}function serializeFunction(buffer2,key,value,index){buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeCode(buffer2,key,value,index,checkKeys=false,depth=0,serializeFunctions=false,ignoreUndefined=true,path){if(value.scope&&typeof value.scope==="object"){buffer2[index++]=BSON_DATA_CODE_W_SCOPE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;const functionString=value.code;index=index+4;const codeSize=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=codeSize&255;buffer2[index+1]=codeSize>>8&255;buffer2[index+2]=codeSize>>16&255;buffer2[index+3]=codeSize>>24&255;buffer2[index+4+codeSize-1]=0;index=index+codeSize+4;const endIndex=serializeInto(buffer2,value.scope,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);index=endIndex-1;const totalSize=endIndex-startIndex;buffer2[startIndex++]=totalSize&255;buffer2[startIndex++]=totalSize>>8&255;buffer2[startIndex++]=totalSize>>16&255;buffer2[startIndex++]=totalSize>>24&255;buffer2[index++]=0}else{buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.code.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0}return index}function serializeBinary(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const data=value.buffer;let size=value.position;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY)size=size+4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=value.sub_type;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY){size=size-4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255}buffer2.set(data,index);index=index+value.position;return index}function serializeSymbol(buffer2,key,value,index){buffer2[index++]=BSON_DATA_SYMBOL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=ByteUtils.encodeUTF8Into(buffer2,value.value,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeDBRef(buffer2,key,value,index,depth,serializeFunctions,path){buffer2[index++]=BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;let output={$ref:value.collection||value.namespace,$id:value.oid};if(value.db!=null){output.$db=value.db}output=Object.assign(output,value.fields);const endIndex=serializeInto(buffer2,output,false,index,depth+1,serializeFunctions,true,path);const size=endIndex-startIndex;buffer2[startIndex++]=size&255;buffer2[startIndex++]=size>>8&255;buffer2[startIndex++]=size>>16&255;buffer2[startIndex++]=size>>24&255;return endIndex}function serializeInto(buffer2,object,checkKeys,startingIndex,depth,serializeFunctions,ignoreUndefined,path){if(path==null){if(object==null){buffer2[0]=5;buffer2[1]=0;buffer2[2]=0;buffer2[3]=0;buffer2[4]=0;return 5}if(Array.isArray(object)){throw new BSONError("serialize does not support an array as the root input")}if(typeof object!=="object"){throw new BSONError("serialize does not support non-object as the root input")}else if("_bsontype"in object&&typeof object._bsontype==="string"){throw new BSONError(`BSON types cannot be serialized as a document`)}else if(isDate(object)||isRegExp(object)||isUint8Array(object)||isAnyArrayBuffer(object)){throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`)}path=new Set}path.add(object);let index=startingIndex+4;if(Array.isArray(object)){for(let i=0;i>8&255;buffer2[startingIndex++]=size>>16&255;buffer2[startingIndex++]=size>>24&255;return index}function isBSONType(value){return value!=null&&typeof value==="object"&&"_bsontype"in value&&typeof value._bsontype==="string"}var keysToCodecs={$oid:ObjectId2,$binary:Binary,$uuid:Binary,$symbol:BSONSymbol,$numberInt:Int32,$numberDecimal:Decimal128,$numberDouble:Double,$numberLong:Long,$minKey:MinKey,$maxKey:MaxKey,$regex:BSONRegExp,$regularExpression:BSONRegExp,$timestamp:Timestamp};function deserializeValue(value,options={}){if(typeof value==="number"){const in32BitRange=value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN;const in64BitRange=value<=BSON_INT64_MAX&&value>=BSON_INT64_MIN;if(options.relaxed||options.legacy){return value}if(Number.isInteger(value)&&!Object.is(value,-0)){if(in32BitRange){return new Int32(value)}if(in64BitRange){if(options.useBigInt64){return BigInt(value)}return Long.fromNumber(value)}}return new Double(value)}if(value==null||typeof value!=="object")return value;if(value.$undefined)return null;const keys=Object.keys(value).filter(k=>k.startsWith("$")&&value[k]!=null);for(let i=0;ik.startsWith("$"));let valid=true;dollarKeys.forEach(k=>{if(["$ref","$id","$db"].indexOf(k)===-1)valid=false});if(valid)return DBRef.fromExtendedJSON(v2)}return value}function serializeArray(array,options){return array.map((v2,index)=>{options.seenObjects.push({propertyName:`index ${index}`,obj:null});try{return serializeValue(v2,options)}finally{options.seenObjects.pop()}})}function getISOString(date){const isoStr=date.toISOString();return date.getUTCMilliseconds()!==0?isoStr:isoStr.slice(0,-5)+"Z"}function serializeValue(value,options){if(value instanceof Map||isMap(value)){const obj=Object.create(null);for(const[k,v2]of value){if(typeof k!=="string"){throw new BSONError("Can only serialize maps with string keys")}obj[k]=v2}return serializeValue(obj,options)}if((typeof value==="object"||typeof value==="function")&&value!==null){const index=options.seenObjects.findIndex(entry=>entry.obj===value);if(index!==-1){const props=options.seenObjects.map(entry=>entry.propertyName);const leadingPart=props.slice(0,index).map(prop=>`${prop} -> `).join("");const alreadySeen=props[index];const circularPart=" -> "+props.slice(index+1,props.length-1).map(prop=>`${prop} -> `).join("");const current=props[props.length-1];const leadingSpace=" ".repeat(leadingPart.length+alreadySeen.length/2);const dashes="-".repeat(circularPart.length+(alreadySeen.length+current.length)/2-1);throw new BSONError(`Converting circular structure to EJSON: - ${leadingPart}${alreadySeen}${circularPart}${current} - ${leadingSpace}\\${dashes}/`)}options.seenObjects[options.seenObjects.length-1].obj=value}if(Array.isArray(value))return serializeArray(value,options);if(value===void 0)return null;if(value instanceof Date||isDate(value)){const dateNum=value.getTime(),inRange=dateNum>-1&&dateNum<2534023188e5;if(options.legacy){return options.relaxed&&inRange?{$date:value.getTime()}:{$date:getISOString(value)}}return options.relaxed&&inRange?{$date:getISOString(value)}:{$date:{$numberLong:value.getTime().toString()}}}if(typeof value==="number"&&(!options.relaxed||!isFinite(value))){if(Number.isInteger(value)&&!Object.is(value,-0)){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return{$numberInt:value.toString()}}if(value>=BSON_INT64_MIN&&value<=BSON_INT64_MAX){return{$numberLong:value.toString()}}}return{$numberDouble:Object.is(value,-0)?"-0.0":value.toString()}}if(typeof value==="bigint"){if(!options.relaxed){return{$numberLong:BigInt.asIntN(64,value).toString()}}return Number(BigInt.asIntN(64,value))}if(value instanceof RegExp||isRegExp(value)){let flags=value.flags;if(flags===void 0){const match=value.toString().match(/[gimuy]*$/);if(match){flags=match[0]}}const rx=new BSONRegExp(value.source,flags);return rx.toExtendedJSON(options)}if(value!=null&&typeof value==="object")return serializeDocument(value,options);return value}var BSON_TYPE_MAPPINGS={Binary:o=>new Binary(o.value(),o.sub_type),Code:o=>new Code(o.code,o.scope),DBRef:o=>new DBRef(o.collection||o.namespace,o.oid,o.db,o.fields),Decimal128:o=>new Decimal128(o.bytes),Double:o=>new Double(o.value),Int32:o=>new Int32(o.value),Long:o=>Long.fromBits(o.low!=null?o.low:o.low_,o.low!=null?o.high:o.high_,o.low!=null?o.unsigned:o.unsigned_),MaxKey:()=>new MaxKey,MinKey:()=>new MinKey,ObjectId:o=>new ObjectId2(o),BSONRegExp:o=>new BSONRegExp(o.pattern,o.options),BSONSymbol:o=>new BSONSymbol(o.value),Timestamp:o=>Timestamp.fromBits(o.low,o.high)};function serializeDocument(doc,options){if(doc==null||typeof doc!=="object")throw new BSONError("not an object instance");const bsontype=doc._bsontype;if(typeof bsontype==="undefined"){const _doc={};for(const name of Object.keys(doc)){options.seenObjects.push({propertyName:name,obj:null});try{const value=serializeValue(doc[name],options);if(name==="__proto__"){Object.defineProperty(_doc,name,{value,writable:true,enumerable:true,configurable:true})}else{_doc[name]=value}}finally{options.seenObjects.pop()}}return _doc}else if(doc!=null&&typeof doc==="object"&&typeof doc._bsontype==="string"&&doc[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(isBSONType(doc)){let outDoc=doc;if(typeof outDoc.toExtendedJSON!=="function"){const mapper=BSON_TYPE_MAPPINGS[doc._bsontype];if(!mapper){throw new BSONError("Unrecognized or invalid _bsontype: "+doc._bsontype)}outDoc=mapper(outDoc)}if(bsontype==="Code"&&outDoc.scope){outDoc=new Code(outDoc.code,serializeValue(outDoc.scope,options))}else if(bsontype==="DBRef"&&outDoc.oid){outDoc=new DBRef(serializeValue(outDoc.collection,options),serializeValue(outDoc.oid,options),serializeValue(outDoc.db,options),serializeValue(outDoc.fields,options))}return outDoc.toExtendedJSON(options)}else{throw new BSONError("_bsontype must be a string, but was: "+typeof bsontype)}}function parse(text,options){const ejsonOptions={useBigInt64:options?.useBigInt64??false,relaxed:options?.relaxed??true,legacy:options?.legacy??false};return JSON.parse(text,(key,value)=>{if(key.indexOf("\0")!==-1){throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`)}return deserializeValue(value,ejsonOptions)})}function stringify(value,replacer,space,options){if(space!=null&&typeof space==="object"){options=space;space=0}if(replacer!=null&&typeof replacer==="object"&&!Array.isArray(replacer)){options=replacer;replacer=void 0;space=0}const serializeOptions=Object.assign({relaxed:true,legacy:false},options,{seenObjects:[{propertyName:"(root)",obj:null}]});const doc=serializeValue(value,serializeOptions);return JSON.stringify(doc,replacer,space)}function EJSONserialize(value,options){options=options||{};return JSON.parse(stringify(value,options))}function EJSONdeserialize(ejson,options){options=options||{};return parse(JSON.stringify(ejson),options)}var EJSON=Object.create(null);EJSON.parse=parse;EJSON.stringify=stringify;EJSON.serialize=EJSONserialize;EJSON.deserialize=EJSONdeserialize;Object.freeze(EJSON);var MAXSIZE=1024*1024*17;var buffer=ByteUtils.allocate(MAXSIZE);function setInternalBufferSize(size){if(buffer.lengthAuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}onCollectionSet=(type,collection)=>{};runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b){if(a.timestamp&&b.timestamp)return a.timestamp-b.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_,__,___=this.data){}onSorted(_=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var defaultSpecifiers=["now","minute","5 minutes","30 minutes","hour","6 hours","12 hours","day","3 days","week","2 weeks","month","6 months","year","5 years","decade"];function genTimeSpecifiers(specifiers=defaultSpecifiers){let result=["now"];specifiers.forEach(s=>{if(s!=="now")result.push(`last ${s}`);else result.push(s)});return result}function genTimestampFromString(specifier){const now=new Date;if(specifier==="now"){}else if(specifier==="last minute"){now.setMinutes(now.getMinutes()-1)}else if(specifier==="last hour"){now.setHours(now.getHours()-1)}else if(specifier==="last day"){now.setDate(now.getDate()-1)}else if(specifier==="last week"){now.setDate(now.getDate()-7)}else if(specifier==="last month"){now.setMonth(now.getMonth()-1)}else if(specifier==="last year"){now.setFullYear(now.getFullYear()-1)}else if(specifier==="last decade"){now.setFullYear(now.getFullYear()-1*10)}else if(specifier==="last century"){now.setFullYear(now.getFullYear()-1*100)}else if(specifier==="last millennium"){now.setFullYear(now.getFullYear()-1*1e3)}else if(specifier==="last microsecond"){now.setMilliseconds(now.getMilliseconds()-1)}else if(specifier==="last nanosecond"){now.setMilliseconds(now.getMilliseconds()-1*.001)}else if(specifier.startsWith("last")){const[,count,unit]=specifier.match(/last (\d+) (\w+)/)||[];if(count&&unit){const num=parseInt(count,10);if(unit.includes("minute")){now.setMinutes(now.getMinutes()-num)}else if(unit.includes("hour")){now.setHours(now.getHours()-num)}else if(unit.includes("day")){now.setDate(now.getDate()-num)}else if(unit.includes("week")){now.setDate(now.getDate()-num*7)}else if(unit.includes("month")){now.setMonth(now.getMonth()-num)}else if(unit.includes("year")){now.setFullYear(now.getFullYear()-num)}else if(unit.includes("decade")){now.setFullYear(now.getFullYear()-num*10)}else if(unit.includes("century")){now.setFullYear(now.getFullYear()-num*100)}else if(unit.includes("millennium")){now.setFullYear(now.getFullYear()-num*1e3)}else if(unit.includes("microsecond")){now.setMilliseconds(now.getMilliseconds()-num)}else if(unit.includes("nanosecond")){now.setMilliseconds(now.getMilliseconds()-num*.001)}}}return now.getTime()}var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v2=>{if(!objProps[v2])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v2=>{obj2[k]=v2;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v2)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v2=>!objProps.includes(v2));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v2=>!objProps.includes(v2));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v2=>!objProps.includes(v2));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p2=origin[key];if(Array.isArray(p2))continue;let instanced;if(typeof p2==="function"){if(isNativeClass(p2)){p2=new p2;if(p2 instanceof GraphNode){p2=p2.prototype.constructor(p2,parent,this);instanced=true}}else p2={__operator:p2,__callable:true}}else if(typeof p2==="string"){if(this.__node.nodes.get(p2))p2=this.__node.nodes.get(p2);else p2=this.__node.roots[p2]}else if(typeof p2==="boolean"){if(this.__node.nodes.get(key))p2=this.__node.nodes.get(key);else p2=this.__node.roots[key]}if(p2&&typeof p2==="object"){if(!instanced&&!(p2 instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p2).filter(v2=>!objProps.includes(v2));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p2)).filter(v2=>!objProps.includes(v2));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p2[key2]}p2=cpy}if(!p2.__node)p2.__node={};if(!p2.__node.tag)p2.__node.tag=key;if(!p2.__node.initial)p2.__node.initial=originCpy[key];if(overwrite&&this.get(p2.__node.tag)){this.remove(p2.__node.tag,true)}else if(this.get(p2.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p2.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p2,2);if(instanced||p2 instanceof GraphNode){node=p2}else{node=new GraphNode(p2,parent,this);newnode=true}if(!newnode&&p2 instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d2=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d2.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{name="structs";currentUser;tablet=new DataTablet;collections=this.tablet.collections;id=randomId();useAccessTokens=false;useRefreshTokens=false;constructor(options,user){super(options);this.load(this);if(options.useAccessTokens)this.useAccessTokens=options.useAccessTokens;if(options.useRefreshTokens)this.useRefreshTokens=options.useRefreshTokens;if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}getToken(user){if(this.useAccessTokens)return user.accessToken;else if(this.useRefreshTokens)return user.refreshToken}setupUser=async(userinfo,callback=currentUser=>{})=>{if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u2;let newu=false;if(!user||!user._id){u2=this.userStruct(userinfo,false);newu=true;let wasSet=await this.setUser(u2);let structs=this.getLocalData(void 0,{"ownerId":u2._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u2)}else{u2=user;let toUpdate={_id:userinfo._id,ownerId:userinfo._id};let struct=this.userStruct(userinfo,false);for(const key in struct){if(userinfo[key]&&user[key]!==userinfo[key]){toUpdate[key]=userinfo[key];user[key]=userinfo[key]}else if(struct[key]&&!user[key]){toUpdate[key]=struct[key];user[key]=struct[key]}}if(Object.keys(toUpdate).length>2)await this.setUser(toUpdate);if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u2)}else{let data=await this.getAllUserData(u2._id,void 0,[genTimestampFromString("last day"),Date.now()]);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u2)}if(u2){if(this.currentUser)Object.assign(this.currentUser,u2);else this.currentUser=u2;callback(this.currentUser);return this.currentUser}else{callback(u2);return u2}};baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}this.onResult(data)};structNotification=()=>{this.checkForNotifications()};structDeleted=struct=>{this.deleteLocalData([struct])};onResult=data=>{};randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}addStruct=async(structType="struct",props={},parentUser,parentStruct,updateServer=true)=>{let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct};getUser=async(info="",basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info,basicInfo,this.getToken(this.currentUser)]});callback(res);return res}};queryUsers=async(info,skip,limit,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"queryUsers",args:[this.currentUser._id,info,skip,limit,void 0,this.getToken(this.currentUser)]});callback(res);return res}};getUsers=async(ids=[],basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids,basicInfo]});callback(res);return res}};getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};getAllUserData=async(ownerId,excluded=[],timeRange,callback=this.baseServerCallback)=>{if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[this.currentUser._id,ownerId,excluded,timeRange,this.getToken(this.currentUser)]});callback(res);return res}};query=async(collection,mongoQuery={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!mongoQuery)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,mongoQuery,findOne,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByTimeRange(collection,timeRange,ownerId,limit=0,skip=0,key){let query={};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}let range={$gt:timeRange[0],$lt:timeRange[1]};if(key)query[key]=range;else query.timestamp=range;return this.getData(collection,ownerId,query,limit,skip)}getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct?.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id,this.getToken(this.currentUser)];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};setUser=async(userStruct,callback=this.baseServerCallback)=>{if(userStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};updateServerData=this.setData;deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteUser=async(userId=this.currentUser._id,deleteData,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId,deleteData,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setGroup=async(groupStruct,callback=this.baseServerCallback)=>{if(groupStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setAuthorization=async(authorizationStruct,callback=this.baseServerCallback)=>{if(authorizationStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=await this.currentUser.request({route:"deleteAuthorization",args:[this.currentUser._id,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent){toUpdate=[parent];allReplies.forEach(r=>{let idx=parent.replies?.indexOf(r._id);if(idx>-1)parent.replies.splice(idx,1);let idx2=parent.comments?.indexOf(r._id);if(idx2>-1)parent.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent?._id){let idx=replyTo.replies?.indexOf(parent._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u2=authorizationStruct.authorizerId;if(u2){return new Promise(async resolve=>{this.getUser(u2,true,async data=>{let res;if(!collection)res=await this.getAllUserData(u2,["notification"],void 0,callback);else res=await this.getData(collection,u2,searchDict,limit,skip,callback);resolve(res);callback(res)})})}else return void 0};getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u2=o.authorizerId;if(u2){let data;let user=await this.getUser(u2,true,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u2,["notification"],void 0,callback);else data=await this.getData(collection,u2,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return{};let result={};let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result[a.authorizedId]=true});return result};getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b)=>a*(typeof b==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(void 0,{_id:struct});if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop]===""||copy[prop].constructor.name==="Map"||copy[prop].constructor.name==="Set"||typeof copy[prop]==="function")delete copy[prop];else if(Array.isArray(copy[prop])&©[prop].length===0)delete copy[prop];else if(typeof copy[prop]==="object"&&Object.keys(copy[prop]).length===0)delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(!user.name&&user.firstName)user.name=user.firstName+" "+user.lastName;else if(user.name&&!user.firstName){let split=user.name.split(" ");user.firstName=split[0];user.lastName=split[split.length-1]}if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e15);user._id=user.id;user.ownerId=user.id;let dummy=DataStructures_exports.ProfileStruct();for(const prop in props){if(Object.keys(dummy).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};addEvent=async(parentUser,author="",event="",notes="",startTime=void 0,endTime=void 0,grade=void 0,value=void 0,units=void 0,location=void 0,attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.value=value;newEvent.units=units;newEvent.users=users;newEvent.location=location;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};addChatroom=async(parentUser,authorId="",message="",attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=void 0,updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res}};var import_bson=__toESM(require_bson());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectId=str2=>{return typeof str2==="string"&&str2.length===24?new import_bson.ObjectId(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{name="structs";debug=false;db;users={};collections={};mode="local";useAuths=true;useAccessTokens=false;useRefreshTokens=false;accessTokens=new Map;refreshTokens=new Map;constructor(options,dboptions){super(options);this.load(this);if(dboptions){this.initDB(dboptions)}}initDB=dboptions=>{this.db=dboptions.db;if(dboptions?.users)this.users=dboptions.users;if(dboptions.mode)this.mode=dboptions.mode;if(dboptions?.collections)this.collections=dboptions.collections;if(dboptions.debug)this.debug=dboptions.debug;if(dboptions.useAccessTokens)this.useAccessTokens=dboptions.useAccessTokens;if(dboptions.useRefreshTokens)this.useRefreshTokens=dboptions.useRefreshTokens;if("useAuths"in dboptions)this.useAuths=dboptions.useAuths;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})};query=async(requestingUserId,collection,queryObj,findOne,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip,token)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token);if(passed)return res}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}));return data}};getUser=async(requestingUserId,lookupId,basicInfo,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId,void 0,basicInfo,token)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:void 0};else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};setUser=async(requestingUserId,struct,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(struct.accessToken){this.accessTokens.set(requestingUserId,token)}if(struct.refreshToken){this.refreshTokens.set(requestingUserId,struct.refreshToken)}delete struct.accessToken;delete struct.refreshToken;delete user.accessToken;delete user.refreshToken;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct,token)}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};getUsersByIds=async(requestingUserId,userIds,basicInfo)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds,basicInfo)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct){if(basicInfo)data.push({_id:struct._id,username:struct.username,firstName:struct.firstName,lastName:struct.lastName,fullName:struct.fullName,pictureUrl:struct.pictureUrl});else data.push(struct)}}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};deleteUser=async(requestingUserId,userId,deleteData,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId,deleteData,token)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};setData=async(requestingUserId,structs,notify,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify,token)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};getData=async(requestingUserId,collection,ownerId,dict,limit,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};getDataByIds=async(requestingUserId,structIds,ownerId,collection,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};getAllData=async(requestingUserId,ownerId,excludedCollections,timeRange,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections,timeRange,token)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};deleteData=async(requestingUserId,structIds,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds,token)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};deleteGroup=async(requestingUserId,groupId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId,token)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};getAuthorizations=async(requestingUserId,ownerId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId,token)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};deleteAuthorization=async(requestingUserId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId,token)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};getToken=user=>{return this.useAccessTokens?this.accessTokens.get(user._id):this.useRefreshTokens?this.refreshTokens.get(user._id):void 0};notificationStruct=(parentStruct={})=>{let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct};checkToNotify=async(user,structs=[],mode=this.mode)=>{if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(struct.ownerId&&user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+struct.ownerId;newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+usr;newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id)+"_"+auth.authorizedId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications,true,this.getToken(user))}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid]?.sendAll({route:"structNotification",args:true})}return true}else return false};queryMongo=async(user,collection,queryObj={},findOne=false,skip=0,token)=>{if(!collection&&!queryObj)return void 0;else if(findOne){let res=await this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token)}if(passed)return res;else return void 0}else{let res=this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];let arr=await res.toArray();if(arr.length>0){let passed=!this.useAuths;let checkedAuth="";for(const s of arr){if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)structs.push(s)}}return structs}};setMongoData=async(user,structs=[],notify=true,token)=>{let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:toObjectId(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType?struct.structType:"data").insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectId(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false};setMongoUser=async(user,struct,token)=>{if(struct._id){const _id=toObjectId(struct._id);let usersearch={_id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));copy._id=_id;if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false};setGroup=async(user,struct,mode=this.mode,token)=>{if(struct?._id){let uid=getStringId(user._id);let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(uid)<0))return false;if(uid!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u2=>{allusers.push({email:u2},{id:u2},{username:u2})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});let arr=cursor.toArray();if(arr.length>0){arr.forEach(user2=>{users[uid]=user2;ids[uid]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u2=users[id];if(struct.admins[getStringId(u2._id)]||struct.admins[u2.email]||struct.admins[u2.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u2._id)])admins[getStringId(u2._id)]=true}if(struct.peers[getStringId(u2._id)]||struct.peers[u2.email]||struct.peers[u2.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u2._id)])peers[getStringId(u2._id)]=true}if(struct.clients[getStringId(u2._id)]||struct.clients[u2.email]||struct.clients[u2.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u2._id)])clients[getStringId(u2._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType?struct.structType:"data").findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectId(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false};getMongoUser=(user,info="",requireAuth=true,basicInfo=false,token)=>{return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectId(info)})}catch(e){console.log("error creating ObjectId with ",info)}let u2=await this.collections.profile.instance.findOne({$or:query});if(!u2||u2==null)resolve(void 0);else{u2._id=getStringId(u2._id);if(!u2.ownerId)u2.ownerId=u2._id;if(basicInfo){if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}let stripped={username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id};u2=stripped;resolve({user:u2})}else if(requireAuth){if(getStringId(user._id)!==u2._id||getStringId(user._id)===u2._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u2,"READ",token);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u2._id});let aarr=await auths.toArray();if(auths.toArray().length>0){aarr.forEach(d2=>authorizations.push(d2))}let gs=this.collections.group.instance.find({users:{$all:[u2._id]}});let arr=await gs.toArray();let groups=[];if(arr.length>0){arr.forEach(d2=>groups.push(d2))}resolve({user:u2,authorizations,groups})}else{if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}resolve({user:u2})}}})};queryUsers=(user,info="",limit=0,skip=0,requireAuth=false,token)=>{if(typeof user==="string")user=this.users[user];if(!user)return;return new Promise(async resolve=>{let q={$regex:`^${info}`,$options:"i"};const query=[{email:q},{username:q},{firstName:q},{lastName:q},{name:q}];let arr;if(this.mode.includes("mongo")){let users=this.collections.profile.instance.find({$or:query},{projection:shallowqueryDummy}).skip(skip);if(limit>0)users.limit(limit);await users;arr=await users.toArray()}else{arr=[];for(let i=0;i{arr.push({firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,username:u2.username,pictureUrl:u2.pictureUrl})})}else if(dat)arr.push({firstName:dat.firstName,lastName:dat.lastName,fullName:dat.fullName,username:dat.username,pictureUrl:dat.pictureUrl})}}if(requireAuth){let result=[];let strid=getStringId(user._id);for(let i=0;i{let usrs=[];userIds.forEach(u2=>{try{usrs.push({_id:toObjectId(u2)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{if(basicInfo){found.push({username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id})}else found.push(u2)})}}return found};getMongoUsersByRole=async(user,role)=>{let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{found.push(u2)})}return found};getMongoDataByIds=async(user,structIds,ownerId,collection,token)=>{let uid=getStringId(user._id);if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectId(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});let arr=await cursor.toArray();if(arr.length>0){let passed=true;let checkedAuth="";for(let i=0;i0){let passed=true;let checkedAuth="";arr.forEach(async s=>{if(!s?.ownerId)passed=true;else if((uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}};getMongoData=async(user,collection,ownerId,dict={},limit=0,skip=0,token)=>{if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectId(dict._id);let uid=getStringId(user._id);let structs=[];let passed=true;let checkedAuth="";let cursor;if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip)}else if(collection&&Object.keys(dict).length>0){if(ownerId)dict.ownerId=ownerId;cursor=await this.db.collection(collection).find(dict).sort({$natural:-1}).skip(skip)}if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{cursor=await this.db.collection(name).find(dict).sort({$natural:-1}).skip(skip);;if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i{let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let query={ownerId};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1]);query.timestamp={$gt:timeRange[0],$lt:timeRange[1]}}let cursor=this.db.collection(name).find(query);let arr=await cursor.toArray();let count=arr.length;for(let k=0;k{let structs=[];if(structs.length>0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectId(ref._id)});if(struct){let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs};getMongoAuthorizations=async(user,ownerId=getStringId(user._id),authId="",token)=>{let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectId(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0],"READ",token);if(!passed)return void 0}return auths};getMongoGroups=async(user,userId=getStringId(user._id),groupId="")=>{let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId),users:{$all:[userId]}}))}catch{}}return groups};deleteMongoData=async(user,structRefs=[],token)=>{let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectId(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=notifications.toArray().length;for(let i=0;i{let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){await this.db.collection(struct.structType?struct.structType:"data").deleteOne({_id:toObjectId(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})}}}));return true};deleteMongoUser=async(user,userId,deleteData,token)=>{if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u2=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u2?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u2,"WRITE",token);if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(deleteData){for(const key in this.collections){this.collections[key].instance.deleteMany({ownerId:userId});this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}})}}if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId]?.sendAll({route:"structDeleted",args:{_id:userId,structType:"profile"}});return true};deleteMongoGroup=async(user,groupId,token)=>{let s=await this.collections.group.instance.findOne({_id:toObjectId(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u2=>{this.users[u2]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}})})}await this.collections.group.instance.deleteOne({_id:toObjectId(groupId)});return true}else return false};deleteMongoAuthorization=async(user,authId,token)=>{let s=await this.collections.authorization.instance.findOne({_id:toObjectId(authId)});let uid=getStringId(user._id);if(s){if(uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectId(s.associatedAuthId)});if(s.authorizerId!==uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}});else if(s.authorizedId!==uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}})}await this.collections.authorization.instance.deleteOne({_id:toObjectId(authId)});if(s.authorizerId===uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});else if(s.authorizedId===uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});return true}else return false};setAuthorization=async(user,authStruct,token)=>{let u1,u2;let mmode=this.mode.includes("mongo");if(mmode){u1=(await this.getMongoUser(user,authStruct.authorizedId,false)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,false)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})?.[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})?.[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.name)authStruct.authorizedName=u1.name;else if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u1.name)authStruct.authorizedName=u1.name;else if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE",token);if(!passed)return false}let auths=[];if(mmode){let s=await this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d2=>{if(d2.authorizerId===authStruct.authorizerId)auths.push(d2)})}}let otherAuthset;if(Array.isArray(auths)){for(let i=0;i{if(typeof user==="string"){if(this.users[user])user=this.users[user];else user={_id:user}}if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}return true}}if(this.useAccessTokens){if(!this.accessTokens.get(user._id)||this.accessTokens.get(user._id)!==token){return false}}else if(this.useRefreshTokens){if(!this.refreshTokens.get(user._id)||this.refreshTokens.get(user._id)!==token){return false}}let auth1,auth2;if(this.mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});if(!auth1)return false;auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(struct.ownerId)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(struct.ownerId)}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed};wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};overwriteLocalData=structs=>{if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}};setLocalData=structs=>{let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)};getLocalData=(collection,query)=>{let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result};deleteLocalData=struct=>{if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var shallowqueryDummy=DataStructures_exports.ProfileStruct();for(const key in shallowqueryDummy){if(key==="username"||key==="lastName"||key==="firstName"||key==="name"||key==="_id"||key==="pictureUrl")shallowqueryDummy[key]=1;else delete shallowqueryDummy[key]}var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u2=(dot11*dot02-dot01*dot12)*_denom;let v2=(dot00*dot12-dot01*dot02)*_denom;if(u2>=0&&v2>=0&&u2+v2<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v2=>{let magnitude=0;for(const key in v2){magnitude+=v2[key]*v2[key]}return Math.sqrt(magnitude)},normalize:v2=>{let magnitude=Systems.collision.magnitude(v2);let _mag=magnitude?1/magnitude:0;let vn={};for(const key in v2){vn[key]=v2[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w2=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w2||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var y=class{r;g;b;a;constructor(e,t,l,o){this.r=e,this.g=t,this.b=l,this.a=o}};var w=class{intensity;visible;numPoints;xy;color;scaleX;scaleY;offsetX;offsetY;loop;webglNumPoints;_vbuffer;_coord;constructor(){this.scaleX=1,this.scaleY=1,this.offsetX=0,this.offsetY=0,this.loop=false,this._vbuffer=0,this._coord=0,this.visible=true,this.intensity=1,this.xy=new Float32Array([]),this.numPoints=0,this.color=new y(0,0,0,1),this.webglNumPoints=0}};var v=class extends w{currentIndex=0;constructor(e,t){super(),this.webglNumPoints=t,this.numPoints=t,this.color=e,this.xy=new Float32Array(2*this.webglNumPoints)}setX(e,t){this.xy[e*2]=t}setY(e,t){this.xy[e*2+1]=t}getX(e){return this.xy[e*2]}getY(e){return this.xy[e*2+1]}lineSpaceX(e,t){for(let l=0;l{let l={x:0,y:0};return l.x=u2.x+e.x*t,l.y=u2.y+e.y*t,l};var A=u2=>P(-u2.y,u2.x);var p=(u2,e)=>{let t=R(u2,e);return t=M(t),t};var T=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x+e.x,t.y=u2.y+e.y,t};var C=(u2,e)=>u2.x*e.x+u2.y*e.y;var M=u2=>{let e={x:0,y:0},t=u2.x*u2.x+u2.y*u2.y;return t>0&&(t=1/Math.sqrt(t),e.x=u2.x*t,e.y=u2.y*t),e};var P=(u2,e)=>{let t={x:0,y:0};return t.x=u2,t.y=e,t};var R=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x-e.x,t.y=u2.y-e.y,t};var X=u2=>{let e,t={x:0,y:0},l={x:0,y:0},o=[],a=(s,r)=>{o.push({vec2:s,miterLength:r})},h=s=>({x:u2[s*2],y:u2[s*2+1]});t=p(h(1),h(0)),e=A(t),a(e,1);let n=u2.length/2;for(let s=1;s{let t=T(u2,e);return t=M(t),P(-t.y,t.x)};var N=(u2,e,t)=>{let l=P(-u2.y,u2.x);return t/C(e,l)};var d=class extends w{currentIndex=0;_linePoints;_thicknessRequested=0;_actualThickness=0;constructor(e,t,l){super(),this.webglNumPoints=t*2,this.numPoints=t,this.color=e,this._thicknessRequested=l,this._linePoints=new Float32Array(t*2),this.xy=new Float32Array(2*this.webglNumPoints)}convertToTriPoints(){let e=this._actualThickness/2,t=X(this._linePoints);for(let l=0;l{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(l.loop?t.LINE_LOOP:t.LINE_STRIP,0,l.webglNumPoints)}})}_drawSurfaces(e){let t=this.webgl;e.forEach(l=>{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(t.TRIANGLE_STRIP,0,l.webglNumPoints)}})}_drawTriangles(e){let t=this.webgl;t.bufferData(t.ARRAY_BUFFER,e.xy,t.STREAM_DRAW),t.useProgram(this._progLine);let l=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(l,false,new Float32Array([e.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,e.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let o=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(o,new Float32Array([e.offsetX+this.gOffsetX,e.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([0,0]));let h=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(h,[e.color.r,e.color.g,e.color.b,e.color.a]),t.drawArrays(t.TRIANGLE_STRIP,0,e.xy.length/2)}_drawThickLines(){this._thickLines.forEach(e=>{if(e.visible){let t=Math.min(this.gScaleX,this.gScaleY);e.setActualThickness(e.getThickness()/t),e.convertToTriPoints(),this._drawTriangles(e)}})}update(){this.clear(),this.draw()}draw(){this._drawLines(this.linesData),this._drawLines(this.linesAux),this._drawThickLines(),this._drawSurfaces(this.surfaces)}clear(){this.webgl.clear(this.webgl.COLOR_BUFFER_BIT)}_addLine(e){e._vbuffer=this.webgl.createBuffer(),this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER,e._vbuffer),this.webgl.bufferData(this.webgl.ARRAY_BUFFER,e.xy,this.webgl.STREAM_DRAW),e._coord=this.webgl.getAttribLocation(this._progLine,"coordinates"),this.webgl.vertexAttribPointer(e._coord,2,this.webgl.FLOAT,false,0,0),this.webgl.enableVertexAttribArray(e._coord)}addDataLine(e){this._addLine(e),this.linesData.push(e)}addLine=this.addDataLine;addAuxLine(e){this._addLine(e),this.linesAux.push(e)}addThickLine(e){this._addLine(e),this._thickLines.push(e)}addSurface(e){this._addLine(e),this.surfaces.push(e)}initThinLineProgram(){let e=` - attribute vec2 coordinates; - uniform mat2 uscale; - uniform vec2 uoffset; - uniform ivec2 is_log; - - void main(void) { - float x = (is_log[0]==1) ? log(coordinates.x) : coordinates.x; - float y = (is_log[1]==1) ? log(coordinates.y) : coordinates.y; - vec2 line = vec2(x, y); - gl_Position = vec4(uscale*line + uoffset, 0.0, 1.0); - }`,t=this.webgl.createShader(this.webgl.VERTEX_SHADER);this.webgl.shaderSource(t,e),this.webgl.compileShader(t);let l=` - precision mediump float; - uniform highp vec4 uColor; - void main(void) { - gl_FragColor = uColor; - }`,o=this.webgl.createShader(this.webgl.FRAGMENT_SHADER);this.webgl.shaderSource(o,l),this.webgl.compileShader(o),this._progLine=this.webgl.createProgram(),this.webgl.attachShader(this._progLine,t),this.webgl.attachShader(this._progLine,o),this.webgl.linkProgram(this._progLine)}popDataLine(){this.linesData.pop()}removeAllLines(){this._linesData=[],this._linesAux=[],this._thickLines=[],this._surfaces=[]}removeDataLines(){this._linesData=[]}removeAuxLines(){this._linesAux=[]}viewport(e,t,l,o){this.webgl.viewport(e,t,l,o)}log(e){this.debug&&console.log("[webgl-plot]:"+e)}};var S=class u{constructor(){this.plots={};this.renderOverlay=(e,t,l,o,a,h=1,n=0)=>{if(typeof l.settings.overlay=="object"&&(o.useOverlay||!("useOverlay"in o))){let s=l.settings.nLines-o.position-1,r=e.height*s/l.settings.nLines,i=e.height*(s+1)/l.settings.nLines;if(t.clearRect(0,r,e.width,i),l.settings.mode==="sweep"){t.strokeStyle=l.settings.sweepColor?l.settings.sweepColor:"rgba(0,255,0,0.8)",t.beginPath();let f=e.width*o.ct/o.values.length;t.moveTo(f,r),t.lineTo(f,i),t.stroke()}if(t.fillStyle=l.settings.overlayColor?l.settings.overlayColor:"white",a&&t.fillText(a,20,e.height*(s+.2)/l.settings.nLines),o.nSec){let f=this.formatTime(o.nSec);t.fillText(`${f}`,l.settings.mode==="sweep"?e.width-35:20,e.height*(s+.9)/l.settings.nLines),t.fillText("0:00",l.settings.mode==="sweep"?20:e.width-35,e.height*(s+.9)/l.settings.nLines)}typeof h=="number"&&t.fillText(`${Math.floor(h)===h?h:h?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.2)/l.settings.nLines),typeof n=="number"&&t.fillText(`${Math.floor(n)===n?n:n?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.8)/l.settings.nLines)}}}initPlot(e,t){if(t||(t=new x2(e.canvas,e.webglOptions)),!e._id)e._id=`plot${Math.floor(Math.random()*1e15)}`;else if(this.plots[e._id]){let r=this.plots[e._id].initial;if(e.lines){for(let i in e.lines)if(r.lines[i]&&Array.isArray(e.lines[i])){let f=e.lines[i];e.lines[i]=r.lines[i]}}e=Object.assign(r,e)}e.overlay&&(typeof e.overlay!="object"&&(e.overlay=document.createElement("canvas"),e.overlay.style.position="absolute",e.overlay.width=e.canvas.width,e.overlay.height=e.canvas.height,e.canvas.appendChild(e.overlay)),e.overlayCtx||(e.overlayCtx=e.overlay.getContext("2d"))),e.width&&(e.canvas.width=e.width,e.canvas.style&&(e.canvas.style.width=e.width+"px"),typeof e.overlay=="object"&&(e.overlay.width=e.width,e.overlay.style&&(e.overlay.style.width=e.width+"px"))),e.height&&(e.canvas.height=e.height,e.canvas.style&&(e.canvas.style.height=e.height+"px"),typeof e.overlay=="object"&&(e.overlay.height=e.height,e.overlay.style&&(e.overlay.style.height=e.height+"px"))),e.lines?.timestamp&&delete e.lines.timestamp,e.lines||(e.lines={});let l={};for(let r in e.lines)l[r]=Object.assign({},l[r]),"viewing"in e.lines[r]||(e.lines[r].viewing=true),l[r].viewing=e.lines[r].viewing,l[r].sps=e.lines[r].sps,l[r].nSec=e.lines[r].nSec,l[r].nPoints=e.lines[r].nPoints,l[r].ymin=e.lines[r].ymin,l[r].ymax=e.lines[r].ymax,l[r].units=e.lines[r].units;let o={plot:t,settings:e,initial:Object.assign(Object.assign({},e),{lines:l}),anim:()=>{t.update()}};this.plots[e._id]=o;let a=0,h=0;Object.keys(e.lines).forEach(r=>{e.lines[r]?.viewing!==false&&h++}),e.nLines=h;let n,s;typeof e.overlay=="object"&&(n=e.overlay,s=e.overlayCtx,s.clearRect(0,0,e.overlay.width,e.overlay.height),s.font=e.overlayFont?e.overlayFont:"1em Courier",s.fillStyle=e.overlayColor?e.overlayColor:"white");for(let r in e.lines){let i=e.lines[r];if(Array.isArray(i)&&(i={values:i},e.lines[r]=i),"viewing"in i||(i.viewing=true),i.color)Array.isArray(i.color)&&(i.color=new y(...i.color));else{let m=u.HSLToRGB(360*(a/h)%360,100,50,1);o.initial.lines[r].color=[...m,1],i.color=new y(...m,1)}let f;if(i.nSec&&i.sps?f=Math.ceil(i.nSec*i.sps):i.nPoints?f=i.nPoints:i.points?f=i.points:e.linePoints?f=e.linePoints:i.values?f=i.values.length:f=1e3,i.points=f,e.lines[r].viewing===false)continue;if((i.width||e.lineWidth)&&i.width!==0){let m=e.lineWidth;m||(m=i.width),i.width?i.line=new d(i.color,f,i.width):e.lineWidth&&(i.line=new d(i.color,f,e.lineWidth)),i.line.lineSpaceX(-1,2/i.line.numPoints)}else i.line=new v(i.color,f),i.line.arrangeX();i.values?.length===i.points?i.values.length!==f&&(i.interpolate?i.values.length>f?i.values=u.downsample(i.values,f):i.values.lengthi.points?i.values=i.values.slice(i.values.length-i.points):i.values=[...new Array(i.points-i.values.length).fill(0),...i.values]):Array.isArray(i.values)?i.values.length>f?i.values=i.values.slice(i.values.length-f):i.values.lengthg){let m=c;g=c,c=m}let _=Math.abs(c);if(i.absmax=_>g?_:g,"autoscale"in i||(i.autoscale=true),i.position||(i.position=e.nLines-a-1),i.autoscale?i.autoscale===2?("clamp"in i||(i.clamp=true),i.scaled=u.autoscale(i.values,i.position,h,i.centerZero,c,g,i.clamp)):(i.scaled=i.values,i.line.scaleY=u.getYScalar(i.values,h,i.centerZero,c,g),i.line.offsetY=u.getYOffset(i.position,h,c,i.line.scaleY)):i.scaled=i.values,i.scaled.forEach((m,L)=>i.line.setY(L,m)),i.line instanceof d?t.addThickLine(i.line):i.line instanceof v&&t.addDataLine(i.line),"xAxis"in i||(i.xAxis=true),i.xAxis){i.xColor?Array.isArray(i.xColor)&&(i.xColor=new y(...i.xColor)):i.xColor=new y(1,1,1,.3);let m=new v(i.xColor,2),L=i.autoscale?(a+1)*2/h-1-1/h:0;m.constY(L),m.arrangeX(),m.xy[2]=1,i.x=m,t.addAuxLine(m)}if(h>1&&i.autoscale&&a!==h-1){e.dividerColor?Array.isArray(e.dividerColor)&&(e.dividerColor=new y(...e.dividerColor)):e.dividerColor=new y(1,1,1,1);let m=new v(e.dividerColor,2);m.constY(i.autoscale?(a+1)*2/h-1:1),m.arrangeX(),m.xy[2]=1,i.divider=m,t.addAuxLine(m)}if(typeof e.overlay=="object"&&(i.useOverlay||!("useOverlay"in i))){let m=e.nLines-i.position-1;s.fillText(r,20,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(g)===g?g:g?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(c)===c?c:c?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.9)/e.nLines)}a++}return requestAnimationFrame(o.anim),this.plots[e._id]}deinitPlot(e){return typeof e=="string"&&(e=this.plots[e]),e.plot.clear(),e.plot.removeAllLines(),true}reinitPlot(e,t){if(typeof e=="string"){let l=e;e=this.plots[e],t._id||(t._id=l)}if(e.plot)return e.plot.clear(),e.plot.removeAllLines(),e.settings.overlayCtx&&e.settings.overlayCtx.clearRect(0,0,e.settings.overlay?.width,e.settings.overlay?.height),this.initPlot(t,e.plot)}getChartSettings(e,t){let l=this.plots[e];if(l){let o=Object.assign({},l.initial);for(let a in l.initial.lines)typeof l.initial.lines[a]?.ymax!="number"&&(o.lines[a].ymax=l.settings.lines[a]?.ymax),typeof l.initial.lines[a]?.ymin!="number"&&(o.lines[a].ymin=l.settings.lines[a]?.ymin),t&&(o.lines[a].values=l.settings.lines[a].values);return delete o.canvas,delete o.overlay,delete o.overlayCtx,o}}update(e,t,l=true){if(typeof e=="string"&&(e=this.plots[e]),!e)return false;let o,a;if(typeof e.settings.overlay=="object"&&(o=e.settings.overlay,a=e.settings.overlayCtx,a.font=e.settings.overlayFont?e.settings.overlayFont:"1em Courier",a.fillStyle=e.settings.overlayColor?e.settings.overlayColor:"white"),t){let h=false;for(let n in t)if(e.settings.lines[n]&&e.settings.lines[n].line){if(e.settings.lines[n]?.viewing===false)continue;let s=e.settings.lines[n];if(s.values){if(e.settings.mode&&e.settings.mode==="sweep"){"ct"in s||(s.ct=0);let g=b=>{s.ct>s.values.length&&(s.ct=0),s.values[s.ct]=b,s.ct++};Array.isArray(t[n])?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n][t[n].length-1])),t[n].forEach(g)):typeof t[n]=="number"?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n])),g(t[n])):t[n].values&&(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n].values[t[n].values.length-1])),t[n].values.forEach(g))}else Array.isArray(t[n])&&s.values?.length<1e5?(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n][t[n].length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n][t[n].length-1]),s.firstWrite=true),t[n].length===s.values.length?s.values=t[n]:u.circularBuffer(s.values,t[n])):typeof t[n]=="number"?(s.firstWrite||(s.values.fill(t[n]),s.firstWrite=true),s.values.push(t[n]),s.values.shift()):t[n]?.values&&(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true),t[n].values.length===s.values.length?s.values=t[n].values:u.circularBuffer(s.values,t[n].values));s.values.length!==s.points&&(s.interpolate?s.values.length>s.points?s.values=u.downsample(s.values,s.points):s.scaled.lengths.points?s.values.splice(0,s.values.length-s.points):s.values=new Array(s.points).fill(0).splice(s.points-s.values.length,0,s.values));let r=s.ymin,i=s.ymax,f=s.values.length<=1e5;if(r===i?(i=f?Math.max(...s.values):1,r=f?Math.min(...s.values):0):isNaN(i)&&(i=f?Math.max(...s.values):1),isNaN(r)&&(r=f?Math.min(...s.values):0),r>i){let g=r;i=r,r=g}let c=Math.abs(r);s.absmax=c>i?c:i,s.autoscale?s.autoscale===2?s.scaled=u.autoscale(s.values,s.position,e.settings.nLines,s.centerZero,r,i,s.clamp):(s.scaled=s.values,s.line.scaleY=u.getYScalar(s.values,e.settings.nLines,s.centerZero,r,i),s.line.offsetY=u.getYOffset(s.position,e.settings.nLines,r,s.line.scaleY)):s.scaled=s.values,s.scaled.forEach((g,b)=>{!s.autoscale&&s.absmax>1?s.line.setY(b,g/s.absmax):s.line.setY(b,g)}),this.renderOverlay(o,a,e,s,n,i,r)}}else e.settings.generateNewLines&&!n.includes("timestamp")&&(Array.isArray(t[n])&&(t[n]={values:t[n]}),!t[n].nSec&&!t[n].nPoints&&!e.settings.linePoints&&(t[n].nPoints=1e3),h=true);if(h)return e.settings.cleanGeneration||Object.keys(e.initial.lines).forEach(n=>{t[n]?t[n]=Object.assign(e.initial.lines[n],t[n]):t[n]=e.initial.lines[n]}),this.reinitPlot(e,{_id:e.settings._id,lines:t}),true}else for(let h in e.settings.lines){let n=e.settings.lines[h];this.renderOverlay(o,a,e,n,h,n.ymax,n.ymin)}return l&&requestAnimationFrame(e.anim),true}updateLine(e,t,l,o,a,h,n){return e.numPoints!==t.length&&(l?e.numPoints>t.length?t=u.downsample(t,e.numPoints):e.numPointse.numPoints?t=t.slice(t.length-e.numPoints):t=[...new Array(t.length).fill(0),...t]),o&&(t=u.autoscale(t,a,h,n)),t.forEach((s,r)=>e.setY(r,s)),true}formatTime(e){let t=Math.floor(e/60),l=Math.floor(t/60);t=t%60,e=e%60;let o="";return l>0&&(o+=l+":",t<10&&(o+="0")),o+=t+":",e>0&&(e<10&&(o+="0"),o+=e),o}static autoscale(e,t=0,l=1,o=false,a,h,n){if(e?.length===0)return e;let s=typeof h=="number"?h:e.length<=1e5?Math.max(...e):1,r=typeof a=="number"?a:e.length<=1e5?Math.min(...e):0,i=1/l,f=1;if(o){let c=Math.max(Math.abs(r),Math.abs(s));return c!==0&&(f=i/c),e.map(g=>(n&&(gs&&(g=s)),g*f+(i*(t+1)*2-1-i)))}else return s===r?s!==0?f=i/s:r!==0&&(f=i/Math.abs(r)):f=i/(s-r),e.map(c=>(n&&(cs&&(c=s)),2*((c-r)*f-1/(2*l))+(i*(t+1)*2-1-i)))}static getYScalar(e,t=1,l=false,o,a){if(e?.length===0)return e;let h=typeof a=="number"?a:e.length<=1e5?Math.max(...e):1,n=typeof o=="number"?o:e.length<=1e5?Math.min(...e):0,s=1/t,r=1;if(l){let i=Math.max(Math.abs(n),Math.abs(h));return i!==0&&(r=s/i),2*r}else return h===n?h!==0?r=s/h:n!==0&&(r=s/Math.abs(n)):r=s/(h-n),2*r}static getYOffset(e=0,t=1,l=0,o=1){let a=1/t,h=a*(e+1)*2-1-a;return l!==0?h-=l*o+1/t:h-=o+1/t,h}static absmax(e){return Math.max(Math.abs(Math.min(...e)),Math.max(...e))}static downsample(e,t,l=1){if(e.length>t){let o=new Array(t),a=e.length/t,h=e.length-1,n=0,s=0;for(let r=a;rh&&(i=h);for(let f=n;ft?u.downsample(e,t,l):e.lengthe.length){let l=e.length;e.splice(0,l,...t.slice(t.length-l))}else e.splice(0,e.length,...t);return e}static formatDataForCharts(e,t){if(Array.isArray(e)){if(Array.isArray(e[0])){let l={};if(e.forEach((o,a)=>{l[a]=o}),e=l,isNaN(e[0][0]))return}else if(t){if(e={[t]:e},isNaN(e[t][0]))return}else if(e={0:e},isNaN(e[0][0]))return}else if(typeof e=="object"){for(let l in e)if(typeof e[l]=="number"?e[l]=[e[l]]:e[l]?.values&&typeof e[l].values=="number"&&(e[l].values=[e[l].values]),isNaN(e[l][0]))return}else if(typeof e=="string"){let l;if(e.includes(`\r -`)){let o=e.split(`\r -`);e={},o.forEach((a,h)=>{a.includes(" ")?l=a.split(" "):a.includes(",")?l=a.split(","):a.includes("|")&&(l=a.split("|")),l&&l.forEach((n,s)=>{if(n.includes(":")){let[r,i]=n.split(":"),f=parseFloat(i);isNaN(f)||(e[r]=[f])}else{let r=parseFloat(n);isNaN(r)||(e[s]=[r])}})})}else e.includes(" ")?l=e.split(" "):e.includes(",")?l=e.split(","):e.includes("|")&&(l=e.split("|"));e={},l&&l.forEach((o,a)=>{if(o.includes(":")){let[h,n]=o.split(":"),s=parseFloat(n);isNaN(s)||(e[h]=[s])}else{let h=parseFloat(o);isNaN(h)||(e[a]=[h])}})}else typeof e=="number"&&(t?e={[t]:[e]}:e={0:[e]});return e}static padTime(e,t,l,o){let a=(e[0]-t)/l/o;return[...new Array(o-e.length).map((n,s)=>t+a*(s+1)),...e]}static interpolateForTime(e,t,l){return u.interpolate(e,Math.ceil(l*t))}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new S;return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new S;return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` - - - - - - - - - - - - - - `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` - - - - - - - - - - - - - - - `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var Math2=class _Math2{constructor(){}static TWO_PI=Math.PI*2;static C=299792458;static G=66743e-15;static h=662607015e-42;static R=8314.32;static Ra=287;static H=69.3;static kbar=1054571817e-43;static kB=1380649e-29;static ke=89875517923e-1;static me=91093837015e-41;static mp=167262192369e-38;static mn=167492749804e-38;static P0=101325;static T0=288.15;static p0=1.225;static Na=60220978e16;static y=1.405;static M0=28.96643;static g0=9.80665;static Re=6378100;static B=1458e-9;static S=110.4;static Sigma=365e-12;static imgkernels={edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]};static HSLToRGB=(h,s,l,scalar=255)=>{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x22=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x22;b=0}else if(60<=h&&h<120){r=x22;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x22}else if(180<=h&&h<240){r=0;g=x22;b=c}else if(240<=h&&h<300){r=x22;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x22}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v2=>v2===a).length-arr.filter(v2=>v2===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean=void 0)=>{let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d2=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean=this.mean(arr);let std=this.std(arr,mean);let z=new Array(arr.length);for(let i=0;ia+(b-mean)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean=this.mean(arr);let std=this.std(arr,mean);return populationMean?std/populationMean:std/mean};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y2)=>acc+Math.pow(y2-meanY,2),0);const ssResidual=observed.reduce((acc,y2,i)=>acc+Math.pow(y2-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p2)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p2*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x22)=>sum+x22,0);const sumY=yCoords.reduce((sum,y2)=>sum+y2,0);const sumXY=xCoords.reduce((sum,x22,i)=>sum+x22*yCoords[i],0);const sumX2=xCoords.reduce((sum,x22)=>sum+x22*x22,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{return vec.map((v2,i)=>v2-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v2,i)=>v2/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x22,y2,z)=>{var r=Math.sqrt(x22*x22+y2*y2+z*z);var theta=Math.atan2(y2,x22);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v2=>(v2-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x22=>{return Math.pow(x22,5)+x22*x22-x22-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y2=x22;return y2},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x22+y2;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w2=x22+y2+z;return w2},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x22;return y2},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x22=Math.cos(t);return x22},yFunc=t=>{let y2=Math.sin(t);return y2},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u2,v2)=>u2,yFunc=(u2,v2)=>v2,zFunc=(u2,v2)=>u2+v2,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u2=rangeU[0];u2{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v2,i,x22,y2)=>{return v2+x22+y2})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v2}, idx:${idx}, x:${i},y:${j}`);return v2+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x22,y2)=>{return[x22*10,y2*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value,index)=>{const row=Array(values.length).fill(0);row[index]=value;return row})};static householderMatrix=v2=>{const size=v2.length;const vvT=v2.map(rowVal=>v2.map(colVal=>rowVal*colVal));const vTv=this.normalize(v2)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A2,B)=>{return A2.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix22*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value=>(value-min)/(max-min))};static garroteThreshold=(data,value)=>{return data.map(x22=>{if(Math.abs(x22)<=value){return 0}else{return x22-value*value/x22}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean1=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v2,i)=>(v2-mean1)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x22,x22),this.cov1d(x22,y2),this.cov1d(x22,z)],[this.cov1d(y2,x22),this.cov1d(y2,y2),this.cov1d(y2,z)],[this.cov1d(z,x22),this.cov1d(z,y2),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v2=>v2-mean)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N2=signalA.length;const M2=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N2=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N2;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x22=arr.filter((element,index)=>{return index%factor===0});return x22};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y2=>y2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x22)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A2,numIter=100)=>{let b=Array(A2.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A2[0].length>A2.length){A2=this.transpose(A2)}const m=A2.length;const n=A2[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A2);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x22):this.normalize(x22);const u2=this.vecsub(x22,e);const normU=this.normalize(u2);const v2=u2.map(val=>val/normU);const Qk=this.householderMatrix(v2);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p2=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p2[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p2[0]=this.matscale(p2[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p2[0]),p2[0]));p2[0]=this.matscale(p2[0],1/p_length);let t_new=this.matmul(mat,p2[0]);let pp=this.matmul(this.transpose(p2[0]),p2[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{ax=ax*this.accelConstant;ay=ay*this.accelConstant;az=az*this.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+this.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+this.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v2,i)=>{return apass(v2,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-this.lastGyroTime;this.lastGyroTime=timestamp;gx=gx*this.gyroConstant+this.gyroXError;gy=gy*this.gyroConstant+this.gyroYError;gz=gz*this.gyroConstant+this.gyroZError;this.gyroXAngle+=gx*elapsed;this.gyroYAngle+=gy*elapsed;this.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:this.gyroXAngle,pitch:this.gyroYAngle,yaw:this.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v2,i)=>{if(result){let r=gpass(v2,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v2,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(this.gyroXAngle||this.gyroYAngle||this.gyroZAngle){result.roll=result.roll*.04+this.gyroXAngle*.96;result.pitch=result.pitch*.04+this.gyroYAngle*.96;result.yaw=this.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-this.lastAccelTime;this.lastAccelTime=timestamp;this.px+=result2.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*.005555555555);this.py+=result2.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*.005555555555);this.pz+=result2.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*.005555555555);result2.px=this.px;result2.py=this.py;result2.pz=this.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{type;freq;sps;Q;dbGain;a0=0;a1=0;a2=0;b0=0;b1=0;b2=0;x1=0;x2=0;y1=0;y2=0;constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A2=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A2+A2);this[type](A2,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A2,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A2,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A2,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A2,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A2,sn,cs,alpha,beta){this.b0=1+alpha*A2;this.b1=-2*cs;this.b2=1-alpha*A2;this.a0=1+alpha/A2;this.a1=-2*cs;this.a2=1-alpha/A2}lowshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1-(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1-(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1+(A2+1)*cs+beta*sn;this.a1=2*(A2-1+(A2+1)*cs);this.a2=A2+1+(A2-1)*cs-beta*sn}highshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1+(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1+(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1-(A2+1)*cs-beta*sn;this.a1=2*(A2-1-(A2+1)*cs);this.a2=A2+1-(A2-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10,__onconnected:function(){if(!this.lowpass){let freq=this.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;this.lowpass=new Biquad("lowpass",this.maxFreq,this.sps);this.peakFinderWindow=Math.floor(this.sps/this.maxFreq);if(this.peakFinderWindow%2===0)this.peakFinderWindow+=1;if(this.peakFinderWindow<5)this.peakFinderWindow=5;this.midpoint=Math.round(this.peakFinderWindow*.5)}},__operator:function(data){if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*this.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){this.refdata.push(amplitude)}this.timestamp.push(timestamp);let beat;if(this.refdata.length>this.peakFinderWindow){this.refdata.shift();this.timestamp.shift()}this.smoothed.push(this.lowpass.applyFilter(this.refdata[this.refdata.length-1]));if(this.smoothed.length>this.peakFinderWindow){this.smoothed.shift()}if(this.smoothed.length===this.peakFinderWindow){if(Math2.isExtrema(this.smoothed,"valley")){this.valleys.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}else if(Math2.isExtrema(this.smoothed,"peak")){this.peaks.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}if(this.valleys.length>2&&this.peaks.length>2){if(this.valleys[this.valleys.length-1].timestamp1&&this.valley_distances.length>1){if(this.lastPeakthis.peak_distances[this.peak_distances.length-1].timestamp){let bpm,change=0;if(this.beats.length<1){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].distance+this.valley_distances[this.valley_distances.length-1].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-1].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].dt+this.valley_distances[this.valley_distances.length-1].dt));change=Math.abs(bpm-this.beats[this.beats.length-1].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-1].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-1].peak0-this.valley_distances[this.valley_distances.length-1].peak0,height1:this.peak_distances[this.peak_distances.length-1].peak1-this.valley_distances[this.valley_distances.length-1].peak1};this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}else{let bpm,change=0;if(this.beats.length<2){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-2].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance));change=Math.abs(bpm-this.beats[this.beats.length-2].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-2].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0,height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1};if(Array.isArray(beat.timestamp))beat.timestamp=beat.timestamp[0];this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}}}if(this.peaks.length>this.limit){this.peaks.shift()}if(this.valleys.length>this.limit){this.valleys.shift()}if(this.peak_distances.length>this.limit){this.peak_distances.shift()}if(this.valley_distances.length>this.limit){this.valley_distances.shift()}if(this.beats.length>this.limit){this.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)result=data.red.map((v2,i)=>{return pass(v2+data.ir[i],data.timestamp[i])}).filter(v2=>{if(v2)return true});else result=data.red.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}}};var blink_detect={sps:250,intervals:{},watch:["0"],tolerance:.2,__onconnected:node=>{node.watch.forEach(ch=>node.intervals[ch]={lowpass:new Biquad("lowpass",20,node.sps),filtered:[],averaged:[]})},__operator:function(data){let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=this.intervals[key].lowpass.applyFilter(n);this.intervals[key].filtered.push(next);this.intervals[key].averaged.push(next);if(this.intervals[key].filtered.length>checkCt){if(this.intervals[key].averaged.length>averageCt){this.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(this.intervals[key].averaged);if(Math.abs(Math.min(...this.intervals[key].filtered))>Math.abs(mean)+this.tolerance){this.intervals[key].filtered.length=0;passed=true;found[key]=true}}else this.intervals[key].filtered.shift()}};for(const key in this.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var ArrayManip=class _ArrayManip{static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,...newEntries.slice(newEntries.length-len))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d2={};data.forEach((arr,i)=>{d2[i]=arr});data=d2;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}static bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target};spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var rechk=/^([<>])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v2,o,c)=>String.fromCharCode(...new Uint8Array(v2.buffer,v2.byteOffset+o,c));var rts=(v2,o,c,s)=>new Uint8Array(v2.buffer,v2.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v2,o,c)=>str(v2,o+1,Math.min(v2.getUint8(o),c-1));var tsp=(v2,o,c,s)=>{v2.setUint8(o,s.length);rts(v2,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v2=>str(v2,o,1),p:(v2,c2)=>rts(v2,o,1,c2)})],"?":c=>[c,1,o=>({u:v2=>Boolean(v2.getUint8(o)),p:(v2,B)=>v2.setUint8(o,B)})],b:c=>[c,1,o=>({u:v2=>v2.getInt8(o),p:(v2,b)=>v2.setInt8(o,b)})],B:c=>[c,1,o=>({u:v2=>v2.getUint8(o),p:(v2,B)=>v2.setUint8(o,B)})],h:c=>[c,2,o=>({u:v2=>v2.getInt16(o,le),p:(v2,h)=>v2.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v2=>v2.getUint16(o,le),p:(v2,H)=>v2.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v2=>v2.getInt32(o,le),p:(v2,i)=>v2.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v2=>v2.getUint32(o,le),p:(v2,I)=>v2.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v2=>v2.getFloat32(o,le),p:(v2,f)=>v2.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v2=>v2.getFloat64(o,le),p:(v2,d2)=>v2.setFloat64(o,d2,le)})],s:c=>[1,c,o=>({u:v2=>str(v2,o,c),p:(v2,s)=>rts(v2,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v2=>pst(v2,o,c),p:(v2,s)=>tsp(v2,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var ByteParser=class _ByteParser extends ArrayManip{static codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x22){let int24=(255&x0)<<16|(255&x1)<<8|255&x22;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x22){return x0*65536+x1*256+x22}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x22,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x22)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x22,x3){return x0*16777216+x1*65536+x22*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M2=pattern.length;if(M2===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R2=256;var rightmost_positions=new Int32Array(R2);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v2=new DataView(arrb,offs|0);return fns.map(f=>f.u(v2))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v2,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var rms={sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{},__operator:function(data){this.watch.forEach(key=>{if(data[key]){if(!this.data[key]){if(Array.isArray(data[key])){this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0])}else this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key])}ByteParser.circularBuffer(this.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){this.rms.timestamp=data.timestamp[data.timestamp.length-1]}else this.rms.timestamp=data.timestamp}else this.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(this.watch.map(async key=>{if(this.data[key])this.rms[key]=Math.sqrt(Math.abs(this.data[key].reduce((p2,v2,i)=>p2+v2*v2)/this.data[key].length));else delete this.rms[key]}));res(this.rms)})}};var circularBuffer2d={bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false,__onconnected:function(node){for(const key in node.watch){node.data[key]=new Array(node.bufferSize).fill(0)}},__operator:function(data){let buffer2d=[];this.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(this.data[key],data[key]);buffer2d.push(this.data[key])}});return buffer2d}};var algorithms={beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d};algorithms["breath"].maxFreq=.2;})(); diff --git a/src/extras/dist/index.services.node.js b/src/extras/dist/index.services.node.js deleted file mode 100644 index fd7961ad..00000000 --- a/src/extras/dist/index.services.node.js +++ /dev/null @@ -1,32 +0,0 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var require_bson=__commonJS({"struct/datastructures/bson.cjs"(exports2){"use strict";var BSON_MAJOR_VERSION=5;var BSON_INT32_MAX=2147483647;var BSON_INT32_MIN=-2147483648;var BSON_INT64_MAX=Math.pow(2,63)-1;var BSON_INT64_MIN=-Math.pow(2,63);var JS_INT_MAX=Math.pow(2,53);var JS_INT_MIN=-Math.pow(2,53);var BSON_DATA_NUMBER=1;var BSON_DATA_STRING=2;var BSON_DATA_OBJECT=3;var BSON_DATA_ARRAY=4;var BSON_DATA_BINARY=5;var BSON_DATA_UNDEFINED=6;var BSON_DATA_OID=7;var BSON_DATA_BOOLEAN=8;var BSON_DATA_DATE=9;var BSON_DATA_NULL=10;var BSON_DATA_REGEXP=11;var BSON_DATA_DBPOINTER=12;var BSON_DATA_CODE=13;var BSON_DATA_SYMBOL=14;var BSON_DATA_CODE_W_SCOPE=15;var BSON_DATA_INT=16;var BSON_DATA_TIMESTAMP=17;var BSON_DATA_LONG=18;var BSON_DATA_DECIMAL128=19;var BSON_DATA_MIN_KEY=255;var BSON_DATA_MAX_KEY=127;var BSON_BINARY_SUBTYPE_DEFAULT=0;var BSON_BINARY_SUBTYPE_UUID_NEW=4;var BSONType=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});var BSONError=class extends Error{get bsonError(){return true}get name(){return"BSONError"}constructor(message){super(message)}static isBSONError(value){return value!=null&&typeof value==="object"&&"bsonError"in value&&value.bsonError===true&&"name"in value&&"message"in value&&"stack"in value}};var BSONVersionError=class extends BSONError{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`)}};var BSONRuntimeError=class extends BSONError{get name(){return"BSONRuntimeError"}constructor(message){super(message)}};function nodejsMathRandomBytes(byteLength){return nodeJsByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var nodejsRandomBytes=(()=>{try{return require("crypto").randomBytes}catch{return nodejsMathRandomBytes}})();var nodeJsByteUtils={toLocalBufferType(potentialBuffer){if(Buffer.isBuffer(potentialBuffer)){return potentialBuffer}if(ArrayBuffer.isView(potentialBuffer)){return Buffer.from(potentialBuffer.buffer,potentialBuffer.byteOffset,potentialBuffer.byteLength)}const stringTag=potentialBuffer?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialBuffer);if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return Buffer.from(potentialBuffer)}throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`)},allocate(size){return Buffer.alloc(size)},equals(a,b){return nodeJsByteUtils.toLocalBufferType(a).equals(b)},fromNumberArray(array){return Buffer.from(array)},fromBase64(base64){return Buffer.from(base64,"base64")},toBase64(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64")},fromISO88591(codePoints){return Buffer.from(codePoints,"binary")},toISO88591(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary")},fromHex(hex){return Buffer.from(hex,"hex")},toHex(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex")},fromUTF8(text){return Buffer.from(text,"utf8")},toUTF8(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8")},utf8ByteLength(input){return Buffer.byteLength(input,"utf8")},encodeUTF8Into(buffer2,source,byteOffset){return nodeJsByteUtils.toLocalBufferType(buffer2).write(source,byteOffset,void 0,"utf8")},randomBytes:nodejsRandomBytes};function isReactNative(){const{navigator}=globalThis;return typeof navigator==="object"&&navigator.product==="ReactNative"}function webMathRandomBytes(byteLength){if(byteLength<0){throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`)}return webByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var webRandomBytes=(()=>{const{crypto}=globalThis;if(crypto!=null&&typeof crypto.getRandomValues==="function"){return byteLength=>{return crypto.getRandomValues(webByteUtils.allocate(byteLength))}}else{if(isReactNative()){const{console:console2}=globalThis;console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return webMathRandomBytes}})();var HEX_DIGIT=/(\d|[a-f])/i;var webByteUtils={toLocalBufferType(potentialUint8array){const stringTag=potentialUint8array?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialUint8array);if(stringTag==="Uint8Array"){return potentialUint8array}if(ArrayBuffer.isView(potentialUint8array)){return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset,potentialUint8array.byteOffset+potentialUint8array.byteLength))}if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return new Uint8Array(potentialUint8array)}throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`)},allocate(size){if(typeof size!=="number"){throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`)}return new Uint8Array(size)},equals(a,b){if(a.byteLength!==b.byteLength){return false}for(let i=0;ic.charCodeAt(0))},toBase64(uint8array){return btoa(webByteUtils.toISO88591(uint8array))},fromISO88591(codePoints){return Uint8Array.from(codePoints,c=>c.charCodeAt(0)&255)},toISO88591(uint8array){return Array.from(Uint16Array.from(uint8array),b=>String.fromCharCode(b)).join("")},fromHex(hex){const evenLengthHex=hex.length%2===0?hex:hex.slice(0,hex.length-1);const buffer2=[];for(let i=0;ibyte.toString(16).padStart(2,"0")).join("")},fromUTF8(text){return new TextEncoder().encode(text)},toUTF8(uint8array){return new TextDecoder("utf8",{fatal:false}).decode(uint8array)},utf8ByteLength(input){return webByteUtils.fromUTF8(input).byteLength},encodeUTF8Into(buffer2,source,byteOffset){const bytes=webByteUtils.fromUTF8(source);buffer2.set(bytes,byteOffset);return bytes.byteLength},randomBytes:webRandomBytes};var hasGlobalBuffer=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==true;var ByteUtils=hasGlobalBuffer?nodeJsByteUtils:webByteUtils;var BSONDataView=class extends DataView{static fromUint8Array(input){return new DataView(input.buffer,input.byteOffset,input.byteLength)}};var VALIDATION_REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;var uuidValidateString=str2=>typeof str2==="string"&&VALIDATION_REGEX.test(str2);var uuidHexStringToBuffer=hexString=>{if(!uuidValidateString(hexString)){throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".')}const sanitizedHexString=hexString.replace(/-/g,"");return ByteUtils.fromHex(sanitizedHexString)};function bufferToUuidHexString(buffer2,includeDashes=true){if(includeDashes){return[ByteUtils.toHex(buffer2.subarray(0,4)),ByteUtils.toHex(buffer2.subarray(4,6)),ByteUtils.toHex(buffer2.subarray(6,8)),ByteUtils.toHex(buffer2.subarray(8,10)),ByteUtils.toHex(buffer2.subarray(10,16))].join("-")}return ByteUtils.toHex(buffer2)}function isAnyArrayBuffer(value){return["[object ArrayBuffer]","[object SharedArrayBuffer]"].includes(Object.prototype.toString.call(value))}function isUint8Array(value){return Object.prototype.toString.call(value)==="[object Uint8Array]"}function isRegExp(d){return Object.prototype.toString.call(d)==="[object RegExp]"}function isMap(d){return Object.prototype.toString.call(d)==="[object Map]"}function isDate(d){return Object.prototype.toString.call(d)==="[object Date]"}var BSONValue=class{get[Symbol.for("@@mdb.bson.version")](){return BSON_MAJOR_VERSION}};var Binary=class _Binary extends BSONValue{get _bsontype(){return"Binary"}constructor(buffer2,subType){super();if(!(buffer2==null)&&!(typeof buffer2==="string")&&!ArrayBuffer.isView(buffer2)&&!(buffer2 instanceof ArrayBuffer)&&!Array.isArray(buffer2)){throw new BSONError("Binary can only be constructed from string, Buffer, TypedArray, or Array")}this.sub_type=subType??_Binary.BSON_BINARY_SUBTYPE_DEFAULT;if(buffer2==null){this.buffer=ByteUtils.allocate(_Binary.BUFFER_SIZE);this.position=0}else{if(typeof buffer2==="string"){this.buffer=ByteUtils.fromISO88591(buffer2)}else if(Array.isArray(buffer2)){this.buffer=ByteUtils.fromNumberArray(buffer2)}else{this.buffer=ByteUtils.toLocalBufferType(buffer2)}this.position=this.buffer.byteLength}}put(byteValue){if(typeof byteValue==="string"&&byteValue.length!==1){throw new BSONError("only accepts single character String")}else if(typeof byteValue!=="number"&&byteValue.length!==1)throw new BSONError("only accepts single character Uint8Array or Array");let decodedByte;if(typeof byteValue==="string"){decodedByte=byteValue.charCodeAt(0)}else if(typeof byteValue==="number"){decodedByte=byteValue}else{decodedByte=byteValue[0]}if(decodedByte<0||decodedByte>255){throw new BSONError("only accepts number in a valid unsigned byte range 0-255")}if(this.buffer.byteLength>this.position){this.buffer[this.position++]=decodedByte}else{const newSpace=ByteUtils.allocate(_Binary.BUFFER_SIZE+this.buffer.length);newSpace.set(this.buffer,0);this.buffer=newSpace;this.buffer[this.position++]=decodedByte}}write(sequence,offset){offset=typeof offset==="number"?offset:this.position;if(this.buffer.byteLengththis.position?offset+sequence.length:this.position}else if(typeof sequence==="string"){const bytes=ByteUtils.fromISO88591(sequence);this.buffer.set(bytes,offset);this.position=offset+sequence.length>this.position?offset+sequence.length:this.position}}read(position,length){length=length&&length>0?length:this.position;return this.buffer.slice(position,position+length)}value(asRaw){asRaw=!!asRaw;if(asRaw&&this.buffer.length===this.position){return this.buffer}if(asRaw){return this.buffer.slice(0,this.position)}return ByteUtils.toISO88591(this.buffer.subarray(0,this.position))}length(){return this.position}toJSON(){return ByteUtils.toBase64(this.buffer)}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.buffer);if(encoding==="base64")return ByteUtils.toBase64(this.buffer);if(encoding==="utf8"||encoding==="utf-8")return ByteUtils.toUTF8(this.buffer);return ByteUtils.toUTF8(this.buffer)}toExtendedJSON(options){options=options||{};const base64String=ByteUtils.toBase64(this.buffer);const subType=Number(this.sub_type).toString(16);if(options.legacy){return{$binary:base64String,$type:subType.length===1?"0"+subType:subType}}return{$binary:{base64:base64String,subType:subType.length===1?"0"+subType:subType}}}toUUID(){if(this.sub_type===_Binary.SUBTYPE_UUID){return new UUID(this.buffer.slice(0,this.position))}throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`)}static fromExtendedJSON(doc,options){options=options||{};let data;let type;if("$binary"in doc){if(options.legacy&&typeof doc.$binary==="string"&&"$type"in doc){type=doc.$type?parseInt(doc.$type,16):0;data=ByteUtils.fromBase64(doc.$binary)}else{if(typeof doc.$binary!=="string"){type=doc.$binary.subType?parseInt(doc.$binary.subType,16):0;data=ByteUtils.fromBase64(doc.$binary.base64)}}}else if("$uuid"in doc){type=4;data=uuidHexStringToBuffer(doc.$uuid)}if(!data){throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`)}return type===BSON_BINARY_SUBTYPE_UUID_NEW?new UUID(data):new _Binary(data,type)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`}};Binary.BSON_BINARY_SUBTYPE_DEFAULT=0;Binary.BUFFER_SIZE=256;Binary.SUBTYPE_DEFAULT=0;Binary.SUBTYPE_FUNCTION=1;Binary.SUBTYPE_BYTE_ARRAY=2;Binary.SUBTYPE_UUID_OLD=3;Binary.SUBTYPE_UUID=4;Binary.SUBTYPE_MD5=5;Binary.SUBTYPE_ENCRYPTED=6;Binary.SUBTYPE_COLUMN=7;Binary.SUBTYPE_USER_DEFINED=128;var UUID_BYTE_LENGTH=16;var UUID=class _UUID extends Binary{constructor(input){let bytes;let hexStr;if(input==null){bytes=_UUID.generate()}else if(input instanceof _UUID){bytes=ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));hexStr=input.__id}else if(ArrayBuffer.isView(input)&&input.byteLength===UUID_BYTE_LENGTH){bytes=ByteUtils.toLocalBufferType(input)}else if(typeof input==="string"){bytes=uuidHexStringToBuffer(input)}else{throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).")}super(bytes,BSON_BINARY_SUBTYPE_UUID_NEW);this.__id=hexStr}get id(){return this.buffer}set id(value){this.buffer=value;if(_UUID.cacheHexString){this.__id=bufferToUuidHexString(value)}}toHexString(includeDashes=true){if(_UUID.cacheHexString&&this.__id){return this.__id}const uuidHexString=bufferToUuidHexString(this.id,includeDashes);if(_UUID.cacheHexString){this.__id=uuidHexString}return uuidHexString}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.id);if(encoding==="base64")return ByteUtils.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(!otherId){return false}if(otherId instanceof _UUID){return ByteUtils.equals(otherId.id,this.id)}try{return ByteUtils.equals(new _UUID(otherId).id,this.id)}catch{return false}}toBinary(){return new Binary(this.id,Binary.SUBTYPE_UUID)}static generate(){const bytes=ByteUtils.randomBytes(UUID_BYTE_LENGTH);bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return bytes}static isValid(input){if(!input){return false}if(input instanceof _UUID){return true}if(typeof input==="string"){return uuidValidateString(input)}if(isUint8Array(input)){if(input.byteLength!==UUID_BYTE_LENGTH){return false}return(input[6]&240)===64&&(input[8]&128)===128}return false}static createFromHexString(hexString){const buffer2=uuidHexStringToBuffer(hexString);return new _UUID(buffer2)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new UUID("${this.toHexString()}")`}};var Code=class _Code extends BSONValue{get _bsontype(){return"Code"}constructor(code,scope){super();this.code=code.toString();this.scope=scope??null}toJSON(){if(this.scope!=null){return{code:this.code,scope:this.scope}}return{code:this.code}}toExtendedJSON(){if(this.scope){return{$code:this.code,$scope:this.scope}}return{$code:this.code}}static fromExtendedJSON(doc){return new _Code(doc.$code,doc.$scope)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const codeJson=this.toJSON();return`new Code("${String(codeJson.code)}"${codeJson.scope!=null?`, ${JSON.stringify(codeJson.scope)}`:""})`}};function isDBRefLike(value){return value!=null&&typeof value==="object"&&"$id"in value&&value.$id!=null&&"$ref"in value&&typeof value.$ref==="string"&&(!("$db"in value)||"$db"in value&&typeof value.$db==="string")}var DBRef=class _DBRef extends BSONValue{get _bsontype(){return"DBRef"}constructor(collection,oid,db,fields){super();const parts=collection.split(".");if(parts.length===2){db=parts.shift();collection=parts.shift()}this.collection=collection;this.oid=oid;this.db=db;this.fields=fields||{}}get namespace(){return this.collection}set namespace(value){this.collection=value}toJSON(){const o=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)o.$db=this.db;return o}toExtendedJSON(options){options=options||{};let o={$ref:this.collection,$id:this.oid};if(options.legacy){return o}if(this.db)o.$db=this.db;o=Object.assign(o,this.fields);return o}static fromExtendedJSON(doc){const copy=Object.assign({},doc);delete copy.$ref;delete copy.$id;delete copy.$db;return new _DBRef(doc.$ref,doc.$id,doc.$db,copy)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const oid=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return`new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db?`, "${this.db}"`:""})`}};var wasm=void 0;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var TWO_PWR_16_DBL=1<<16;var TWO_PWR_24_DBL=1<<24;var TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL;var TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL;var TWO_PWR_63_DBL=TWO_PWR_64_DBL/2;var INT_CACHE={};var UINT_CACHE={};var MAX_INT64_STRING_LENGTH=20;var DECIMAL_REG_EX=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;var Long=class _Long extends BSONValue{get _bsontype(){return"Long"}get __isLong__(){return true}constructor(low=0,high,unsigned){super();if(typeof low==="bigint"){Object.assign(this,_Long.fromBigInt(low,!!high))}else if(typeof low==="string"){Object.assign(this,_Long.fromString(low,!!high))}else{this.low=low|0;this.high=high|0;this.unsigned=!!unsigned}}static fromBits(lowBits,highBits,unsigned){return new _Long(lowBits,highBits,unsigned)}static fromInt(value,unsigned){let obj,cachedObj,cache;if(unsigned){value>>>=0;if(cache=0<=value&&value<256){cachedObj=UINT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,(value|0)<0?-1:0,true);if(cache)UINT_CACHE[value]=obj;return obj}else{value|=0;if(cache=-128<=value&&value<128){cachedObj=INT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,value<0?-1:0,false);if(cache)INT_CACHE[value]=obj;return obj}}static fromNumber(value,unsigned){if(isNaN(value))return unsigned?_Long.UZERO:_Long.ZERO;if(unsigned){if(value<0)return _Long.UZERO;if(value>=TWO_PWR_64_DBL)return _Long.MAX_UNSIGNED_VALUE}else{if(value<=-TWO_PWR_63_DBL)return _Long.MIN_VALUE;if(value+1>=TWO_PWR_63_DBL)return _Long.MAX_VALUE}if(value<0)return _Long.fromNumber(-value,unsigned).neg();return _Long.fromBits(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0,unsigned)}static fromBigInt(value,unsigned){return _Long.fromString(value.toString(),unsigned)}static fromString(str2,unsigned,radix){if(str2.length===0)throw new BSONError("empty string");if(str2==="NaN"||str2==="Infinity"||str2==="+Infinity"||str2==="-Infinity")return _Long.ZERO;if(typeof unsigned==="number"){radix=unsigned,unsigned=false}else{unsigned=!!unsigned}radix=radix||10;if(radix<2||360)throw new BSONError("interior hyphen");else if(p===0){return _Long.fromString(str2.substring(1),unsigned,radix).neg()}const radixToPower=_Long.fromNumber(Math.pow(radix,8));let result=_Long.ZERO;for(let i=0;i>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=addend.high>>>16;const b32=addend.high&65535;const b16=addend.low>>>16;const b00=addend.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}and(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low&other.low,this.high&other.high,this.unsigned)}compare(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.eq(other))return 0;const thisNeg=this.isNegative(),otherNeg=other.isNegative();if(thisNeg&&!otherNeg)return-1;if(!thisNeg&&otherNeg)return 1;if(!this.unsigned)return this.sub(other).isNegative()?-1:1;return other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}comp(other){return this.compare(other)}divide(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(divisor.isZero())throw new BSONError("division by zero");if(wasm){if(!this.unsigned&&this.high===-2147483648&&divisor.low===-1&&divisor.high===-1){return this}const low=(this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?_Long.UZERO:_Long.ZERO;let approx,rem,res;if(!this.unsigned){if(this.eq(_Long.MIN_VALUE)){if(divisor.eq(_Long.ONE)||divisor.eq(_Long.NEG_ONE))return _Long.MIN_VALUE;else if(divisor.eq(_Long.MIN_VALUE))return _Long.ONE;else{const halfThis=this.shr(1);approx=halfThis.div(divisor).shl(1);if(approx.eq(_Long.ZERO)){return divisor.isNegative()?_Long.ONE:_Long.NEG_ONE}else{rem=this.sub(divisor.mul(approx));res=approx.add(rem.div(divisor));return res}}}else if(divisor.eq(_Long.MIN_VALUE))return this.unsigned?_Long.UZERO:_Long.ZERO;if(this.isNegative()){if(divisor.isNegative())return this.neg().div(divisor.neg());return this.neg().div(divisor).neg()}else if(divisor.isNegative())return this.div(divisor.neg()).neg();res=_Long.ZERO}else{if(!divisor.unsigned)divisor=divisor.toUnsigned();if(divisor.gt(this))return _Long.UZERO;if(divisor.gt(this.shru(1)))return _Long.UONE;res=_Long.UZERO}rem=this;while(rem.gte(divisor)){approx=Math.max(1,Math.floor(rem.toNumber()/divisor.toNumber()));const log2=Math.ceil(Math.log(approx)/Math.LN2);const delta=log2<=48?1:Math.pow(2,log2-48);let approxRes=_Long.fromNumber(approx);let approxRem=approxRes.mul(divisor);while(approxRem.isNegative()||approxRem.gt(rem)){approx-=delta;approxRes=_Long.fromNumber(approx,this.unsigned);approxRem=approxRes.mul(divisor)}if(approxRes.isZero())approxRes=_Long.ONE;res=res.add(approxRes);rem=rem.sub(approxRem)}return res}div(divisor){return this.divide(divisor)}equals(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.unsigned!==other.unsigned&&this.high>>>31===1&&other.high>>>31===1)return false;return this.high===other.high&&this.low===other.low}eq(other){return this.equals(other)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative()){return this.eq(_Long.MIN_VALUE)?64:this.neg().getNumBitsAbs()}const val=this.high!==0?this.high:this.low;let bit;for(bit=31;bit>0;bit--)if((val&1<0}gt(other){return this.greaterThan(other)}greaterThanOrEqual(other){return this.comp(other)>=0}gte(other){return this.greaterThanOrEqual(other)}ge(other){return this.greaterThanOrEqual(other)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(other){return this.comp(other)<0}lt(other){return this.lessThan(other)}lessThanOrEqual(other){return this.comp(other)<=0}lte(other){return this.lessThanOrEqual(other)}modulo(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(wasm){const low=(this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}return this.sub(this.div(divisor).mul(divisor))}mod(divisor){return this.modulo(divisor)}rem(divisor){return this.modulo(divisor)}multiply(multiplier){if(this.isZero())return _Long.ZERO;if(!_Long.isLong(multiplier))multiplier=_Long.fromValue(multiplier);if(wasm){const low=wasm.mul(this.low,this.high,multiplier.low,multiplier.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(multiplier.isZero())return _Long.ZERO;if(this.eq(_Long.MIN_VALUE))return multiplier.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(multiplier.eq(_Long.MIN_VALUE))return this.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(this.isNegative()){if(multiplier.isNegative())return this.neg().mul(multiplier.neg());else return this.neg().mul(multiplier).neg()}else if(multiplier.isNegative())return this.mul(multiplier.neg()).neg();if(this.lt(_Long.TWO_PWR_24)&&multiplier.lt(_Long.TWO_PWR_24))return _Long.fromNumber(this.toNumber()*multiplier.toNumber(),this.unsigned);const a48=this.high>>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=multiplier.high>>>16;const b32=multiplier.high&65535;const b16=multiplier.low>>>16;const b00=multiplier.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}mul(multiplier){return this.multiply(multiplier)}negate(){if(!this.unsigned&&this.eq(_Long.MIN_VALUE))return _Long.MIN_VALUE;return this.not().add(_Long.ONE)}neg(){return this.negate()}not(){return _Long.fromBits(~this.low,~this.high,this.unsigned)}notEquals(other){return!this.equals(other)}neq(other){return this.notEquals(other)}ne(other){return this.notEquals(other)}or(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low|other.low,this.high|other.high,this.unsigned)}shiftLeft(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();if((numBits&=63)===0)return this;else if(numBits<32)return _Long.fromBits(this.low<>>32-numBits,this.unsigned);else return _Long.fromBits(0,this.low<>>numBits|this.high<<32-numBits,this.high>>numBits,this.unsigned);else return _Long.fromBits(this.high>>numBits-32,this.high>=0?0:-1,this.unsigned)}shr(numBits){return this.shiftRight(numBits)}shiftRightUnsigned(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();numBits&=63;if(numBits===0)return this;else{const high=this.high;if(numBits<32){const low=this.low;return _Long.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits,this.unsigned)}else if(numBits===32)return _Long.fromBits(high,0,this.unsigned);else return _Long.fromBits(high>>>numBits-32,0,this.unsigned)}}shr_u(numBits){return this.shiftRightUnsigned(numBits)}shru(numBits){return this.shiftRightUnsigned(numBits)}subtract(subtrahend){if(!_Long.isLong(subtrahend))subtrahend=_Long.fromValue(subtrahend);return this.add(subtrahend.neg())}sub(subtrahend){return this.subtract(subtrahend)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0);return this.high*TWO_PWR_32_DBL+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(le){return le?this.toBytesLE():this.toBytesBE()}toBytesLE(){const hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}toBytesBE(){const hi=this.high,lo=this.low;return[hi>>>24,hi>>>16&255,hi>>>8&255,hi&255,lo>>>24,lo>>>16&255,lo>>>8&255,lo&255]}toSigned(){if(!this.unsigned)return this;return _Long.fromBits(this.low,this.high,false)}toString(radix){radix=radix||10;if(radix<2||36>>0;let digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6)digits="0"+digits;result=""+digits+result}}}toUnsigned(){if(this.unsigned)return this;return _Long.fromBits(this.low,this.high,true)}xor(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low^other.low,this.high^other.high,this.unsigned)}eqz(){return this.isZero()}le(other){return this.lessThanOrEqual(other)}toExtendedJSON(options){if(options&&options.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(doc,options){const{useBigInt64=false,relaxed=true}={...options};if(doc.$numberLong.length>MAX_INT64_STRING_LENGTH){throw new BSONError("$numberLong string is too long")}if(!DECIMAL_REG_EX.test(doc.$numberLong)){throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`)}if(useBigInt64){const bigIntResult=BigInt(doc.$numberLong);return BigInt.asIntN(64,bigIntResult)}const longResult=_Long.fromString(doc.$numberLong);if(relaxed){return longResult.toNumber()}return longResult}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Long("${this.toString()}"${this.unsigned?", true":""})`}};Long.TWO_PWR_24=Long.fromInt(TWO_PWR_24_DBL);Long.MAX_UNSIGNED_VALUE=Long.fromBits(4294967295|0,4294967295|0,true);Long.ZERO=Long.fromInt(0);Long.UZERO=Long.fromInt(0,true);Long.ONE=Long.fromInt(1);Long.UONE=Long.fromInt(1,true);Long.NEG_ONE=Long.fromInt(-1);Long.MAX_VALUE=Long.fromBits(4294967295|0,2147483647|0,false);Long.MIN_VALUE=Long.fromBits(0,2147483648|0,false);var PARSE_STRING_REGEXP=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var PARSE_INF_REGEXP=/^(\+|-)?(Infinity|inf)$/i;var PARSE_NAN_REGEXP=/^(\+|-)?NaN$/i;var EXPONENT_MAX=6111;var EXPONENT_MIN=-6176;var EXPONENT_BIAS=6176;var MAX_DIGITS=34;var NAN_BUFFER=ByteUtils.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_NEGATIVE_BUFFER=ByteUtils.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_POSITIVE_BUFFER=ByteUtils.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var EXPONENT_REGEX=/^([-+])?(\d+)?$/;var COMBINATION_MASK=31;var EXPONENT_MASK=16383;var COMBINATION_INFINITY=30;var COMBINATION_NAN=31;function isDigit(value){return!isNaN(parseInt(value,10))}function divideu128(value){const DIVISOR=Long.fromNumber(1e3*1e3*1e3);let _rem=Long.fromNumber(0);if(!value.parts[0]&&!value.parts[1]&&!value.parts[2]&&!value.parts[3]){return{quotient:value,rem:_rem}}for(let i=0;i<=3;i++){_rem=_rem.shiftLeft(32);_rem=_rem.add(new Long(value.parts[i],0));value.parts[i]=_rem.div(DIVISOR).low;_rem=_rem.modulo(DIVISOR)}return{quotient:value,rem:_rem}}function multiply64x2(left,right){if(!left&&!right){return{high:Long.fromNumber(0),low:Long.fromNumber(0)}}const leftHigh=left.shiftRightUnsigned(32);const leftLow=new Long(left.getLowBits(),0);const rightHigh=right.shiftRightUnsigned(32);const rightLow=new Long(right.getLowBits(),0);let productHigh=leftHigh.multiply(rightHigh);let productMid=leftHigh.multiply(rightLow);const productMid2=leftLow.multiply(rightHigh);let productLow=leftLow.multiply(rightLow);productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productMid=new Long(productMid.getLowBits(),0).add(productMid2).add(productLow.shiftRightUnsigned(32));productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productLow=productMid.shiftLeft(32).add(new Long(productLow.getLowBits(),0));return{high:productHigh,low:productLow}}function lessThan(left,right){const uhleft=left.high>>>0;const uhright=right.high>>>0;if(uhleft>>0;const ulright=right.low>>>0;if(ulleft=7e3){throw new BSONError(""+representation+" not a valid Decimal128 string")}const stringMatch=representation.match(PARSE_STRING_REGEXP);const infMatch=representation.match(PARSE_INF_REGEXP);const nanMatch=representation.match(PARSE_NAN_REGEXP);if(!stringMatch&&!infMatch&&!nanMatch||representation.length===0){throw new BSONError(""+representation+" not a valid Decimal128 string")}if(stringMatch){const unsignedNumber=stringMatch[2];const e=stringMatch[4];const expSign=stringMatch[5];const expNumber=stringMatch[6];if(e&&expNumber===void 0)invalidErr(representation,"missing exponent power");if(e&&unsignedNumber===void 0)invalidErr(representation,"missing exponent base");if(e===void 0&&(expSign||expNumber)){invalidErr(representation,"missing e before exponent")}}if(representation[index]==="+"||representation[index]==="-"){isNegative=representation[index++]==="-"}if(!isDigit(representation[index])&&representation[index]!=="."){if(representation[index]==="i"||representation[index]==="I"){return new _Decimal128(isNegative?INF_NEGATIVE_BUFFER:INF_POSITIVE_BUFFER)}else if(representation[index]==="N"){return new _Decimal128(NAN_BUFFER)}}while(isDigit(representation[index])||representation[index]==="."){if(representation[index]==="."){if(sawRadix)invalidErr(representation,"contains multiple periods");sawRadix=true;index=index+1;continue}if(nDigitsStored<34){if(representation[index]!=="0"||foundNonZero){if(!foundNonZero){firstNonZero=nDigitsRead}foundNonZero=true;digits[digitsInsert++]=parseInt(representation[index],10);nDigitsStored=nDigitsStored+1}}if(foundNonZero)nDigits=nDigits+1;if(sawRadix)radixPosition=radixPosition+1;nDigitsRead=nDigitsRead+1;index=index+1}if(sawRadix&&!nDigitsRead)throw new BSONError(""+representation+" not a valid Decimal128 string");if(representation[index]==="e"||representation[index]==="E"){const match=representation.substr(++index).match(EXPONENT_REGEX);if(!match||!match[2])return new _Decimal128(NAN_BUFFER);exponent=parseInt(match[0],10);index=index+match[0].length}if(representation[index])return new _Decimal128(NAN_BUFFER);firstDigit=0;if(!nDigitsStored){firstDigit=0;lastDigit=0;digits[0]=0;nDigits=1;nDigitsStored=1;significantDigits=0}else{lastDigit=nDigitsStored-1;significantDigits=nDigits;if(significantDigits!==1){while(digits[firstNonZero+significantDigits-1]===0){significantDigits=significantDigits-1}}}if(exponent<=radixPosition&&radixPosition-exponent>1<<14){exponent=EXPONENT_MIN}else{exponent=exponent-radixPosition}while(exponent>EXPONENT_MAX){lastDigit=lastDigit+1;if(lastDigit-firstDigit>MAX_DIGITS){const digitsString=digits.join("");if(digitsString.match(/^0+$/)){exponent=EXPONENT_MAX;break}invalidErr(representation,"overflow")}exponent=exponent-1}while(exponent=5){roundBit=1;if(roundDigit===5){roundBit=digits[lastDigit]%2===1?1:0;for(i=firstNonZero+lastDigit+2;i=0;dIdx--){if(++digits[dIdx]>9){digits[dIdx]=0;if(dIdx===0){if(exponent>8&255;buffer2[index++]=dec.low.low>>16&255;buffer2[index++]=dec.low.low>>24&255;buffer2[index++]=dec.low.high&255;buffer2[index++]=dec.low.high>>8&255;buffer2[index++]=dec.low.high>>16&255;buffer2[index++]=dec.low.high>>24&255;buffer2[index++]=dec.high.low&255;buffer2[index++]=dec.high.low>>8&255;buffer2[index++]=dec.high.low>>16&255;buffer2[index++]=dec.high.low>>24&255;buffer2[index++]=dec.high.high&255;buffer2[index++]=dec.high.high>>8&255;buffer2[index++]=dec.high.high>>16&255;buffer2[index++]=dec.high.high>>24&255;return new _Decimal128(buffer2)}toString(){let biased_exponent;let significand_digits=0;const significand=new Array(36);for(let i=0;i>26&COMBINATION_MASK;if(combination>>3===3){if(combination===COMBINATION_INFINITY){return string.join("")+"Infinity"}else if(combination===COMBINATION_NAN){return"NaN"}else{biased_exponent=high>>15&EXPONENT_MASK;significand_msb=8+(high>>14&1)}}else{significand_msb=high>>14&7;biased_exponent=high>>17&EXPONENT_MASK}const exponent=biased_exponent-EXPONENT_BIAS;significand128.parts[0]=(high&16383)+((significand_msb&15)<<14);significand128.parts[1]=midh;significand128.parts[2]=midl;significand128.parts[3]=low;if(significand128.parts[0]===0&&significand128.parts[1]===0&&significand128.parts[2]===0&&significand128.parts[3]===0){is_zero=true}else{for(k=3;k>=0;k--){let least_digits=0;const result=divideu128(significand128);significand128=result.quotient;least_digits=result.rem.low;if(!least_digits)continue;for(j=8;j>=0;j--){significand[k*9+j]=least_digits%10;least_digits=Math.floor(least_digits/10)}}}if(is_zero){significand_digits=1;significand[index]=0}else{significand_digits=36;while(!significand[index]){significand_digits=significand_digits-1;index=index+1}}const scientific_exponent=significand_digits-1+exponent;if(scientific_exponent>=34||scientific_exponent<=-7||exponent>0){if(significand_digits>34){string.push(`${0}`);if(exponent>0)string.push(`E+${exponent}`);else if(exponent<0)string.push(`E${exponent}`);return string.join("")}string.push(`${significand[index++]}`);significand_digits=significand_digits-1;if(significand_digits){string.push(".")}for(let i=0;i0){string.push(`+${scientific_exponent}`)}else{string.push(`${scientific_exponent}`)}}else{if(exponent>=0){for(let i=0;i0){for(let i=0;i>8&255;buffer2[9]=inc>>16&255;return buffer2}toString(encoding){if(encoding==="base64")return ByteUtils.toBase64(this.id);if(encoding==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(otherId===void 0||otherId===null){return false}if(otherId instanceof _ObjectId){return this[kId][11]===otherId[kId][11]&&ByteUtils.equals(this[kId],otherId[kId])}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12&&isUint8Array(this.id)){return ByteUtils.equals(this.id,ByteUtils.fromISO88591(otherId))}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===24){return otherId.toLowerCase()===this.toHexString()}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12){return ByteUtils.equals(ByteUtils.fromUTF8(otherId),this.id)}if(typeof otherId==="object"&&"toHexString"in otherId&&typeof otherId.toHexString==="function"){const otherIdString=otherId.toHexString();const thisIdString=this.toHexString().toLowerCase();return typeof otherIdString==="string"&&otherIdString.toLowerCase()===thisIdString}return false}getTimestamp(){const timestamp=new Date;const time=BSONDataView.fromUint8Array(this.id).getUint32(0,false);timestamp.setTime(Math.floor(time)*1e3);return timestamp}static createPk(){return new _ObjectId}static createFromTime(time){const buffer2=ByteUtils.fromNumberArray([0,0,0,0,0,0,0,0,0,0,0,0]);BSONDataView.fromUint8Array(buffer2).setUint32(0,time,false);return new _ObjectId(buffer2)}static createFromHexString(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new BSONError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}return new _ObjectId(ByteUtils.fromHex(hexString))}static isValid(id){if(id==null)return false;try{new _ObjectId(id);return true}catch{return false}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(doc){return new _ObjectId(doc.$oid)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new ObjectId("${this.toHexString()}")`}};ObjectId2.index=Math.floor(Math.random()*16777215);function internalCalculateObjectSize(object,serializeFunctions,ignoreUndefined){let totalLength=4+1;if(Array.isArray(object)){for(let i=0;i=JS_INT_MIN&&value<=JS_INT_MAX){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(4+1)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}case"undefined":if(isArray||!ignoreUndefined)return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1;return 0;case"boolean":return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+1);case"object":if(value!=null&&typeof value._bsontype==="string"&&value[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(value==null||value._bsontype==="MinKey"||value._bsontype==="MaxKey"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1}else if(value._bsontype==="ObjectId"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(12+1)}else if(value instanceof Date||isDate(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(ArrayBuffer.isView(value)||value instanceof ArrayBuffer||isAnyArrayBuffer(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+4+1)+value.byteLength}else if(value._bsontype==="Long"||value._bsontype==="Double"||value._bsontype==="Timestamp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(value._bsontype==="Decimal128"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(16+1)}else if(value._bsontype==="Code"){if(value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+4+ByteUtils.utf8ByteLength(value.code.toString())+1+internalCalculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.code.toString())+1}}else if(value._bsontype==="Binary"){const binary=value;if(binary.sub_type===Binary.SUBTYPE_BYTE_ARRAY){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1+4)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1)}}else if(value._bsontype==="Symbol"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+ByteUtils.utf8ByteLength(value.value)+4+1+1}else if(value._bsontype==="DBRef"){const ordered_values=Object.assign({$ref:value.collection,$id:value.oid},value.fields);if(value.db!=null){ordered_values["$db"]=value.db}return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+internalCalculateObjectSize(ordered_values,serializeFunctions,ignoreUndefined)}else if(value instanceof RegExp||isRegExp(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.source)+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else if(value._bsontype==="BSONRegExp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.pattern)+1+ByteUtils.utf8ByteLength(value.options)+1}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+internalCalculateObjectSize(value,serializeFunctions,ignoreUndefined)+1}case"function":if(serializeFunctions){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.toString())+1}}return 0}function alphabetize(str2){return str2.split("").sort().join("")}var BSONRegExp=class _BSONRegExp extends BSONValue{get _bsontype(){return"BSONRegExp"}constructor(pattern,options){super();this.pattern=pattern;this.options=alphabetize(options??"");if(this.pattern.indexOf("\0")!==-1){throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`)}if(this.options.indexOf("\0")!==-1){throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`)}for(let i=0;i4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max")}if(low.i>4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max")}super(low.i.valueOf(),low.t.valueOf(),true)}else{throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}}toJSON(){return{$timestamp:this.toString()}}static fromInt(value){return new _Timestamp(Long.fromInt(value,true))}static fromNumber(value){return new _Timestamp(Long.fromNumber(value,true))}static fromBits(lowBits,highBits){return new _Timestamp({i:lowBits,t:highBits})}static fromString(str2,optRadix){return new _Timestamp(Long.fromString(str2,true,optRadix))}toExtendedJSON(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}}static fromExtendedJSON(doc){const i=Long.isLong(doc.$timestamp.i)?doc.$timestamp.i.getLowBitsUnsigned():doc.$timestamp.i;const t=Long.isLong(doc.$timestamp.t)?doc.$timestamp.t.getLowBitsUnsigned():doc.$timestamp.t;return new _Timestamp({t,i})}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`}};Timestamp.MAX_VALUE=Long.MAX_UNSIGNED_VALUE;var FIRST_BIT=128;var FIRST_TWO_BITS=192;var FIRST_THREE_BITS=224;var FIRST_FOUR_BITS=240;var FIRST_FIVE_BITS=248;var TWO_BIT_CHAR=192;var THREE_BIT_CHAR=224;var FOUR_BIT_CHAR=240;var CONTINUING_CHAR=128;function validateUtf8(bytes,start,end){let continuation=0;for(let i=start;i= 5, is ${size}`)}if(options.allowObjectSmallerThanBufferSize&&buffer2.length= bson size ${size}`)}if(!options.allowObjectSmallerThanBufferSize&&buffer2.length!==size){throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`)}if(size+index>buffer2.byteLength){throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`)}if(buffer2[index+size-1]!==0){throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(buffer2,index,options,isArray)}var allowedDBRefKeys=/^\$ref$|^\$id$|^\$db$/;function deserializeObject(buffer2,index,options,isArray=false){const fieldsAsRaw=options["fieldsAsRaw"]==null?null:options["fieldsAsRaw"];const raw=options["raw"]==null?false:options["raw"];const bsonRegExp=typeof options["bsonRegExp"]==="boolean"?options["bsonRegExp"]:false;const promoteBuffers=options.promoteBuffers??false;const promoteLongs=options.promoteLongs??true;const promoteValues=options.promoteValues??true;const useBigInt64=options.useBigInt64??false;if(useBigInt64&&!promoteValues){throw new BSONError("Must either request bigint or Long for int64 deserialization")}if(useBigInt64&&!promoteLongs){throw new BSONError("Must either request bigint or Long for int64 deserialization")}const validation=options.validation==null?{utf8:true}:options.validation;let globalUTFValidation=true;let validationSetting;const utf8KeysSet=new Set;const utf8ValidatedKeys=validation.utf8;if(typeof utf8ValidatedKeys==="boolean"){validationSetting=utf8ValidatedKeys}else{globalUTFValidation=false;const utf8ValidationValues=Object.keys(utf8ValidatedKeys).map(function(key){return utf8ValidatedKeys[key]});if(utf8ValidationValues.length===0){throw new BSONError("UTF-8 validation setting cannot be empty")}if(typeof utf8ValidationValues[0]!=="boolean"){throw new BSONError("Invalid UTF-8 validation option, must specify boolean values")}validationSetting=utf8ValidationValues[0];if(!utf8ValidationValues.every(item=>item===validationSetting)){throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}}if(!globalUTFValidation){for(const key of Object.keys(utf8ValidatedKeys)){utf8KeysSet.add(key)}}const startIndex=index;if(buffer2.length<5)throw new BSONError("corrupt bson message < 5 bytes long");const size=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(size<5||size>buffer2.length)throw new BSONError("corrupt bson message");const object=isArray?[]:{};let arrayIndex=0;const done=false;let isPossibleDBRef=isArray?false:null;const dataview=new DataView(buffer2.buffer,buffer2.byteOffset,buffer2.byteLength);while(!done){const elementType=buffer2[index++];if(elementType===0)break;let i=index;while(buffer2[i]!==0&&i=buffer2.byteLength)throw new BSONError("Bad BSON Document: illegal CString");const name=isArray?arrayIndex++:ByteUtils.toUTF8(buffer2.subarray(index,i));let shouldValidateKey=true;if(globalUTFValidation||utf8KeysSet.has(name)){shouldValidateKey=validationSetting}else{shouldValidateKey=!validationSetting}if(isPossibleDBRef!==false&&name[0]==="$"){isPossibleDBRef=allowedDBRefKeys.test(name)}let value;index=i+1;if(elementType===BSON_DATA_STRING){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}value=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize}else if(elementType===BSON_DATA_OID){const oid=ByteUtils.allocate(12);oid.set(buffer2.subarray(index,index+12));value=new ObjectId2(oid);index=index+12}else if(elementType===BSON_DATA_INT&&promoteValues===false){value=new Int32(buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24)}else if(elementType===BSON_DATA_INT){value=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24}else if(elementType===BSON_DATA_NUMBER&&promoteValues===false){value=new Double(dataview.getFloat64(index,true));index=index+8}else if(elementType===BSON_DATA_NUMBER){value=dataview.getFloat64(index,true);index=index+8}else if(elementType===BSON_DATA_DATE){const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;value=new Date(new Long(lowBits,highBits).toNumber())}else if(elementType===BSON_DATA_BOOLEAN){if(buffer2[index]!==0&&buffer2[index]!==1)throw new BSONError("illegal boolean type value");value=buffer2[index++]===1}else if(elementType===BSON_DATA_OBJECT){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;if(objectSize<=0||objectSize>buffer2.length-index)throw new BSONError("bad embedded document length in bson");if(raw){value=buffer2.slice(index,index+objectSize)}else{let objectOptions=options;if(!globalUTFValidation){objectOptions={...options,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,objectOptions,false)}index=index+objectSize}else if(elementType===BSON_DATA_ARRAY){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;let arrayOptions=options;const stopIndex=index+objectSize;if(fieldsAsRaw&&fieldsAsRaw[name]){arrayOptions={...options,raw:true}}if(!globalUTFValidation){arrayOptions={...arrayOptions,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,arrayOptions,true);index=index+objectSize;if(buffer2[index-1]!==0)throw new BSONError("invalid array terminator byte");if(index!==stopIndex)throw new BSONError("corrupted array bson")}else if(elementType===BSON_DATA_UNDEFINED){value=void 0}else if(elementType===BSON_DATA_NULL){value=null}else if(elementType===BSON_DATA_LONG){const dataview2=BSONDataView.fromUint8Array(buffer2.subarray(index,index+8));const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const long=new Long(lowBits,highBits);if(useBigInt64){value=dataview2.getBigInt64(0,true)}else if(promoteLongs&&promoteValues===true){value=long.lessThanOrEqual(JS_INT_MAX_LONG)&&long.greaterThanOrEqual(JS_INT_MIN_LONG)?long.toNumber():long}else{value=long}}else if(elementType===BSON_DATA_DECIMAL128){const bytes=ByteUtils.allocate(16);bytes.set(buffer2.subarray(index,index+16),0);index=index+16;value=new Decimal128(bytes)}else if(elementType===BSON_DATA_BINARY){let binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const totalBinarySize=binarySize;const subType=buffer2[index++];if(binarySize<0)throw new BSONError("Negative binary type element size found");if(binarySize>buffer2.byteLength)throw new BSONError("Binary type size larger than document size");if(buffer2["slice"]!=null){if(subType===Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(binarySize<0)throw new BSONError("Negative binary type element size found for subtype 0x02");if(binarySize>totalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySizetotalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySize=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;const optionsArray=new Array(regExpOptions.length);for(i=0;i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;value=new BSONRegExp(source,regExpOptions)}else if(elementType===BSON_DATA_SYMBOL){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const symbol=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=promoteValues?symbol:new BSONSymbol(symbol);index=index+stringSize}else if(elementType===BSON_DATA_TIMESTAMP){const i2=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);const t=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);value=new Timestamp({i:i2,t})}else if(elementType===BSON_DATA_MIN_KEY){value=new MinKey}else if(elementType===BSON_DATA_MAX_KEY){value=new MaxKey}else if(elementType===BSON_DATA_CODE){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=new Code(functionString);index=index+stringSize}else if(elementType===BSON_DATA_CODE_W_SCOPE){const totalSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(totalSize<4+4+4+1){throw new BSONError("code_w_scope total size shorter minimum expected length")}const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize;const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;const scopeObject=deserializeObject(buffer2,_index,options,false);index=index+objectSize;if(totalSize<4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too short, truncating scope")}if(totalSize>4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too long, clips outer document")}value=new Code(functionString,scopeObject)}else if(elementType===BSON_DATA_DBPOINTER){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0)throw new BSONError("bad string length in bson");if(validation!=null&&validation.utf8){if(!validateUtf8(buffer2,index,index+stringSize-1)){throw new BSONError("Invalid UTF-8 string in BSON document")}}const namespace=ByteUtils.toUTF8(buffer2.subarray(index,index+stringSize-1));index=index+stringSize;const oidBuffer=ByteUtils.allocate(12);oidBuffer.set(buffer2.subarray(index,index+12),0);const oid=new ObjectId2(oidBuffer);index=index+12;value=new DBRef(namespace,oid)}else{throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`)}if(name==="__proto__"){Object.defineProperty(object,name,{value,writable:true,enumerable:true,configurable:true})}else{object[name]=value}}if(size!==index-startIndex){if(isArray)throw new BSONError("corrupt array bson");throw new BSONError("corrupt object bson")}if(!isPossibleDBRef)return object;if(isDBRefLike(object)){const copy=Object.assign({},object);delete copy.$ref;delete copy.$id;delete copy.$db;return new DBRef(object.$ref,object.$id,object.$db,copy)}return object}function getValidatedString(buffer2,start,end,shouldValidateUtf8){const value=ByteUtils.toUTF8(buffer2.subarray(start,end));if(shouldValidateUtf8){for(let i=0;i>24&255;buffer2[index+2]=size+1>>16&255;buffer2[index+1]=size+1>>8&255;buffer2[index]=size+1&255;index=index+4+size;buffer2[index++]=0;return index}var NUMBER_SPACE=new DataView(new ArrayBuffer(8),0,8);var FOUR_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,4);var EIGHT_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,8);function serializeNumber(buffer2,key,value,index){const isNegativeZero=Object.is(value,-0);const type=!isNegativeZero&&Number.isSafeInteger(value)&&value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN?BSON_DATA_INT:BSON_DATA_NUMBER;if(type===BSON_DATA_INT){NUMBER_SPACE.setInt32(0,value,true)}else{NUMBER_SPACE.setFloat64(0,value,true)}const bytes=type===BSON_DATA_INT?FOUR_BYTE_VIEW_ON_NUMBER:EIGHT_BYTE_VIEW_ON_NUMBER;buffer2[index++]=type;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(bytes,index);index+=bytes.byteLength;return index}function serializeBigInt(buffer2,key,value,index){buffer2[index++]=BSON_DATA_LONG;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index+=numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setBigInt64(0,value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index+=EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;return index}function serializeNull(buffer2,key,_,index){buffer2[index++]=BSON_DATA_NULL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeBoolean(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BOOLEAN;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value?1:0;return index}function serializeDate(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DATE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const dateInMilis=Long.fromNumber(value.getTime());const lowBits=dateInMilis.getLowBits();const highBits=dateInMilis.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.source&&value.source.match(regexp)!=null){throw new BSONError("value "+value.source+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.source,index);buffer2[index++]=0;if(value.ignoreCase)buffer2[index++]=105;if(value.global)buffer2[index++]=115;if(value.multiline)buffer2[index++]=109;buffer2[index++]=0;return index}function serializeBSONRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.pattern.match(regexp)!=null){throw new BSONError("pattern "+value.pattern+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.pattern,index);buffer2[index++]=0;const sortedOptions=value.options.split("").sort().join("");index=index+ByteUtils.encodeUTF8Into(buffer2,sortedOptions,index);buffer2[index++]=0;return index}function serializeMinMax(buffer2,key,value,index){if(value===null){buffer2[index++]=BSON_DATA_NULL}else if(value._bsontype==="MinKey"){buffer2[index++]=BSON_DATA_MIN_KEY}else{buffer2[index++]=BSON_DATA_MAX_KEY}const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeObjectId(buffer2,key,value,index){buffer2[index++]=BSON_DATA_OID;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(isUint8Array(value.id)){buffer2.set(value.id.subarray(0,12),index)}else{throw new BSONError("object ["+JSON.stringify(value)+"] is not a valid ObjectId")}return index+12}function serializeBuffer(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=value.length;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=BSON_BINARY_SUBTYPE_DEFAULT;buffer2.set(value,index);index=index+size;return index}function serializeObject(buffer2,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined,path){if(path.has(value)){throw new BSONError("Cannot convert circular structure to BSON")}path.add(value);buffer2[index++]=Array.isArray(value)?BSON_DATA_ARRAY:BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const endIndex=serializeInto(buffer2,value,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);path.delete(value);return endIndex}function serializeDecimal128(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DECIMAL128;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(value.bytes.subarray(0,16),index);return index+16}function serializeLong(buffer2,key,value,index){buffer2[index++]=value._bsontype==="Long"?BSON_DATA_LONG:BSON_DATA_TIMESTAMP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const lowBits=value.getLowBits();const highBits=value.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeInt32(buffer2,key,value,index){value=value.valueOf();buffer2[index++]=BSON_DATA_INT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value&255;buffer2[index++]=value>>8&255;buffer2[index++]=value>>16&255;buffer2[index++]=value>>24&255;return index}function serializeDouble(buffer2,key,value,index){buffer2[index++]=BSON_DATA_NUMBER;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setFloat64(0,value.value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index=index+8;return index}function serializeFunction(buffer2,key,value,index){buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeCode(buffer2,key,value,index,checkKeys=false,depth=0,serializeFunctions=false,ignoreUndefined=true,path){if(value.scope&&typeof value.scope==="object"){buffer2[index++]=BSON_DATA_CODE_W_SCOPE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;const functionString=value.code;index=index+4;const codeSize=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=codeSize&255;buffer2[index+1]=codeSize>>8&255;buffer2[index+2]=codeSize>>16&255;buffer2[index+3]=codeSize>>24&255;buffer2[index+4+codeSize-1]=0;index=index+codeSize+4;const endIndex=serializeInto(buffer2,value.scope,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);index=endIndex-1;const totalSize=endIndex-startIndex;buffer2[startIndex++]=totalSize&255;buffer2[startIndex++]=totalSize>>8&255;buffer2[startIndex++]=totalSize>>16&255;buffer2[startIndex++]=totalSize>>24&255;buffer2[index++]=0}else{buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.code.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0}return index}function serializeBinary(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const data=value.buffer;let size=value.position;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY)size=size+4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=value.sub_type;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY){size=size-4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255}buffer2.set(data,index);index=index+value.position;return index}function serializeSymbol(buffer2,key,value,index){buffer2[index++]=BSON_DATA_SYMBOL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=ByteUtils.encodeUTF8Into(buffer2,value.value,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeDBRef(buffer2,key,value,index,depth,serializeFunctions,path){buffer2[index++]=BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;let output={$ref:value.collection||value.namespace,$id:value.oid};if(value.db!=null){output.$db=value.db}output=Object.assign(output,value.fields);const endIndex=serializeInto(buffer2,output,false,index,depth+1,serializeFunctions,true,path);const size=endIndex-startIndex;buffer2[startIndex++]=size&255;buffer2[startIndex++]=size>>8&255;buffer2[startIndex++]=size>>16&255;buffer2[startIndex++]=size>>24&255;return endIndex}function serializeInto(buffer2,object,checkKeys,startingIndex,depth,serializeFunctions,ignoreUndefined,path){if(path==null){if(object==null){buffer2[0]=5;buffer2[1]=0;buffer2[2]=0;buffer2[3]=0;buffer2[4]=0;return 5}if(Array.isArray(object)){throw new BSONError("serialize does not support an array as the root input")}if(typeof object!=="object"){throw new BSONError("serialize does not support non-object as the root input")}else if("_bsontype"in object&&typeof object._bsontype==="string"){throw new BSONError(`BSON types cannot be serialized as a document`)}else if(isDate(object)||isRegExp(object)||isUint8Array(object)||isAnyArrayBuffer(object)){throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`)}path=new Set}path.add(object);let index=startingIndex+4;if(Array.isArray(object)){for(let i=0;i>8&255;buffer2[startingIndex++]=size>>16&255;buffer2[startingIndex++]=size>>24&255;return index}function isBSONType(value){return value!=null&&typeof value==="object"&&"_bsontype"in value&&typeof value._bsontype==="string"}var keysToCodecs={$oid:ObjectId2,$binary:Binary,$uuid:Binary,$symbol:BSONSymbol,$numberInt:Int32,$numberDecimal:Decimal128,$numberDouble:Double,$numberLong:Long,$minKey:MinKey,$maxKey:MaxKey,$regex:BSONRegExp,$regularExpression:BSONRegExp,$timestamp:Timestamp};function deserializeValue(value,options={}){if(typeof value==="number"){const in32BitRange=value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN;const in64BitRange=value<=BSON_INT64_MAX&&value>=BSON_INT64_MIN;if(options.relaxed||options.legacy){return value}if(Number.isInteger(value)&&!Object.is(value,-0)){if(in32BitRange){return new Int32(value)}if(in64BitRange){if(options.useBigInt64){return BigInt(value)}return Long.fromNumber(value)}}return new Double(value)}if(value==null||typeof value!=="object")return value;if(value.$undefined)return null;const keys=Object.keys(value).filter(k=>k.startsWith("$")&&value[k]!=null);for(let i=0;ik.startsWith("$"));let valid=true;dollarKeys.forEach(k=>{if(["$ref","$id","$db"].indexOf(k)===-1)valid=false});if(valid)return DBRef.fromExtendedJSON(v)}return value}function serializeArray(array,options){return array.map((v,index)=>{options.seenObjects.push({propertyName:`index ${index}`,obj:null});try{return serializeValue(v,options)}finally{options.seenObjects.pop()}})}function getISOString(date){const isoStr=date.toISOString();return date.getUTCMilliseconds()!==0?isoStr:isoStr.slice(0,-5)+"Z"}function serializeValue(value,options){if(value instanceof Map||isMap(value)){const obj=Object.create(null);for(const[k,v]of value){if(typeof k!=="string"){throw new BSONError("Can only serialize maps with string keys")}obj[k]=v}return serializeValue(obj,options)}if((typeof value==="object"||typeof value==="function")&&value!==null){const index=options.seenObjects.findIndex(entry=>entry.obj===value);if(index!==-1){const props=options.seenObjects.map(entry=>entry.propertyName);const leadingPart=props.slice(0,index).map(prop=>`${prop} -> `).join("");const alreadySeen=props[index];const circularPart=" -> "+props.slice(index+1,props.length-1).map(prop=>`${prop} -> `).join("");const current=props[props.length-1];const leadingSpace=" ".repeat(leadingPart.length+alreadySeen.length/2);const dashes="-".repeat(circularPart.length+(alreadySeen.length+current.length)/2-1);throw new BSONError(`Converting circular structure to EJSON: - ${leadingPart}${alreadySeen}${circularPart}${current} - ${leadingSpace}\\${dashes}/`)}options.seenObjects[options.seenObjects.length-1].obj=value}if(Array.isArray(value))return serializeArray(value,options);if(value===void 0)return null;if(value instanceof Date||isDate(value)){const dateNum=value.getTime(),inRange=dateNum>-1&&dateNum<2534023188e5;if(options.legacy){return options.relaxed&&inRange?{$date:value.getTime()}:{$date:getISOString(value)}}return options.relaxed&&inRange?{$date:getISOString(value)}:{$date:{$numberLong:value.getTime().toString()}}}if(typeof value==="number"&&(!options.relaxed||!isFinite(value))){if(Number.isInteger(value)&&!Object.is(value,-0)){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return{$numberInt:value.toString()}}if(value>=BSON_INT64_MIN&&value<=BSON_INT64_MAX){return{$numberLong:value.toString()}}}return{$numberDouble:Object.is(value,-0)?"-0.0":value.toString()}}if(typeof value==="bigint"){if(!options.relaxed){return{$numberLong:BigInt.asIntN(64,value).toString()}}return Number(BigInt.asIntN(64,value))}if(value instanceof RegExp||isRegExp(value)){let flags=value.flags;if(flags===void 0){const match=value.toString().match(/[gimuy]*$/);if(match){flags=match[0]}}const rx=new BSONRegExp(value.source,flags);return rx.toExtendedJSON(options)}if(value!=null&&typeof value==="object")return serializeDocument(value,options);return value}var BSON_TYPE_MAPPINGS={Binary:o=>new Binary(o.value(),o.sub_type),Code:o=>new Code(o.code,o.scope),DBRef:o=>new DBRef(o.collection||o.namespace,o.oid,o.db,o.fields),Decimal128:o=>new Decimal128(o.bytes),Double:o=>new Double(o.value),Int32:o=>new Int32(o.value),Long:o=>Long.fromBits(o.low!=null?o.low:o.low_,o.low!=null?o.high:o.high_,o.low!=null?o.unsigned:o.unsigned_),MaxKey:()=>new MaxKey,MinKey:()=>new MinKey,ObjectId:o=>new ObjectId2(o),BSONRegExp:o=>new BSONRegExp(o.pattern,o.options),BSONSymbol:o=>new BSONSymbol(o.value),Timestamp:o=>Timestamp.fromBits(o.low,o.high)};function serializeDocument(doc,options){if(doc==null||typeof doc!=="object")throw new BSONError("not an object instance");const bsontype=doc._bsontype;if(typeof bsontype==="undefined"){const _doc={};for(const name of Object.keys(doc)){options.seenObjects.push({propertyName:name,obj:null});try{const value=serializeValue(doc[name],options);if(name==="__proto__"){Object.defineProperty(_doc,name,{value,writable:true,enumerable:true,configurable:true})}else{_doc[name]=value}}finally{options.seenObjects.pop()}}return _doc}else if(doc!=null&&typeof doc==="object"&&typeof doc._bsontype==="string"&&doc[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(isBSONType(doc)){let outDoc=doc;if(typeof outDoc.toExtendedJSON!=="function"){const mapper=BSON_TYPE_MAPPINGS[doc._bsontype];if(!mapper){throw new BSONError("Unrecognized or invalid _bsontype: "+doc._bsontype)}outDoc=mapper(outDoc)}if(bsontype==="Code"&&outDoc.scope){outDoc=new Code(outDoc.code,serializeValue(outDoc.scope,options))}else if(bsontype==="DBRef"&&outDoc.oid){outDoc=new DBRef(serializeValue(outDoc.collection,options),serializeValue(outDoc.oid,options),serializeValue(outDoc.db,options),serializeValue(outDoc.fields,options))}return outDoc.toExtendedJSON(options)}else{throw new BSONError("_bsontype must be a string, but was: "+typeof bsontype)}}function parse(text,options){const ejsonOptions={useBigInt64:options?.useBigInt64??false,relaxed:options?.relaxed??true,legacy:options?.legacy??false};return JSON.parse(text,(key,value)=>{if(key.indexOf("\0")!==-1){throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`)}return deserializeValue(value,ejsonOptions)})}function stringify(value,replacer,space,options){if(space!=null&&typeof space==="object"){options=space;space=0}if(replacer!=null&&typeof replacer==="object"&&!Array.isArray(replacer)){options=replacer;replacer=void 0;space=0}const serializeOptions=Object.assign({relaxed:true,legacy:false},options,{seenObjects:[{propertyName:"(root)",obj:null}]});const doc=serializeValue(value,serializeOptions);return JSON.stringify(doc,replacer,space)}function EJSONserialize(value,options){options=options||{};return JSON.parse(stringify(value,options))}function EJSONdeserialize(ejson,options){options=options||{};return parse(JSON.stringify(ejson),options)}var EJSON=Object.create(null);EJSON.parse=parse;EJSON.stringify=stringify;EJSON.serialize=EJSONserialize;EJSON.deserialize=EJSONdeserialize;Object.freeze(EJSON);var MAXSIZE=1024*1024*17;var buffer=ByteUtils.allocate(MAXSIZE);function setInternalBufferSize(size){if(buffer.lengthStructBackend,StructFrontend:()=>StructFrontend,Systems:()=>Systems,WebglLinePlotInfo:()=>void 0,WebglLinePlotProps:()=>void 0,WebglLinePlotUtil:()=>void 0,WebglLineProps:()=>void 0,algorithms:()=>algorithms,defaultSpecifiers:()=>defaultSpecifiers,genTimeSpecifiers:()=>genTimeSpecifiers,genTimestampFromString:()=>genTimestampFromString,getStringId:()=>getStringId,pseudoObjectId:()=>pseudoObjectId,randomId:()=>randomId,setSignalControls:()=>setSignalControls,toObjectId:()=>toObjectId,webglPlotRoutes:()=>webglPlotRoutes});module.exports=__toCommonJS(index_services_exports);var DataStructures_exports={};__export(DataStructures_exports,{AuthorizationStruct:()=>AuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}onCollectionSet=(type,collection)=>{};runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b){if(a.timestamp&&b.timestamp)return a.timestamp-b.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_,__,___=this.data){}onSorted(_=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var defaultSpecifiers=["now","minute","5 minutes","30 minutes","hour","6 hours","12 hours","day","3 days","week","2 weeks","month","6 months","year","5 years","decade"];function genTimeSpecifiers(specifiers=defaultSpecifiers){let result=["now"];specifiers.forEach(s=>{if(s!=="now")result.push(`last ${s}`);else result.push(s)});return result}function genTimestampFromString(specifier){const now=new Date;if(specifier==="now"){}else if(specifier==="last minute"){now.setMinutes(now.getMinutes()-1)}else if(specifier==="last hour"){now.setHours(now.getHours()-1)}else if(specifier==="last day"){now.setDate(now.getDate()-1)}else if(specifier==="last week"){now.setDate(now.getDate()-7)}else if(specifier==="last month"){now.setMonth(now.getMonth()-1)}else if(specifier==="last year"){now.setFullYear(now.getFullYear()-1)}else if(specifier==="last decade"){now.setFullYear(now.getFullYear()-1*10)}else if(specifier==="last century"){now.setFullYear(now.getFullYear()-1*100)}else if(specifier==="last millennium"){now.setFullYear(now.getFullYear()-1*1e3)}else if(specifier==="last microsecond"){now.setMilliseconds(now.getMilliseconds()-1)}else if(specifier==="last nanosecond"){now.setMilliseconds(now.getMilliseconds()-1*.001)}else if(specifier.startsWith("last")){const[,count,unit]=specifier.match(/last (\d+) (\w+)/)||[];if(count&&unit){const num=parseInt(count,10);if(unit.includes("minute")){now.setMinutes(now.getMinutes()-num)}else if(unit.includes("hour")){now.setHours(now.getHours()-num)}else if(unit.includes("day")){now.setDate(now.getDate()-num)}else if(unit.includes("week")){now.setDate(now.getDate()-num*7)}else if(unit.includes("month")){now.setMonth(now.getMonth()-num)}else if(unit.includes("year")){now.setFullYear(now.getFullYear()-num)}else if(unit.includes("decade")){now.setFullYear(now.getFullYear()-num*10)}else if(unit.includes("century")){now.setFullYear(now.getFullYear()-num*100)}else if(unit.includes("millennium")){now.setFullYear(now.getFullYear()-num*1e3)}else if(unit.includes("microsecond")){now.setMilliseconds(now.getMilliseconds()-num)}else if(unit.includes("nanosecond")){now.setMilliseconds(now.getMilliseconds()-num*.001)}}}return now.getTime()}var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{name="structs";currentUser;tablet=new DataTablet;collections=this.tablet.collections;id=randomId();useAccessTokens=false;useRefreshTokens=false;constructor(options,user){super(options);this.load(this);if(options.useAccessTokens)this.useAccessTokens=options.useAccessTokens;if(options.useRefreshTokens)this.useRefreshTokens=options.useRefreshTokens;if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}getToken(user){if(this.useAccessTokens)return user.accessToken;else if(this.useRefreshTokens)return user.refreshToken}setupUser=async(userinfo,callback=currentUser=>{})=>{if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u;let newu=false;if(!user||!user._id){u=this.userStruct(userinfo,false);newu=true;let wasSet=await this.setUser(u);let structs=this.getLocalData(void 0,{"ownerId":u._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u)}else{u=user;let toUpdate={_id:userinfo._id,ownerId:userinfo._id};let struct=this.userStruct(userinfo,false);for(const key in struct){if(userinfo[key]&&user[key]!==userinfo[key]){toUpdate[key]=userinfo[key];user[key]=userinfo[key]}else if(struct[key]&&!user[key]){toUpdate[key]=struct[key];user[key]=struct[key]}}if(Object.keys(toUpdate).length>2)await this.setUser(toUpdate);if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u)}else{let data=await this.getAllUserData(u._id,void 0,[genTimestampFromString("last day"),Date.now()]);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u)}if(u){if(this.currentUser)Object.assign(this.currentUser,u);else this.currentUser=u;callback(this.currentUser);return this.currentUser}else{callback(u);return u}};baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}this.onResult(data)};structNotification=()=>{this.checkForNotifications()};structDeleted=struct=>{this.deleteLocalData([struct])};onResult=data=>{};randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}addStruct=async(structType="struct",props={},parentUser,parentStruct,updateServer=true)=>{let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct};getUser=async(info="",basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info,basicInfo,this.getToken(this.currentUser)]});callback(res);return res}};queryUsers=async(info,skip,limit,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"queryUsers",args:[this.currentUser._id,info,skip,limit,void 0,this.getToken(this.currentUser)]});callback(res);return res}};getUsers=async(ids=[],basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids,basicInfo]});callback(res);return res}};getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};getAllUserData=async(ownerId,excluded=[],timeRange,callback=this.baseServerCallback)=>{if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[this.currentUser._id,ownerId,excluded,timeRange,this.getToken(this.currentUser)]});callback(res);return res}};query=async(collection,mongoQuery={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!mongoQuery)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,mongoQuery,findOne,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByTimeRange(collection,timeRange,ownerId,limit=0,skip=0,key){let query={};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}let range={$gt:timeRange[0],$lt:timeRange[1]};if(key)query[key]=range;else query.timestamp=range;return this.getData(collection,ownerId,query,limit,skip)}getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct?.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id,this.getToken(this.currentUser)];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};setUser=async(userStruct,callback=this.baseServerCallback)=>{if(userStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};updateServerData=this.setData;deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteUser=async(userId=this.currentUser._id,deleteData,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId,deleteData,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setGroup=async(groupStruct,callback=this.baseServerCallback)=>{if(groupStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setAuthorization=async(authorizationStruct,callback=this.baseServerCallback)=>{if(authorizationStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=await this.currentUser.request({route:"deleteAuthorization",args:[this.currentUser._id,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent){toUpdate=[parent];allReplies.forEach(r=>{let idx=parent.replies?.indexOf(r._id);if(idx>-1)parent.replies.splice(idx,1);let idx2=parent.comments?.indexOf(r._id);if(idx2>-1)parent.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent?._id){let idx=replyTo.replies?.indexOf(parent._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u=authorizationStruct.authorizerId;if(u){return new Promise(async resolve=>{this.getUser(u,true,async data=>{let res;if(!collection)res=await this.getAllUserData(u,["notification"],void 0,callback);else res=await this.getData(collection,u,searchDict,limit,skip,callback);resolve(res);callback(res)})})}else return void 0};getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u=o.authorizerId;if(u){let data;let user=await this.getUser(u,true,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u,["notification"],void 0,callback);else data=await this.getData(collection,u,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return{};let result={};let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result[a.authorizedId]=true});return result};getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b)=>a*(typeof b==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(void 0,{_id:struct});if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop]===""||copy[prop].constructor.name==="Map"||copy[prop].constructor.name==="Set"||typeof copy[prop]==="function")delete copy[prop];else if(Array.isArray(copy[prop])&©[prop].length===0)delete copy[prop];else if(typeof copy[prop]==="object"&&Object.keys(copy[prop]).length===0)delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(!user.name&&user.firstName)user.name=user.firstName+" "+user.lastName;else if(user.name&&!user.firstName){let split=user.name.split(" ");user.firstName=split[0];user.lastName=split[split.length-1]}if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e15);user._id=user.id;user.ownerId=user.id;let dummy=DataStructures_exports.ProfileStruct();for(const prop in props){if(Object.keys(dummy).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};addEvent=async(parentUser,author="",event="",notes="",startTime=void 0,endTime=void 0,grade=void 0,value=void 0,units=void 0,location=void 0,attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.value=value;newEvent.units=units;newEvent.users=users;newEvent.location=location;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};addChatroom=async(parentUser,authorId="",message="",attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=void 0,updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res}};var import_bson=__toESM(require_bson());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectId=str2=>{return typeof str2==="string"&&str2.length===24?new import_bson.ObjectId(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{name="structs";debug=false;db;users={};collections={};mode="local";useAuths=true;useAccessTokens=false;useRefreshTokens=false;accessTokens=new Map;refreshTokens=new Map;constructor(options,dboptions){super(options);this.load(this);if(dboptions){this.initDB(dboptions)}}initDB=dboptions=>{this.db=dboptions.db;if(dboptions?.users)this.users=dboptions.users;if(dboptions.mode)this.mode=dboptions.mode;if(dboptions?.collections)this.collections=dboptions.collections;if(dboptions.debug)this.debug=dboptions.debug;if(dboptions.useAccessTokens)this.useAccessTokens=dboptions.useAccessTokens;if(dboptions.useRefreshTokens)this.useRefreshTokens=dboptions.useRefreshTokens;if("useAuths"in dboptions)this.useAuths=dboptions.useAuths;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})};query=async(requestingUserId,collection,queryObj,findOne,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip,token)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token);if(passed)return res}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}));return data}};getUser=async(requestingUserId,lookupId,basicInfo,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId,void 0,basicInfo,token)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:void 0};else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};setUser=async(requestingUserId,struct,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(struct.accessToken){this.accessTokens.set(requestingUserId,token)}if(struct.refreshToken){this.refreshTokens.set(requestingUserId,struct.refreshToken)}delete struct.accessToken;delete struct.refreshToken;delete user.accessToken;delete user.refreshToken;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct,token)}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};getUsersByIds=async(requestingUserId,userIds,basicInfo)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds,basicInfo)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct){if(basicInfo)data.push({_id:struct._id,username:struct.username,firstName:struct.firstName,lastName:struct.lastName,fullName:struct.fullName,pictureUrl:struct.pictureUrl});else data.push(struct)}}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};deleteUser=async(requestingUserId,userId,deleteData,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId,deleteData,token)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};setData=async(requestingUserId,structs,notify,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify,token)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};getData=async(requestingUserId,collection,ownerId,dict,limit,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};getDataByIds=async(requestingUserId,structIds,ownerId,collection,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};getAllData=async(requestingUserId,ownerId,excludedCollections,timeRange,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections,timeRange,token)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};deleteData=async(requestingUserId,structIds,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds,token)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};deleteGroup=async(requestingUserId,groupId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId,token)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};getAuthorizations=async(requestingUserId,ownerId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId,token)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};deleteAuthorization=async(requestingUserId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId,token)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};getToken=user=>{return this.useAccessTokens?this.accessTokens.get(user._id):this.useRefreshTokens?this.refreshTokens.get(user._id):void 0};notificationStruct=(parentStruct={})=>{let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct};checkToNotify=async(user,structs=[],mode=this.mode)=>{if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(struct.ownerId&&user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+struct.ownerId;newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+usr;newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d=>auths.push(d))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id)+"_"+auth.authorizedId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications,true,this.getToken(user))}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid]?.sendAll({route:"structNotification",args:true})}return true}else return false};queryMongo=async(user,collection,queryObj={},findOne=false,skip=0,token)=>{if(!collection&&!queryObj)return void 0;else if(findOne){let res=await this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token)}if(passed)return res;else return void 0}else{let res=this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];let arr=await res.toArray();if(arr.length>0){let passed=!this.useAuths;let checkedAuth="";for(const s of arr){if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)structs.push(s)}}return structs}};setMongoData=async(user,structs=[],notify=true,token)=>{let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:toObjectId(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType?struct.structType:"data").insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectId(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false};setMongoUser=async(user,struct,token)=>{if(struct._id){const _id=toObjectId(struct._id);let usersearch={_id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));copy._id=_id;if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false};setGroup=async(user,struct,mode=this.mode,token)=>{if(struct?._id){let uid=getStringId(user._id);let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(uid)<0))return false;if(uid!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u=>{allusers.push({email:u},{id:u},{username:u})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});let arr=cursor.toArray();if(arr.length>0){arr.forEach(user2=>{users[uid]=user2;ids[uid]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u=users[id];if(struct.admins[getStringId(u._id)]||struct.admins[u.email]||struct.admins[u.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u._id)])admins[getStringId(u._id)]=true}if(struct.peers[getStringId(u._id)]||struct.peers[u.email]||struct.peers[u.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u._id)])peers[getStringId(u._id)]=true}if(struct.clients[getStringId(u._id)]||struct.clients[u.email]||struct.clients[u.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u._id)])clients[getStringId(u._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType?struct.structType:"data").findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectId(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false};getMongoUser=(user,info="",requireAuth=true,basicInfo=false,token)=>{return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectId(info)})}catch(e){console.log("error creating ObjectId with ",info)}let u=await this.collections.profile.instance.findOne({$or:query});if(!u||u==null)resolve(void 0);else{u._id=getStringId(u._id);if(!u.ownerId)u.ownerId=u._id;if(basicInfo){if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}let stripped={username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName,pictureUrl:u.pictureUrl,_id:u._id};u=stripped;resolve({user:u})}else if(requireAuth){if(getStringId(user._id)!==u._id||getStringId(user._id)===u._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u,"READ",token);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u._id});let aarr=await auths.toArray();if(auths.toArray().length>0){aarr.forEach(d=>authorizations.push(d))}let gs=this.collections.group.instance.find({users:{$all:[u._id]}});let arr=await gs.toArray();let groups=[];if(arr.length>0){arr.forEach(d=>groups.push(d))}resolve({user:u,authorizations,groups})}else{if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}resolve({user:u})}}})};queryUsers=(user,info="",limit=0,skip=0,requireAuth=false,token)=>{if(typeof user==="string")user=this.users[user];if(!user)return;return new Promise(async resolve=>{let q={$regex:`^${info}`,$options:"i"};const query=[{email:q},{username:q},{firstName:q},{lastName:q},{name:q}];let arr;if(this.mode.includes("mongo")){let users=this.collections.profile.instance.find({$or:query},{projection:shallowqueryDummy}).skip(skip);if(limit>0)users.limit(limit);await users;arr=await users.toArray()}else{arr=[];for(let i=0;i{arr.push({firstName:u.firstName,lastName:u.lastName,fullName:u.fullName,username:u.username,pictureUrl:u.pictureUrl})})}else if(dat)arr.push({firstName:dat.firstName,lastName:dat.lastName,fullName:dat.fullName,username:dat.username,pictureUrl:dat.pictureUrl})}}if(requireAuth){let result=[];let strid=getStringId(user._id);for(let i=0;i{let usrs=[];userIds.forEach(u=>{try{usrs.push({_id:toObjectId(u)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});let arr=await users.toArray();if(arr.length>0){arr.forEach(u=>{if(basicInfo){found.push({username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName,pictureUrl:u.pictureUrl,_id:u._id})}else found.push(u)})}}return found};getMongoUsersByRole=async(user,role)=>{let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];let arr=await users.toArray();if(arr.length>0){arr.forEach(u=>{found.push(u)})}return found};getMongoDataByIds=async(user,structIds,ownerId,collection,token)=>{let uid=getStringId(user._id);if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectId(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});let arr=await cursor.toArray();if(arr.length>0){let passed=true;let checkedAuth="";for(let i=0;i0){let passed=true;let checkedAuth="";arr.forEach(async s=>{if(!s?.ownerId)passed=true;else if((uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}};getMongoData=async(user,collection,ownerId,dict={},limit=0,skip=0,token)=>{if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectId(dict._id);let uid=getStringId(user._id);let structs=[];let passed=true;let checkedAuth="";let cursor;if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip)}else if(collection&&Object.keys(dict).length>0){if(ownerId)dict.ownerId=ownerId;cursor=await this.db.collection(collection).find(dict).sort({$natural:-1}).skip(skip)}if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{cursor=await this.db.collection(name).find(dict).sort({$natural:-1}).skip(skip);;if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i{let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let query={ownerId};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1]);query.timestamp={$gt:timeRange[0],$lt:timeRange[1]}}let cursor=this.db.collection(name).find(query);let arr=await cursor.toArray();let count=arr.length;for(let k=0;k{let structs=[];if(structs.length>0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectId(ref._id)});if(struct){let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs};getMongoAuthorizations=async(user,ownerId=getStringId(user._id),authId="",token)=>{let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectId(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0],"READ",token);if(!passed)return void 0}return auths};getMongoGroups=async(user,userId=getStringId(user._id),groupId="")=>{let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId),users:{$all:[userId]}}))}catch{}}return groups};deleteMongoData=async(user,structRefs=[],token)=>{let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectId(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=notifications.toArray().length;for(let i=0;i{let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){await this.db.collection(struct.structType?struct.structType:"data").deleteOne({_id:toObjectId(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})}}}));return true};deleteMongoUser=async(user,userId,deleteData,token)=>{if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u,"WRITE",token);if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(deleteData){for(const key in this.collections){this.collections[key].instance.deleteMany({ownerId:userId});this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}})}}if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId]?.sendAll({route:"structDeleted",args:{_id:userId,structType:"profile"}});return true};deleteMongoGroup=async(user,groupId,token)=>{let s=await this.collections.group.instance.findOne({_id:toObjectId(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u=>{this.users[u]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}})})}await this.collections.group.instance.deleteOne({_id:toObjectId(groupId)});return true}else return false};deleteMongoAuthorization=async(user,authId,token)=>{let s=await this.collections.authorization.instance.findOne({_id:toObjectId(authId)});let uid=getStringId(user._id);if(s){if(uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectId(s.associatedAuthId)});if(s.authorizerId!==uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}});else if(s.authorizedId!==uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}})}await this.collections.authorization.instance.deleteOne({_id:toObjectId(authId)});if(s.authorizerId===uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});else if(s.authorizedId===uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});return true}else return false};setAuthorization=async(user,authStruct,token)=>{let u1,u2;let mmode=this.mode.includes("mongo");if(mmode){u1=(await this.getMongoUser(user,authStruct.authorizedId,false)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,false)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})?.[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})?.[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.name)authStruct.authorizedName=u1.name;else if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u1.name)authStruct.authorizedName=u1.name;else if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE",token);if(!passed)return false}let auths=[];if(mmode){let s=await this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d=>auths.push(d))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d=>{if(d.authorizerId===authStruct.authorizerId)auths.push(d)})}}let otherAuthset;if(Array.isArray(auths)){for(let i=0;i{if(typeof user==="string"){if(this.users[user])user=this.users[user];else user={_id:user}}if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}return true}}if(this.useAccessTokens){if(!this.accessTokens.get(user._id)||this.accessTokens.get(user._id)!==token){return false}}else if(this.useRefreshTokens){if(!this.refreshTokens.get(user._id)||this.refreshTokens.get(user._id)!==token){return false}}let auth1,auth2;if(this.mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});if(!auth1)return false;auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(struct.ownerId)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(struct.ownerId)}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed};wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};overwriteLocalData=structs=>{if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}};setLocalData=structs=>{let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)};getLocalData=(collection,query)=>{let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result};deleteLocalData=struct=>{if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var shallowqueryDummy=DataStructures_exports.ProfileStruct();for(const key in shallowqueryDummy){if(key==="username"||key==="lastName"||key==="firstName"||key==="name"||key==="_id"||key==="pictureUrl")shallowqueryDummy[key]=1;else delete shallowqueryDummy[key]}var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u=(dot11*dot02-dot01*dot12)*_denom;let v=(dot00*dot12-dot01*dot02)*_denom;if(u>=0&&v>=0&&u+v<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v=>{let magnitude=0;for(const key in v){magnitude+=v[key]*v[key]}return Math.sqrt(magnitude)},normalize:v=>{let magnitude=Systems.collision.magnitude(v);let _mag=magnitude?1/magnitude:0;let vn={};for(const key in v){vn[key]=v[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new(void 0);return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new(void 0);return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` - - - - - - - - - - - - - - `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` - - - - - - - - - - - - - - - `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var Math2=class _Math2{constructor(){}static TWO_PI=Math.PI*2;static C=299792458;static G=66743e-15;static h=662607015e-42;static R=8314.32;static Ra=287;static H=69.3;static kbar=1054571817e-43;static kB=1380649e-29;static ke=89875517923e-1;static me=91093837015e-41;static mp=167262192369e-38;static mn=167492749804e-38;static P0=101325;static T0=288.15;static p0=1.225;static Na=60220978e16;static y=1.405;static M0=28.96643;static g0=9.80665;static Re=6378100;static B=1458e-9;static S=110.4;static Sigma=365e-12;static imgkernels={edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]};static HSLToRGB=(h,s,l,scalar=255)=>{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean=void 0)=>{let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean=this.mean(arr);let std=this.std(arr,mean);let z=new Array(arr.length);for(let i=0;ia+(b-mean)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean=this.mean(arr);let std=this.std(arr,mean);return populationMean?std/populationMean:std/mean};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y)=>acc+Math.pow(y-meanY,2),0);const ssResidual=observed.reduce((acc,y,i)=>acc+Math.pow(y-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x2)=>sum+x2,0);const sumY=yCoords.reduce((sum,y)=>sum+y,0);const sumXY=xCoords.reduce((sum,x2,i)=>sum+x2*yCoords[i],0);const sumX2=xCoords.reduce((sum,x2)=>sum+x2*x2,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{return vec.map((v,i)=>v-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v,i)=>v/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v,i)=>v+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v,i)=>v-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v,i)=>v/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x2,y,z)=>{var r=Math.sqrt(x2*x2+y*y+z*z);var theta=Math.atan2(y,x2);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y=x2;return y},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x2=Math.cos(t);return x2},yFunc=t=>{let y=Math.sin(t);return y},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u,v)=>u,yFunc=(u,v)=>v,zFunc=(u,v)=>u+v,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u=rangeU[0];u{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value,index)=>{const row=Array(values.length).fill(0);row[index]=value;return row})};static householderMatrix=v=>{const size=v.length;const vvT=v.map(rowVal=>v.map(colVal=>rowVal*colVal));const vTv=this.normalize(v)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A,B)=>{return A.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value=>(value-min)/(max-min))};static garroteThreshold=(data,value)=>{return data.map(x2=>{if(Math.abs(x2)<=value){return 0}else{return x2-value*value/x2}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean1=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v,i)=>(v-mean1)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x2,x2),this.cov1d(x2,y),this.cov1d(x2,z)],[this.cov1d(y,x2),this.cov1d(y,y),this.cov1d(y,z)],[this.cov1d(z,x2),this.cov1d(z,y),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v=>v-mean)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N=signalA.length;const M=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x2=arr.filter((element,index)=>{return index%factor===0});return x2};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y=>y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x2)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A,numIter=100)=>{let b=Array(A.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A[0].length>A.length){A=this.transpose(A)}const m=A.length;const n=A[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x2):this.normalize(x2);const u=this.vecsub(x2,e);const normU=this.normalize(u);const v=u.map(val=>val/normU);const Qk=this.householderMatrix(v);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{ax=ax*this.accelConstant;ay=ay*this.accelConstant;az=az*this.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+this.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+this.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v,i)=>{return apass(v,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-this.lastGyroTime;this.lastGyroTime=timestamp;gx=gx*this.gyroConstant+this.gyroXError;gy=gy*this.gyroConstant+this.gyroYError;gz=gz*this.gyroConstant+this.gyroZError;this.gyroXAngle+=gx*elapsed;this.gyroYAngle+=gy*elapsed;this.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:this.gyroXAngle,pitch:this.gyroYAngle,yaw:this.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v,i)=>{if(result){let r=gpass(v,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(this.gyroXAngle||this.gyroYAngle||this.gyroZAngle){result.roll=result.roll*.04+this.gyroXAngle*.96;result.pitch=result.pitch*.04+this.gyroYAngle*.96;result.yaw=this.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-this.lastAccelTime;this.lastAccelTime=timestamp;this.px+=result2.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*.005555555555);this.py+=result2.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*.005555555555);this.pz+=result2.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*.005555555555);result2.px=this.px;result2.py=this.py;result2.pz=this.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{type;freq;sps;Q;dbGain;a0=0;a1=0;a2=0;b0=0;b1=0;b2=0;x1=0;x2=0;y1=0;y2=0;constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A+A);this[type](A,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A,sn,cs,alpha,beta){this.b0=1+alpha*A;this.b1=-2*cs;this.b2=1-alpha*A;this.a0=1+alpha/A;this.a1=-2*cs;this.a2=1-alpha/A}lowshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1-(A-1)*cs+beta*sn);this.b1=2*A*(A-1-(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1+(A+1)*cs+beta*sn;this.a1=2*(A-1+(A+1)*cs);this.a2=A+1+(A-1)*cs-beta*sn}highshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1+(A-1)*cs+beta*sn);this.b1=2*A*(A-1+(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1-(A+1)*cs-beta*sn;this.a1=2*(A-1-(A+1)*cs);this.a2=A+1-(A-1)*cs-beta*sn}applyFilter(signal_step){let y=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y;return y}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10,__onconnected:function(){if(!this.lowpass){let freq=this.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;this.lowpass=new Biquad("lowpass",this.maxFreq,this.sps);this.peakFinderWindow=Math.floor(this.sps/this.maxFreq);if(this.peakFinderWindow%2===0)this.peakFinderWindow+=1;if(this.peakFinderWindow<5)this.peakFinderWindow=5;this.midpoint=Math.round(this.peakFinderWindow*.5)}},__operator:function(data){if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*this.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){this.refdata.push(amplitude)}this.timestamp.push(timestamp);let beat;if(this.refdata.length>this.peakFinderWindow){this.refdata.shift();this.timestamp.shift()}this.smoothed.push(this.lowpass.applyFilter(this.refdata[this.refdata.length-1]));if(this.smoothed.length>this.peakFinderWindow){this.smoothed.shift()}if(this.smoothed.length===this.peakFinderWindow){if(Math2.isExtrema(this.smoothed,"valley")){this.valleys.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}else if(Math2.isExtrema(this.smoothed,"peak")){this.peaks.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}if(this.valleys.length>2&&this.peaks.length>2){if(this.valleys[this.valleys.length-1].timestamp1&&this.valley_distances.length>1){if(this.lastPeakthis.peak_distances[this.peak_distances.length-1].timestamp){let bpm,change=0;if(this.beats.length<1){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].distance+this.valley_distances[this.valley_distances.length-1].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-1].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].dt+this.valley_distances[this.valley_distances.length-1].dt));change=Math.abs(bpm-this.beats[this.beats.length-1].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-1].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-1].peak0-this.valley_distances[this.valley_distances.length-1].peak0,height1:this.peak_distances[this.peak_distances.length-1].peak1-this.valley_distances[this.valley_distances.length-1].peak1};this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}else{let bpm,change=0;if(this.beats.length<2){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-2].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance));change=Math.abs(bpm-this.beats[this.beats.length-2].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-2].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0,height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1};if(Array.isArray(beat.timestamp))beat.timestamp=beat.timestamp[0];this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}}}if(this.peaks.length>this.limit){this.peaks.shift()}if(this.valleys.length>this.limit){this.valleys.shift()}if(this.peak_distances.length>this.limit){this.peak_distances.shift()}if(this.valley_distances.length>this.limit){this.valley_distances.shift()}if(this.beats.length>this.limit){this.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)result=data.red.map((v,i)=>{return pass(v+data.ir[i],data.timestamp[i])}).filter(v=>{if(v)return true});else result=data.red.map((v,i)=>{return pass(v,data.timestamp[i])}).filter(v=>{if(v)return true});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v,i)=>{return pass(v,data.timestamp[i])}).filter(v=>{if(v)return true});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v,i)=>{return pass(v,data.timestamp[i])}).filter(v=>{if(v)return true});return result}}};var blink_detect={sps:250,intervals:{},watch:["0"],tolerance:.2,__onconnected:node=>{node.watch.forEach(ch=>node.intervals[ch]={lowpass:new Biquad("lowpass",20,node.sps),filtered:[],averaged:[]})},__operator:function(data){let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=this.intervals[key].lowpass.applyFilter(n);this.intervals[key].filtered.push(next);this.intervals[key].averaged.push(next);if(this.intervals[key].filtered.length>checkCt){if(this.intervals[key].averaged.length>averageCt){this.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(this.intervals[key].averaged);if(Math.abs(Math.min(...this.intervals[key].filtered))>Math.abs(mean)+this.tolerance){this.intervals[key].filtered.length=0;passed=true;found[key]=true}}else this.intervals[key].filtered.shift()}};for(const key in this.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var ArrayManip=class _ArrayManip{static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y=>{if(clamp){if(ymax)y=max}return y*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y=>{if(clamp){if(ymax)y=max}return 2*((y-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,...newEntries.slice(newEntries.length-len))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d={};data.forEach((arr,i)=>{d[i]=arr});data=d;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}static bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target};spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var rechk=/^([<>])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v,o,c)=>String.fromCharCode(...new Uint8Array(v.buffer,v.byteOffset+o,c));var rts=(v,o,c,s)=>new Uint8Array(v.buffer,v.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v,o,c)=>str(v,o+1,Math.min(v.getUint8(o),c-1));var tsp=(v,o,c,s)=>{v.setUint8(o,s.length);rts(v,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v=>str(v,o,1),p:(v,c2)=>rts(v,o,1,c2)})],"?":c=>[c,1,o=>({u:v=>Boolean(v.getUint8(o)),p:(v,B)=>v.setUint8(o,B)})],b:c=>[c,1,o=>({u:v=>v.getInt8(o),p:(v,b)=>v.setInt8(o,b)})],B:c=>[c,1,o=>({u:v=>v.getUint8(o),p:(v,B)=>v.setUint8(o,B)})],h:c=>[c,2,o=>({u:v=>v.getInt16(o,le),p:(v,h)=>v.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v=>v.getUint16(o,le),p:(v,H)=>v.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v=>v.getInt32(o,le),p:(v,i)=>v.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v=>v.getUint32(o,le),p:(v,I)=>v.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v=>v.getFloat32(o,le),p:(v,f)=>v.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v=>v.getFloat64(o,le),p:(v,d)=>v.setFloat64(o,d,le)})],s:c=>[1,c,o=>({u:v=>str(v,o,c),p:(v,s)=>rts(v,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v=>pst(v,o,c),p:(v,s)=>tsp(v,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var ByteParser=class _ByteParser extends ArrayManip{static codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y){return[y&255,y>>8&255]}static bytesToInt24(x0,x1,x2){let int24=(255&x0)<<16|(255&x1)<<8|255&x2;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x2){return x0*65536+x1*256+x2}static Uint24ToBytes(y){return[y&255,y>>8&255,y>>16&255]}static bytesToInt32(x0,x1,x2,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x2)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x2,x3){return x0*16777216+x1*65536+x2*256+x3}static Uint32ToBytes(y){return[y&255,y>>8&255,y>>16&255,y>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M=pattern.length;if(M===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R=256;var rightmost_positions=new Int32Array(R);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v=new DataView(arrb,offs|0);return fns.map(f=>f.u(v))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var rms={sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{},__operator:function(data){this.watch.forEach(key=>{if(data[key]){if(!this.data[key]){if(Array.isArray(data[key])){this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0])}else this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key])}ByteParser.circularBuffer(this.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){this.rms.timestamp=data.timestamp[data.timestamp.length-1]}else this.rms.timestamp=data.timestamp}else this.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(this.watch.map(async key=>{if(this.data[key])this.rms[key]=Math.sqrt(Math.abs(this.data[key].reduce((p,v,i)=>p+v*v)/this.data[key].length));else delete this.rms[key]}));res(this.rms)})}};var circularBuffer2d={bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false,__onconnected:function(node){for(const key in node.watch){node.data[key]=new Array(node.bufferSize).fill(0)}},__operator:function(data){let buffer2d=[];this.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(this.data[key],data[key]);buffer2d.push(this.data[key])}});return buffer2d}};var algorithms={beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d};algorithms["breath"].maxFreq=.2;0&&(module.exports={StructBackend,StructFrontend,Systems,WebglLinePlotInfo,WebglLinePlotProps,WebglLinePlotUtil,WebglLineProps,algorithms,defaultSpecifiers,genTimeSpecifiers,genTimestampFromString,getStringId,pseudoObjectId,randomId,setSignalControls,toObjectId,webglPlotRoutes}); diff --git a/src/extras/dist/index.storage.services.d.ts b/src/extras/dist/index.storage.services.d.ts deleted file mode 100644 index 7a6a642f..00000000 --- a/src/extras/dist/index.storage.services.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './storage/csv'; -export * from './storage/BFSUtils'; -export * from './storage/BFS_CSV'; diff --git a/src/extras/dist/index.storage.services.esm.js b/src/extras/dist/index.storage.services.esm.js deleted file mode 100644 index 9d23db51..00000000 --- a/src/extras/dist/index.storage.services.esm.js +++ /dev/null @@ -1,16 +0,0 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browserfs=__commonJS({"node_modules/browserfs/dist/browserfs.js"(exports,module){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["BrowserFS"]=factory();else root["BrowserFS"]=factory()})(exports,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module2=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module2.exports,module2,module2.exports,__webpack_require__);module2.loaded=true;return module2.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module2,exports2,__webpack_require__){(function(Buffer2,global,module3,process){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var buffer=__webpack_require__(2);var path=__webpack_require__(9);var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2["EPERM"]=1]="EPERM";ErrorCode2[ErrorCode2["ENOENT"]=2]="ENOENT";ErrorCode2[ErrorCode2["EIO"]=5]="EIO";ErrorCode2[ErrorCode2["EBADF"]=9]="EBADF";ErrorCode2[ErrorCode2["EACCES"]=13]="EACCES";ErrorCode2[ErrorCode2["EBUSY"]=16]="EBUSY";ErrorCode2[ErrorCode2["EEXIST"]=17]="EEXIST";ErrorCode2[ErrorCode2["ENOTDIR"]=20]="ENOTDIR";ErrorCode2[ErrorCode2["EISDIR"]=21]="EISDIR";ErrorCode2[ErrorCode2["EINVAL"]=22]="EINVAL";ErrorCode2[ErrorCode2["EFBIG"]=27]="EFBIG";ErrorCode2[ErrorCode2["ENOSPC"]=28]="ENOSPC";ErrorCode2[ErrorCode2["EROFS"]=30]="EROFS";ErrorCode2[ErrorCode2["ENOTEMPTY"]=39]="ENOTEMPTY";ErrorCode2[ErrorCode2["ENOTSUP"]=95]="ENOTSUP"})(ErrorCode||(ErrorCode={}));var ErrorStrings={};ErrorStrings[ErrorCode.EPERM]="Operation not permitted.";ErrorStrings[ErrorCode.ENOENT]="No such file or directory.";ErrorStrings[ErrorCode.EIO]="Input/output error.";ErrorStrings[ErrorCode.EBADF]="Bad file descriptor.";ErrorStrings[ErrorCode.EACCES]="Permission denied.";ErrorStrings[ErrorCode.EBUSY]="Resource busy or locked.";ErrorStrings[ErrorCode.EEXIST]="File exists.";ErrorStrings[ErrorCode.ENOTDIR]="File is not a directory.";ErrorStrings[ErrorCode.EISDIR]="File is a directory.";ErrorStrings[ErrorCode.EINVAL]="Invalid argument.";ErrorStrings[ErrorCode.EFBIG]="File is too big.";ErrorStrings[ErrorCode.ENOSPC]="No space left on disk.";ErrorStrings[ErrorCode.EROFS]="Cannot modify a read-only file system.";ErrorStrings[ErrorCode.ENOTEMPTY]="Directory is not empty.";ErrorStrings[ErrorCode.ENOTSUP]="Operation is not supported.";var ApiError=function(Error2){function ApiError2(type,message,path$$1){if(message===void 0)message=ErrorStrings[type];Error2.call(this,message);this.syscall="";this.errno=type;this.code=ErrorCode[type];this.path=path$$1;this.stack=new Error2().stack;this.message="Error: "+this.code+": "+message+(this.path?", '"+this.path+"'":"")}if(Error2)ApiError2.__proto__=Error2;ApiError2.prototype=Object.create(Error2&&Error2.prototype);ApiError2.prototype.constructor=ApiError2;ApiError2.fromJSON=function fromJSON(json){var err=new ApiError2(0);err.errno=json.errno;err.code=json.code;err.path=json.path;err.stack=json.stack;err.message=json.message;return err};ApiError2.fromBuffer=function fromBuffer(buffer$$1,i2){if(i2===void 0)i2=0;return ApiError2.fromJSON(JSON.parse(buffer$$1.toString("utf8",i2+4,i2+4+buffer$$1.readUInt32LE(i2))))};ApiError2.FileError=function FileError(code,p){return new ApiError2(code,ErrorStrings[code],p)};ApiError2.ENOENT=function ENOENT(path$$1){return this.FileError(ErrorCode.ENOENT,path$$1)};ApiError2.EEXIST=function EEXIST(path$$1){return this.FileError(ErrorCode.EEXIST,path$$1)};ApiError2.EISDIR=function EISDIR(path$$1){return this.FileError(ErrorCode.EISDIR,path$$1)};ApiError2.ENOTDIR=function ENOTDIR(path$$1){return this.FileError(ErrorCode.ENOTDIR,path$$1)};ApiError2.EPERM=function EPERM(path$$1){return this.FileError(ErrorCode.EPERM,path$$1)};ApiError2.ENOTEMPTY=function ENOTEMPTY(path$$1){return this.FileError(ErrorCode.ENOTEMPTY,path$$1)};ApiError2.prototype.toString=function toString(){return this.message};ApiError2.prototype.toJSON=function toJSON(){return{errno:this.errno,code:this.code,path:this.path,stack:this.stack,message:this.message}};ApiError2.prototype.writeToBuffer=function writeToBuffer(buffer$$1,i2){if(buffer$$1===void 0)buffer$$1=Buffer2.alloc(this.bufferSize());if(i2===void 0)i2=0;var bytesWritten=buffer$$1.write(JSON.stringify(this.toJSON()),i2+4);buffer$$1.writeUInt32LE(bytesWritten,i2);return buffer$$1};ApiError2.prototype.bufferSize=function bufferSize(){return 4+Buffer2.byteLength(JSON.stringify(this.toJSON()))};return ApiError2}(Error);var api_error=Object.freeze({get ErrorCode(){return ErrorCode},ErrorStrings,ApiError});var ActionType;(function(ActionType2){ActionType2[ActionType2["NOP"]=0]="NOP";ActionType2[ActionType2["THROW_EXCEPTION"]=1]="THROW_EXCEPTION";ActionType2[ActionType2["TRUNCATE_FILE"]=2]="TRUNCATE_FILE";ActionType2[ActionType2["CREATE_FILE"]=3]="CREATE_FILE"})(ActionType||(ActionType={}));var FileFlag=function FileFlag2(flagStr){this.flagStr=flagStr;if(FileFlag2.validFlagStrs.indexOf(flagStr)<0){throw new ApiError(ErrorCode.EINVAL,"Invalid flag: "+flagStr)}};FileFlag.getFileFlag=function getFileFlag(flagStr){if(FileFlag.flagCache.hasOwnProperty(flagStr)){return FileFlag.flagCache[flagStr]}return FileFlag.flagCache[flagStr]=new FileFlag(flagStr)};FileFlag.prototype.getFlagString=function getFlagString(){return this.flagStr};FileFlag.prototype.isReadable=function isReadable(){return this.flagStr.indexOf("r")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isWriteable=function isWriteable(){return this.flagStr.indexOf("w")!==-1||this.flagStr.indexOf("a")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isTruncating=function isTruncating(){return this.flagStr.indexOf("w")!==-1};FileFlag.prototype.isAppendable=function isAppendable(){return this.flagStr.indexOf("a")!==-1};FileFlag.prototype.isSynchronous=function isSynchronous(){return this.flagStr.indexOf("s")!==-1};FileFlag.prototype.isExclusive=function isExclusive(){return this.flagStr.indexOf("x")!==-1};FileFlag.prototype.pathExistsAction=function pathExistsAction(){if(this.isExclusive()){return ActionType.THROW_EXCEPTION}else if(this.isTruncating()){return ActionType.TRUNCATE_FILE}else{return ActionType.NOP}};FileFlag.prototype.pathNotExistsAction=function pathNotExistsAction(){if((this.isWriteable()||this.isAppendable())&&this.flagStr!=="r+"){return ActionType.CREATE_FILE}else{return ActionType.THROW_EXCEPTION}};FileFlag.flagCache={};FileFlag.validFlagStrs=["r","r+","rs","rs+","w","wx","w+","wx+","a","ax","a+","ax+"];var FileType;(function(FileType2){FileType2[FileType2["FILE"]=32768]="FILE";FileType2[FileType2["DIRECTORY"]=16384]="DIRECTORY";FileType2[FileType2["SYMLINK"]=40960]="SYMLINK"})(FileType||(FileType={}));var Stats=function Stats2(itemType,size,mode,atime,mtime,ctime){if(atime===void 0)atime=new Date;if(mtime===void 0)mtime=new Date;if(ctime===void 0)ctime=new Date;this.size=size;this.atime=atime;this.mtime=mtime;this.ctime=ctime;this.dev=0;this.ino=0;this.rdev=0;this.nlink=1;this.blksize=4096;this.uid=0;this.gid=0;this.birthtime=new Date(0);this.fileData=null;if(!mode){switch(itemType){case FileType.FILE:this.mode=420;break;case FileType.DIRECTORY:default:this.mode=511}}else{this.mode=mode}this.blocks=Math.ceil(size/512);if(this.mode<4096){this.mode|=itemType}};Stats.fromBuffer=function fromBuffer(buffer$$1){var size=buffer$$1.readUInt32LE(0),mode=buffer$$1.readUInt32LE(4),atime=buffer$$1.readDoubleLE(8),mtime=buffer$$1.readDoubleLE(16),ctime=buffer$$1.readDoubleLE(24);return new Stats(mode&61440,size,mode&4095,new Date(atime),new Date(mtime),new Date(ctime))};Stats.prototype.toBuffer=function toBuffer(){var buffer$$1=Buffer2.alloc(32);buffer$$1.writeUInt32LE(this.size,0);buffer$$1.writeUInt32LE(this.mode,4);buffer$$1.writeDoubleLE(this.atime.getTime(),8);buffer$$1.writeDoubleLE(this.mtime.getTime(),16);buffer$$1.writeDoubleLE(this.ctime.getTime(),24);return buffer$$1};Stats.prototype.clone=function clone(){return new Stats(this.mode&61440,this.size,this.mode&4095,this.atime,this.mtime,this.ctime)};Stats.prototype.isFile=function isFile(){return(this.mode&61440)===FileType.FILE};Stats.prototype.isDirectory=function isDirectory(){return(this.mode&61440)===FileType.DIRECTORY};Stats.prototype.isSymbolicLink=function isSymbolicLink(){return(this.mode&61440)===FileType.SYMLINK};Stats.prototype.chmod=function chmod(mode){this.mode=this.mode&61440|mode};Stats.prototype.isSocket=function isSocket(){return false};Stats.prototype.isBlockDevice=function isBlockDevice(){return false};Stats.prototype.isCharacterDevice=function isCharacterDevice(){return false};Stats.prototype.isFIFO=function isFIFO(){return false};var wrapCb=function(cb,numArgs){return cb};function assertRoot(fs4){if(fs4){return fs4}throw new ApiError(ErrorCode.EIO,"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)")}function normalizeMode(mode,def){switch(typeof mode){case"number":return mode;case"string":var trueMode=parseInt(mode,8);if(!isNaN(trueMode)){return trueMode}return def;default:return def}}function normalizeTime(time){if(time instanceof Date){return time}else if(typeof time==="number"){return new Date(time*1e3)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid time.")}}function normalizePath(p){if(p.indexOf("\0")>=0){throw new ApiError(ErrorCode.EINVAL,"Path must be a string without null bytes.")}else if(p===""){throw new ApiError(ErrorCode.EINVAL,"Path must not be empty.")}return path.resolve(p)}function normalizeOptions(options,defEnc,defFlag,defMode){switch(typeof options){case"object":return{encoding:typeof options["encoding"]!=="undefined"?options["encoding"]:defEnc,flag:typeof options["flag"]!=="undefined"?options["flag"]:defFlag,mode:normalizeMode(options["mode"],defMode)};case"string":return{encoding:options,flag:defFlag,mode:defMode};default:return{encoding:defEnc,flag:defFlag,mode:defMode}}}function nopCb(){}var FS=function FS2(){this.F_OK=0;this.R_OK=4;this.W_OK=2;this.X_OK=1;this.root=null;this.fdMap={};this.nextFd=100};FS.prototype.initialize=function initialize3(rootFS){if(!rootFS.constructor.isAvailable()){throw new ApiError(ErrorCode.EINVAL,"Tried to instantiate BrowserFS with an unavailable file system.")}return this.root=rootFS};FS.prototype._toUnixTimestamp=function _toUnixTimestamp(time){if(typeof time==="number"){return time}else if(time instanceof Date){return time.getTime()/1e3}throw new Error("Cannot parse time: "+time)};FS.prototype.getRootFS=function getRootFS(){if(this.root){return this.root}else{return null}};FS.prototype.rename=function rename(oldPath,newPath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).rename(normalizePath(oldPath),normalizePath(newPath),newCb)}catch(e){newCb(e)}};FS.prototype.renameSync=function renameSync(oldPath,newPath){assertRoot(this.root).renameSync(normalizePath(oldPath),normalizePath(newPath))};FS.prototype.exists=function exists2(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).exists(normalizePath(path$$1),newCb)}catch(e){return newCb(false)}};FS.prototype.existsSync=function existsSync(path$$1){try{return assertRoot(this.root).existsSync(normalizePath(path$$1))}catch(e){return false}};FS.prototype.stat=function stat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),false,newCb)}catch(e){return newCb(e)}};FS.prototype.statSync=function statSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),false)};FS.prototype.lstat=function lstat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),true,newCb)}catch(e){return newCb(e)}};FS.prototype.lstatSync=function lstatSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),true)};FS.prototype.truncate=function truncate(path$$1,arg2,cb){if(arg2===void 0)arg2=0;if(cb===void 0)cb=nopCb;var len=0;if(typeof arg2==="function"){cb=arg2}else if(typeof arg2==="number"){len=arg2}var newCb=wrapCb(cb,1);try{if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncate(normalizePath(path$$1),len,newCb)}catch(e){return newCb(e)}};FS.prototype.truncateSync=function truncateSync(path$$1,len){if(len===void 0)len=0;if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncateSync(normalizePath(path$$1),len)};FS.prototype.unlink=function unlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).unlink(normalizePath(path$$1),newCb)}catch(e){return newCb(e)}};FS.prototype.unlinkSync=function unlinkSync(path$$1){return assertRoot(this.root).unlinkSync(normalizePath(path$$1))};FS.prototype.open=function open(path$$1,flag,arg2,cb){var this$1=this;if(cb===void 0)cb=nopCb;var mode=normalizeMode(arg2,420);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{assertRoot(this.root).open(normalizePath(path$$1),FileFlag.getFileFlag(flag),mode,function(e,file){if(file){newCb(e,this$1.getFdForFile(file))}else{newCb(e)}})}catch(e){newCb(e)}};FS.prototype.openSync=function openSync(path$$1,flag,mode){if(mode===void 0)mode=420;return this.getFdForFile(assertRoot(this.root).openSync(normalizePath(path$$1),FileFlag.getFileFlag(flag),normalizeMode(mode,420)))};FS.prototype.readFile=function readFile2(filename,arg2,cb){if(arg2===void 0)arg2={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg2,null,"r",null);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{var flag=FileFlag.getFileFlag(options["flag"]);if(!flag.isReadable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading."))}return assertRoot(this.root).readFile(normalizePath(filename),options.encoding,flag,newCb)}catch(e){return newCb(e)}};FS.prototype.readFileSync=function readFileSync(filename,arg2){if(arg2===void 0)arg2={};var options=normalizeOptions(arg2,null,"r",null);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isReadable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading.")}return assertRoot(this.root).readFileSync(normalizePath(filename),options.encoding,flag)};FS.prototype.writeFile=function writeFile2(filename,data,arg3,cb){if(arg3===void 0)arg3={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","w",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing."))}return assertRoot(this.root).writeFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){return newCb(e)}};FS.prototype.writeFileSync=function writeFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","w",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing.")}return assertRoot(this.root).writeFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.appendFile=function appendFile3(filename,data,arg3,cb){if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","a",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending."))}assertRoot(this.root).appendFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){newCb(e)}};FS.prototype.appendFileSync=function appendFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","a",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending.")}return assertRoot(this.root).appendFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.fstat=function fstat(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{var file=this.fd2file(fd);file.stat(newCb)}catch(e){newCb(e)}};FS.prototype.fstatSync=function fstatSync(fd){return this.fd2file(fd).statSync()};FS.prototype.close=function close(fd,cb){var this$1=this;if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).close(function(e){if(!e){this$1.closeFd(fd)}newCb(e)})}catch(e){newCb(e)}};FS.prototype.closeSync=function closeSync(fd){this.fd2file(fd).closeSync();this.closeFd(fd)};FS.prototype.ftruncate=function ftruncate(fd,arg2,cb){if(cb===void 0)cb=nopCb;var length=typeof arg2==="number"?arg2:0;cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(length<0){throw new ApiError(ErrorCode.EINVAL)}file.truncate(length,newCb)}catch(e){newCb(e)}};FS.prototype.ftruncateSync=function ftruncateSync(fd,len){if(len===void 0)len=0;var file=this.fd2file(fd);if(len<0){throw new ApiError(ErrorCode.EINVAL)}file.truncateSync(len)};FS.prototype.fsync=function fsync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).sync(newCb)}catch(e){newCb(e)}};FS.prototype.fsyncSync=function fsyncSync(fd){this.fd2file(fd).syncSync()};FS.prototype.fdatasync=function fdatasync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).datasync(newCb)}catch(e){newCb(e)}};FS.prototype.fdatasyncSync=function fdatasyncSync(fd){this.fd2file(fd).datasyncSync()};FS.prototype.write=function write(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var buffer$$1,offset,length,position=null;if(typeof arg2==="string"){var encoding="utf8";switch(typeof arg3){case"function":cb=arg3;break;case"number":position=arg3;encoding=typeof arg4==="string"?arg4:"utf8";cb=typeof arg5==="function"?arg5:cb;break;default:cb=typeof arg4==="function"?arg4:typeof arg5==="function"?arg5:cb;return cb(new ApiError(ErrorCode.EINVAL,"Invalid arguments."))}buffer$$1=Buffer2.from(arg2,encoding);offset=0;length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null;cb=typeof arg5==="function"?arg5:cb}var newCb=wrapCb(cb,3);try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.write(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.writeSync=function writeSync(fd,arg2,arg3,arg4,arg5){var buffer$$1,offset=0,length,position;if(typeof arg2==="string"){position=typeof arg3==="number"?arg3:null;var encoding=typeof arg4==="string"?arg4:"utf8";offset=0;buffer$$1=Buffer2.from(arg2,encoding);length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}return file.writeSync(buffer$$1,offset,length,position)};FS.prototype.read=function read(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var position,offset,length,buffer$$1,newCb;if(typeof arg2==="number"){length=arg2;position=arg3;var encoding=arg4;cb=typeof arg5==="function"?arg5:cb;offset=0;buffer$$1=Buffer2.alloc(length);newCb=wrapCb(function(err,bytesRead,buf){if(err){return cb(err)}cb(err,buf.toString(encoding),bytesRead)},3)}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5;newCb=wrapCb(cb,3)}try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.read(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.readSync=function readSync(fd,arg2,arg3,arg4,arg5){var shenanigans=false;var buffer$$1,offset,length,position,encoding="utf8";if(typeof arg2==="number"){length=arg2;position=arg3;encoding=arg4;offset=0;buffer$$1=Buffer2.alloc(length);shenanigans=true}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}var rv=file.readSync(buffer$$1,offset,length,position);if(!shenanigans){return rv}else{return[buffer$$1.toString(encoding),rv]}};FS.prototype.fchown=function fchown(fd,uid,gid,callback){if(callback===void 0)callback=nopCb;var newCb=wrapCb(callback,1);try{this.fd2file(fd).chown(uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.fchownSync=function fchownSync(fd,uid,gid){this.fd2file(fd).chownSync(uid,gid)};FS.prototype.fchmod=function fchmod(fd,mode,cb){var newCb=wrapCb(cb,1);try{var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmod(numMode,newCb)}catch(e){newCb(e)}};FS.prototype.fchmodSync=function fchmodSync(fd,mode){var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmodSync(numMode)};FS.prototype.futimes=function futimes(fd,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(typeof atime==="number"){atime=new Date(atime*1e3)}if(typeof mtime==="number"){mtime=new Date(mtime*1e3)}file.utimes(atime,mtime,newCb)}catch(e){newCb(e)}};FS.prototype.futimesSync=function futimesSync(fd,atime,mtime){this.fd2file(fd).utimesSync(normalizeTime(atime),normalizeTime(mtime))};FS.prototype.rmdir=function rmdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).rmdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.rmdirSync=function rmdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).rmdirSync(path$$1)};FS.prototype.mkdir=function mkdir(path$$1,mode,cb){if(cb===void 0)cb=nopCb;if(typeof mode==="function"){cb=mode;mode=511}var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).mkdir(path$$1,mode,newCb)}catch(e){newCb(e)}};FS.prototype.mkdirSync=function mkdirSync(path$$1,mode){assertRoot(this.root).mkdirSync(normalizePath(path$$1),normalizeMode(mode,511))};FS.prototype.readdir=function readdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readdirSync=function readdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readdirSync(path$$1)};FS.prototype.link=function link(srcpath,dstpath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).link(srcpath,dstpath,newCb)}catch(e){newCb(e)}};FS.prototype.linkSync=function linkSync(srcpath,dstpath){srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).linkSync(srcpath,dstpath)};FS.prototype.symlink=function symlink(srcpath,dstpath,arg3,cb){if(cb===void 0)cb=nopCb;var type=typeof arg3==="string"?arg3:"file";cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{if(type!=="file"&&type!=="dir"){return newCb(new ApiError(ErrorCode.EINVAL,"Invalid type: "+type))}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).symlink(srcpath,dstpath,type,newCb)}catch(e){newCb(e)}};FS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(!type){type="file"}else if(type!=="file"&&type!=="dir"){throw new ApiError(ErrorCode.EINVAL,"Invalid type: "+type)}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).symlinkSync(srcpath,dstpath,type)};FS.prototype.readlink=function readlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readlink(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readlinkSync=function readlinkSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readlinkSync(path$$1)};FS.prototype.chown=function chown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,false,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.chownSync=function chownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,false,uid,gid)};FS.prototype.lchown=function lchown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,true,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.lchownSync=function lchownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,true,uid,gid)};FS.prototype.chmod=function chmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),false,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.chmodSync=function chmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}path$$1=normalizePath(path$$1);assertRoot(this.root).chmodSync(path$$1,false,numMode)};FS.prototype.lchmod=function lchmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),true,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.lchmodSync=function lchmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<1){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmodSync(normalizePath(path$$1),true,numMode)};FS.prototype.utimes=function utimes(path$$1,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).utimes(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime),newCb)}catch(e){newCb(e)}};FS.prototype.utimesSync=function utimesSync(path$$1,atime,mtime){assertRoot(this.root).utimesSync(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime))};FS.prototype.realpath=function realpath(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;var cache=typeof arg2==="object"?arg2:{};cb=typeof arg2==="function"?arg2:nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).realpath(path$$1,cache,newCb)}catch(e){newCb(e)}};FS.prototype.realpathSync=function realpathSync(path$$1,cache){if(cache===void 0)cache={};path$$1=normalizePath(path$$1);return assertRoot(this.root).realpathSync(path$$1,cache)};FS.prototype.watchFile=function watchFile(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.unwatchFile=function unwatchFile(filename,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.watch=function watch(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.access=function access(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.accessSync=function accessSync(path$$1,mode){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createReadStream=function createReadStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createWriteStream=function createWriteStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.wrapCallbacks=function wrapCallbacks(cbWrapper){wrapCb=cbWrapper};FS.prototype.getFdForFile=function getFdForFile(file){var fd=this.nextFd++;this.fdMap[fd]=file;return fd};FS.prototype.fd2file=function fd2file(fd){var rv=this.fdMap[fd];if(rv){return rv}else{throw new ApiError(ErrorCode.EBADF,"Invalid file descriptor.")}};FS.prototype.closeFd=function closeFd(fd){delete this.fdMap[fd]};FS.Stats=Stats;var fs3=new FS;var _fsMock={};var fsProto=FS.prototype;Object.keys(fsProto).forEach(function(key){if(typeof fs3[key]==="function"){_fsMock[key]=function(){return fs3[key].apply(fs3,arguments)}}else{_fsMock[key]=fs3[key]}});_fsMock["changeFSModule"]=function(newFs){fs3=newFs};_fsMock["getFSModule"]=function(){return fs3};_fsMock["FS"]=FS;function _min(d0,d1,d2,bx,ay){return d0d2?d2+1:d0+1:bx===ay?d1:d1+1}function levenshtein(a,b){if(a===b){return 0}if(a.length>b.length){var tmp=a;a=b;b=tmp}var la=a.length;var lb=b.length;while(la>0&&a.charCodeAt(la-1)===b.charCodeAt(lb-1)){la--;lb--}var offset=0;while(offsetdd?dd+1:dy$1+1:bx0$1===vector[la+y$2]?d0:d0+1;d0=dy$1}}return dd}function deprecationMessage(print,fsName,opts){if(print){console.warn("["+fsName+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+fsName+".Create("+JSON.stringify(opts)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}}var isIE=typeof navigator!=="undefined"&&!!(/(msie) ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||navigator.userAgent.indexOf("Trident")!==-1);var isWebWorker=typeof window==="undefined";function fail(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function mkdirpSync(p,mode,fs4){if(!fs4.existsSync(p)){mkdirpSync(path.dirname(p),mode,fs4);fs4.mkdirSync(p,mode)}}function buffer2ArrayBuffer(buff){var u8=buffer2Uint8array(buff),u8offset=u8.byteOffset,u8Len=u8.byteLength;if(u8offset===0&&u8Len===u8.buffer.byteLength){return u8.buffer}else{return u8.buffer.slice(u8offset,u8offset+u8Len)}}function buffer2Uint8array(buff){if(buff instanceof Uint8Array){return buff}else{return new Uint8Array(buff)}}function arrayish2Buffer(arr){if(arr instanceof Buffer2){return arr}else if(arr instanceof Uint8Array){return uint8Array2Buffer(arr)}else{return Buffer2.from(arr)}}function uint8Array2Buffer(u8){if(u8 instanceof Buffer2){return u8}else if(u8.byteOffset===0&&u8.byteLength===u8.buffer.byteLength){return arrayBuffer2Buffer(u8.buffer)}else{return Buffer2.from(u8.buffer,u8.byteOffset,u8.byteLength)}}function arrayBuffer2Buffer(ab){return Buffer2.from(ab)}function copyingSlice(buff,start,end){if(start===void 0)start=0;if(end===void 0)end=buff.length;if(start<0||end<0||end>buff.length||start>end){throw new TypeError("Invalid slice bounds on buffer of length "+buff.length+": ["+start+", "+end+"]")}if(buff.length===0){return emptyBuffer()}else{var u8=buffer2Uint8array(buff),s0=buff[0],newS0=(s0+1)%255;buff[0]=newS0;if(u8[0]===newS0){u8[0]=s0;return uint8Array2Buffer(u8.slice(start,end))}else{buff[0]=s0;return uint8Array2Buffer(u8.subarray(start,end))}}}var emptyBuff=null;function emptyBuffer(){if(emptyBuff){return emptyBuff}return emptyBuff=Buffer2.alloc(0)}function bufferValidator(v,cb){if(Buffer2.isBuffer(v)){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"option must be a Buffer."))}}function checkOptions(fsType,opts,cb){var optsInfo=fsType.Options;var fsName=fsType.Name;var pendingValidators=0;var callbackCalled=false;var loopEnded=false;function validatorCallback(e){if(!callbackCalled){if(e){callbackCalled=true;cb(e)}pendingValidators--;if(pendingValidators===0&&loopEnded){cb()}}}var loop=function(optName2){if(optsInfo.hasOwnProperty(optName2)){var opt=optsInfo[optName2];var providedValue=opts[optName2];if(providedValue===void 0||providedValue===null){if(!opt.optional){var incorrectOptions=Object.keys(opts).filter(function(o){return!(o in optsInfo)}).map(function(a){return{str:a,distance:levenshtein(optName2,a)}}).filter(function(o){return o.distance<5}).sort(function(a,b){return a.distance-b.distance});if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Required option '"+optName2+"' not provided."+(incorrectOptions.length>0?" You provided unrecognized option '"+incorrectOptions[0].str+"'; perhaps you meant to type '"+optName2+"'.":"")+"\nOption description: "+opt.description))}}}else{var typeMatches=false;if(Array.isArray(opt.type)){typeMatches=opt.type.indexOf(typeof providedValue)!==-1}else{typeMatches=typeof providedValue===opt.type}if(!typeMatches){if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Value provided for option "+optName2+" is not the proper type. Expected "+(Array.isArray(opt.type)?"one of {"+opt.type.join(", ")+"}":opt.type)+", but received "+typeof providedValue+"\nOption description: "+opt.description))}}else if(opt.validator){pendingValidators++;opt.validator(providedValue,validatorCallback)}}}};for(var optName in optsInfo){var returned=loop(optName);if(returned)return returned.v}loopEnded=true;if(pendingValidators===0&&!callbackCalled){cb()}}var BFSUtils=Object.freeze({deprecationMessage,isIE,isWebWorker,fail,mkdirpSync,buffer2ArrayBuffer,buffer2Uint8array,arrayish2Buffer,uint8Array2Buffer,arrayBuffer2Buffer,copyingSlice,emptyBuffer,bufferValidator,checkOptions});var BFSEmscriptenStreamOps=function BFSEmscriptenStreamOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenStreamOps.prototype.open=function open(stream){var path$$1=this.fs.realPath(stream.node);var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)){stream.nfd=this.nodefs.openSync(path$$1,this.fs.flagsToPermissionString(stream.flags))}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.close=function close(stream){var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)&&stream.nfd){this.nodefs.closeSync(stream.nfd)}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.read=function read(stream,buffer$$1,offset,length,position){try{return this.nodefs.readSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.write=function write(stream,buffer$$1,offset,length,position){try{return this.nodefs.writeSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.llseek=function llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(this.FS.isFile(stream.node.mode)){try{var stat=this.nodefs.fstatSync(stream.nfd);position+=stat.size}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}}if(position<0){throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL)}stream.position=position;return position};var BFSEmscriptenNodeOps=function BFSEmscriptenNodeOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenNodeOps.prototype.getattr=function getattr(node){var path$$1=this.fs.realPath(node);var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return{dev:stat.dev,ino:stat.ino,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}};BFSEmscriptenNodeOps.prototype.setattr=function setattr(node,attr){var path$$1=this.fs.realPath(node);try{if(attr.mode!==void 0){this.nodefs.chmodSync(path$$1,attr.mode);node.mode=attr.mode}if(attr.timestamp!==void 0){var date=new Date(attr.timestamp);this.nodefs.utimesSync(path$$1,date,date)}}catch(e){if(!e.code){throw e}if(e.code!=="ENOTSUP"){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}if(attr.size!==void 0){try{this.nodefs.truncateSync(path$$1,attr.size)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}};BFSEmscriptenNodeOps.prototype.lookup=function lookup(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);var mode=this.fs.getMode(path$$1);return this.fs.createNode(parent,name,mode)};BFSEmscriptenNodeOps.prototype.mknod=function mknod(parent,name,mode,dev){var node=this.fs.createNode(parent,name,mode,dev);var path$$1=this.fs.realPath(node);try{if(this.FS.isDir(node.mode)){this.nodefs.mkdirSync(path$$1,node.mode)}else{this.nodefs.writeFileSync(path$$1,"",{mode:node.mode})}}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return node};BFSEmscriptenNodeOps.prototype.rename=function rename(oldNode,newDir,newName){var oldPath=this.fs.realPath(oldNode);var newPath=this.PATH.join2(this.fs.realPath(newDir),newName);try{this.nodefs.renameSync(oldPath,newPath);oldNode.name=newName;oldNode.parent=newDir}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.unlink=function unlink(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.unlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.rmdir=function rmdir(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.rmdirSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readdir=function readdir(node){var path$$1=this.fs.realPath(node);try{var contents=this.nodefs.readdirSync(path$$1);contents.push(".","..");return contents}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.symlink=function symlink(parent,newName,oldPath){var newPath=this.PATH.join2(this.fs.realPath(parent),newName);try{this.nodefs.symlinkSync(oldPath,newPath)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readlink=function readlink(node){var path$$1=this.fs.realPath(node);try{return this.nodefs.readlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};var BFSEmscriptenFS=function BFSEmscriptenFS2(_FS,_PATH,_ERRNO_CODES,nodefs){if(_FS===void 0)_FS=self["FS"];if(_PATH===void 0)_PATH=self["PATH"];if(_ERRNO_CODES===void 0)_ERRNO_CODES=self["ERRNO_CODES"];if(nodefs===void 0)nodefs=_fsMock;this.flagsToPermissionStringMap={0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"};this.nodefs=nodefs;this.FS=_FS;this.PATH=_PATH;this.ERRNO_CODES=_ERRNO_CODES;this.node_ops=new BFSEmscriptenNodeOps(this);this.stream_ops=new BFSEmscriptenStreamOps(this)};BFSEmscriptenFS.prototype.mount=function mount(m){return this.createNode(null,"/",this.getMode(m.opts.root),0)};BFSEmscriptenFS.prototype.createNode=function createNode(parent,name,mode,dev){var FS2=this.FS;if(!FS2.isDir(mode)&&!FS2.isFile(mode)&&!FS2.isLink(mode)){throw new FS2.ErrnoError(this.ERRNO_CODES.EINVAL)}var node=FS2.createNode(parent,name,mode);node.node_ops=this.node_ops;node.stream_ops=this.stream_ops;return node};BFSEmscriptenFS.prototype.getMode=function getMode(path$$1){var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return stat.mode};BFSEmscriptenFS.prototype.realPath=function realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return this.PATH.join.apply(null,parts)};BFSEmscriptenFS.prototype.flagsToPermissionString=function flagsToPermissionString(flags){var parsedFlags=typeof flags==="string"?parseInt(flags,10):flags;parsedFlags&=8191;if(parsedFlags in this.flagsToPermissionStringMap){return this.flagsToPermissionStringMap[parsedFlags]}else{return flags}};BFSEmscriptenFS.prototype.getNodeFS=function getNodeFS(){return this.nodefs};BFSEmscriptenFS.prototype.getFS=function getFS(){return this.FS};BFSEmscriptenFS.prototype.getPATH=function getPATH(){return this.PATH};BFSEmscriptenFS.prototype.getERRNO_CODES=function getERRNO_CODES(){return this.ERRNO_CODES};var BaseFileSystem=function BaseFileSystem2(){};BaseFileSystem.prototype.supportsLinks=function supportsLinks(){return false};BaseFileSystem.prototype.diskSpace=function diskSpace(p,cb){cb(0,0)};BaseFileSystem.prototype.openFile=function openFile(p,flag,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFile=function createFile(p,flag,mode,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.open=function open(p,flag,mode,cb){var this$1=this;var mustBeFile=function(e,stats){if(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.stat(path.dirname(p),false,function(e2,parentStats){if(e2){cb(e2)}else if(parentStats&&!parentStats.isDirectory()){cb(ApiError.ENOTDIR(path.dirname(p)))}else{this$1.createFile(p,flag,mode,cb)}});case ActionType.THROW_EXCEPTION:return cb(ApiError.ENOENT(p));default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}else{if(stats&&stats.isDirectory()){return cb(ApiError.EISDIR(p))}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:return cb(ApiError.EEXIST(p));case ActionType.TRUNCATE_FILE:return this$1.openFile(p,flag,function(e2,fd){if(e2){cb(e2)}else if(fd){fd.truncate(0,function(){fd.sync(function(){cb(null,fd)})})}else{fail()}});case ActionType.NOP:return this$1.openFile(p,flag,cb);default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}};this.stat(p,false,mustBeFile)};BaseFileSystem.prototype.rename=function rename(oldPath,newPath,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.renameSync=function renameSync(oldPath,newPath){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.stat=function stat(p,isLstat,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.statSync=function statSync(p,isLstat){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openFileSync=function openFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFileSync=function createFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openSync=function openSync(p,flag,mode){var stats;try{stats=this.statSync(p,false)}catch(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:var parentStats=this.statSync(path.dirname(p),false);if(!parentStats.isDirectory()){throw ApiError.ENOTDIR(path.dirname(p))}return this.createFileSync(p,flag,mode);case ActionType.THROW_EXCEPTION:throw ApiError.ENOENT(p);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}}if(stats.isDirectory()){throw ApiError.EISDIR(p)}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:throw ApiError.EEXIST(p);case ActionType.TRUNCATE_FILE:this.unlinkSync(p);return this.createFileSync(p,flag,stats.mode);case ActionType.NOP:return this.openFileSync(p,flag,mode);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}};BaseFileSystem.prototype.unlink=function unlink(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.unlinkSync=function unlinkSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.rmdir=function rmdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.rmdirSync=function rmdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.mkdir=function mkdir(p,mode,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.mkdirSync=function mkdirSync(p,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.readdir=function readdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.readdirSync=function readdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.exists=function exists2(p,cb){this.stat(p,null,function(err){cb(!err)})};BaseFileSystem.prototype.existsSync=function existsSync(p){try{this.statSync(p,true);return true}catch(e){return false}};BaseFileSystem.prototype.realpath=function realpath(p,cache,cb){if(this.supportsLinks()){var splitPath=p.split(path.sep);for(var i2=0;i2this._buffer.length){var buf=Buffer2.alloc(len-this._buffer.length,0);this.writeSync(buf,0,buf.length,this._buffer.length);if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}return}this._stat.size=len;var newBuff=Buffer2.alloc(len);this._buffer.copy(newBuff,0,0,len);this._buffer=newBuff;if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}};PreloadFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){this._dirty=true;if(position===void 0||position===null){position=this.getPos()}if(!this._flag.isWriteable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a writeable mode.")}var endFp=position+length;if(endFp>this._stat.size){this._stat.size=endFp;if(endFp>this._buffer.length){var newBuff=Buffer2.alloc(endFp);this._buffer.copy(newBuff);this._buffer=newBuff}}var len=buffer$$1.copy(this._buffer,position,offset,offset+length);this._stat.mtime=new Date;if(this._flag.isSynchronous()){this.syncSync();return len}this.setPos(position+len);return len};PreloadFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){if(!this._flag.isReadable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a readable mode.")}if(position===void 0||position===null){position=this.getPos()}var endRead=position+length;if(endRead>this._stat.size){length=this._stat.size-position}var rv=this._buffer.copy(buffer$$1,offset,position,position+length);this._stat.atime=new Date;this._pos=position+length;return rv};PreloadFile2.prototype.chmod=function chmod(mode,cb){try{this.chmodSync(mode);cb()}catch(e){cb(e)}};PreloadFile2.prototype.chmodSync=function chmodSync(mode){if(!this._fs.supportsProps()){throw new ApiError(ErrorCode.ENOTSUP)}this._dirty=true;this._stat.chmod(mode);this.syncSync()};PreloadFile2.prototype.isDirty=function isDirty(){return this._dirty};PreloadFile2.prototype.resetDirty=function resetDirty(){this._dirty=false};return PreloadFile2}(BaseFile);var NoSyncFile=function(PreloadFile2){function NoSyncFile2(_fs,_path,_flag,_stat,contents){PreloadFile2.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile2)NoSyncFile2.__proto__=PreloadFile2;NoSyncFile2.prototype=Object.create(PreloadFile2&&PreloadFile2.prototype);NoSyncFile2.prototype.constructor=NoSyncFile2;NoSyncFile2.prototype.sync=function sync(cb){cb()};NoSyncFile2.prototype.syncSync=function syncSync(){};NoSyncFile2.prototype.close=function close(cb){cb()};NoSyncFile2.prototype.closeSync=function closeSync(){};return NoSyncFile2}(PreloadFile);var MirrorFile=function(PreloadFile$$1){function MirrorFile2(fs4,path$$1,flag,stat,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,data)}if(PreloadFile$$1)MirrorFile2.__proto__=PreloadFile$$1;MirrorFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);MirrorFile2.prototype.constructor=MirrorFile2;MirrorFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};MirrorFile2.prototype.closeSync=function closeSync(){this.syncSync()};return MirrorFile2}(PreloadFile);var AsyncMirror=function(SynchronousFileSystem$$1){function AsyncMirror2(sync,async,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this._queue=[];this._queueRunning=false;this._isInitialized=false;this._initializeCallbacks=[];this._sync=sync;this._async=async;if(!sync.supportsSynch()){throw new Error("The first argument to AsyncMirror needs to be a synchronous file system.")}deprecationMessage(deprecateMsg,AsyncMirror2.Name,{sync:"sync file system instance",async:"async file system instance"})}if(SynchronousFileSystem$$1)AsyncMirror2.__proto__=SynchronousFileSystem$$1;AsyncMirror2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);AsyncMirror2.prototype.constructor=AsyncMirror2;AsyncMirror2.Create=function Create(opts,cb){try{var fs4=new AsyncMirror2(opts.sync,opts.async,false);fs4.initialize(function(e){if(e){cb(e)}else{cb(null,fs4)}},false)}catch(e){cb(e)}};AsyncMirror2.isAvailable=function isAvailable(){return true};AsyncMirror2.prototype.getName=function getName(){return AsyncMirror2.Name};AsyncMirror2.prototype._syncSync=function _syncSync(fd){this._sync.writeFileSync(fd.getPath(),fd.getBuffer(),null,FileFlag.getFileFlag("w"),fd.getStats().mode);this.enqueueOp({apiMethod:"writeFile",arguments:[fd.getPath(),fd.getBuffer(),null,fd.getFlag(),fd.getStats().mode]})};AsyncMirror2.prototype.initialize=function initialize3(userCb,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.")}var callbacks=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbacks.forEach(function(cb){return cb(e)})};if(!this._isInitialized){if(callbacks.push(userCb)===1){var copyDirectory=function(p,mode,cb){if(p!=="/"){this$1._sync.mkdirSync(p,mode)}this$1._async.readdir(p,function(err,files){var i2=0;function copyNextFile(err2){if(err2){cb(err2)}else if(i20){var op2=this$1._queue.shift(),args=op2.arguments;args.push(doNextOp);this$1._async[op2.apiMethod].apply(this$1._async,args)}else{this$1._queueRunning=false}};doNextOp()}};return AsyncMirror2}(SynchronousFileSystem);AsyncMirror.Name="AsyncMirror";AsyncMirror.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to."},async:{type:"object",description:"The asynchronous file system to mirror."}};function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}var nativeMax=Math.max;function overRest$1(func,start,transform){start=nativeMax(start===void 0?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}var breakLoop={};function noop(){}function once(fn){return function(){if(fn===null){return}var callFn=fn;fn=null;callFn.apply(this,arguments)}}var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator;var getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()};function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index-1&&value%1==0&&value++numRun){switch(error.status){case Dropbox.ApiError.SERVER_ERROR:case Dropbox.ApiError.NETWORK_ERROR:case Dropbox.ApiError.RATE_LIMITED:setTimeout(function(){performOp(interceptCb)},timeoutDuration*1e3);break;default:cb.apply(null,arguments);break}}else{cb.apply(null,arguments)}};performOp(interceptCb)};CachedDropboxClient.prototype.getCachedInfo=function getCachedInfo(p){return this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.putCachedInfo=function putCachedInfo(p,cache){this._cache[p.toLowerCase()]=cache};CachedDropboxClient.prototype.deleteCachedInfo=function deleteCachedInfo(p){delete this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.getCachedDirInfo=function getCachedDirInfo(p){var info=this.getCachedInfo(p);if(isDirInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.getCachedFileInfo=function getCachedFileInfo(p){var info=this.getCachedInfo(p);if(isFileInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.updateCachedDirInfo=function updateCachedDirInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.contentHash!==null&&(cachedInfo===void 0||cachedInfo.stat.contentHash!==stat.contentHash)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedFileInfo=function updateCachedFileInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.versionTag!==null&&(cachedInfo===void 0||cachedInfo.stat.versionTag!==stat.versionTag)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedInfo=function updateCachedInfo(p,stat,contents){if(contents===void 0)contents=null;if(stat.isFile&&isArrayBuffer(contents)){this.updateCachedFileInfo(p,stat,contents)}else if(stat.isFolder&&Array.isArray(contents)){this.updateCachedDirInfo(p,stat,contents)}};var DropboxFile=function(PreloadFile$$1){function DropboxFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)DropboxFile2.__proto__=PreloadFile$$1;DropboxFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);DropboxFile2.prototype.constructor=DropboxFile2;DropboxFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){var buffer$$1=this.getBuffer(),arrayBuffer=buffer2ArrayBuffer(buffer$$1);this._fs._writeFileStrict(this.getPath(),arrayBuffer,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};DropboxFile2.prototype.close=function close(cb){this.sync(cb)};return DropboxFile2}(PreloadFile);var DropboxFileSystem=function(BaseFileSystem$$1){function DropboxFileSystem2(client,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._client=new CachedDropboxClient(client);deprecationMessage(deprecateMsg,DropboxFileSystem2.Name,{client:"authenticated dropbox client instance"});constructErrorCodeLookup()}if(BaseFileSystem$$1)DropboxFileSystem2.__proto__=BaseFileSystem$$1;DropboxFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);DropboxFileSystem2.prototype.constructor=DropboxFileSystem2;DropboxFileSystem2.Create=function Create(opts,cb){cb(null,new DropboxFileSystem2(opts.client,false))};DropboxFileSystem2.isAvailable=function isAvailable(){return typeof Dropbox!=="undefined"};DropboxFileSystem2.prototype.getName=function getName(){return DropboxFileSystem2.Name};DropboxFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};DropboxFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};DropboxFileSystem2.prototype.supportsProps=function supportsProps(){return false};DropboxFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};DropboxFileSystem2.prototype.empty=function empty(mainCb){var this$1=this;this._client.readdir("/",function(error,files){if(error){mainCb(this$1.convert(error,"/"))}else{var deleteFile2=function(file,cb){var p=path.join("/",file);this$1._client.remove(p,function(err){cb(err?this$1.convert(err,p):null)})};var finished=function(err){if(err){mainCb(err)}else{mainCb()}};eachLimit(files,deleteFile2,finished)}})};DropboxFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._client.move(oldPath,newPath,function(error){if(error){this$1._client.stat(newPath,function(error2,stat){if(error2||stat.isFolder){var missingPath=error.response.error.indexOf(oldPath)>-1?oldPath:newPath;cb(this$1.convert(error,missingPath))}else{this$1._client.remove(newPath,function(error22){if(error22){cb(this$1.convert(error22,newPath))}else{this$1.rename(oldPath,newPath,cb)}})}})}else{cb()}})};DropboxFileSystem2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;this._client.stat(path$$1,function(error,stat2){if(error){cb(this$1.convert(error,path$$1))}else if(stat2&&stat2.isRemoved){cb(ApiError.FileError(ErrorCode.ENOENT,path$$1))}else{var stats=new Stats(this$1._statType(stat2),stat2.size);return cb(null,stats)}})};DropboxFileSystem2.prototype.open=function open(path$$1,flags,mode,cb){var this$1=this;this._client.readFile(path$$1,function(error,content,dbStat){if(error){if(flags.isReadable()){cb(this$1.convert(error,path$$1))}else{switch(error.status){case Dropbox.ApiError.NOT_FOUND:var ab=new ArrayBuffer(0);return this$1._writeFileStrict(path$$1,ab,function(error2,stat){if(error2){cb(error2)}else{var file2=this$1._makeFile(path$$1,flags,stat,arrayBuffer2Buffer(ab));cb(null,file2)}});default:return cb(this$1.convert(error,path$$1))}}}else{var buffer$$1;if(content===null){buffer$$1=emptyBuffer()}else{buffer$$1=arrayBuffer2Buffer(content)}var file=this$1._makeFile(path$$1,flags,dbStat,buffer$$1);return cb(null,file)}})};DropboxFileSystem2.prototype._writeFileStrict=function _writeFileStrict(p,data,cb){var this$1=this;var parent=path.dirname(p);this.stat(parent,false,function(error,stat){if(error){cb(ApiError.FileError(ErrorCode.ENOENT,parent))}else{this$1._client.writeFile(p,data,function(error2,stat2){if(error2){cb(this$1.convert(error2,p))}else{cb(null,stat2)}})}})};DropboxFileSystem2.prototype._statType=function _statType(stat){return stat.isFile?FileType.FILE:FileType.DIRECTORY};DropboxFileSystem2.prototype._makeFile=function _makeFile(path$$1,flag,stat,buffer$$1){var type=this._statType(stat);var stats=new Stats(type,stat.size);return new DropboxFile(this,path$$1,flag,stats,buffer$$1)};DropboxFileSystem2.prototype._remove=function _remove(path$$1,cb,isFile){var this$1=this;this._client.stat(path$$1,function(error,stat){if(error){cb(this$1.convert(error,path$$1))}else{if(stat.isFile&&!isFile){cb(ApiError.FileError(ErrorCode.ENOTDIR,path$$1))}else if(!stat.isFile&&isFile){cb(ApiError.FileError(ErrorCode.EISDIR,path$$1))}else{this$1._client.remove(path$$1,function(error2){if(error2){cb(this$1.convert(error2,path$$1))}else{cb(null)}})}}})};DropboxFileSystem2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};DropboxFileSystem2.prototype.rmdir=function rmdir(path$$1,cb){this._remove(path$$1,cb,false)};DropboxFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;var parent=path.dirname(p);this._client.stat(parent,function(error,stat){if(error){cb(this$1.convert(error,parent))}else{this$1._client.mkdir(p,function(error2){if(error2){cb(ApiError.FileError(ErrorCode.EEXIST,p))}else{cb(null)}})}})};DropboxFileSystem2.prototype.readdir=function readdir(path$$1,cb){var this$1=this;this._client.readdir(path$$1,function(error,files){if(error){return cb(this$1.convert(error))}else{return cb(null,files)}})};DropboxFileSystem2.prototype.convert=function convert(err,path$$1){if(path$$1===void 0)path$$1=null;var errorCode=errorCodeLookup[err.status];if(errorCode===void 0){errorCode=ErrorCode.EIO}if(!path$$1){return new ApiError(errorCode)}else{return ApiError.FileError(errorCode,path$$1)}};return DropboxFileSystem2}(BaseFileSystem);DropboxFileSystem.Name="Dropbox";DropboxFileSystem.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.",validator:function(opt,cb){if(opt.isAuthenticated&&opt.isAuthenticated()){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK."))}}}};function convertError(e,path$$1){if(path$$1===void 0)path$$1="";var errno=e.errno;var parent=e.node;var paths=[];while(parent){paths.unshift(parent.name);if(parent===parent.parent){break}parent=parent.parent}return new ApiError(errno,ErrorStrings[errno],paths.length>0?"/"+paths.join("/"):path$$1)}var EmscriptenFile=function(BaseFile$$1){function EmscriptenFile2(_fs,_FS,_path,_stream){BaseFile$$1.call(this);this._fs=_fs;this._FS=_FS;this._path=_path;this._stream=_stream}if(BaseFile$$1)EmscriptenFile2.__proto__=BaseFile$$1;EmscriptenFile2.prototype=Object.create(BaseFile$$1&&BaseFile$$1.prototype);EmscriptenFile2.prototype.constructor=EmscriptenFile2;EmscriptenFile2.prototype.getPos=function getPos(){return void 0};EmscriptenFile2.prototype.close=function close(cb){var err=null;try{this.closeSync()}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.closeSync=function closeSync(){try{this._FS.close(this._stream)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.stat=function stat(cb){try{cb(null,this.statSync())}catch(e){cb(e)}};EmscriptenFile2.prototype.statSync=function statSync(){try{return this._fs.statSync(this._path,false)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.truncate=function truncate(len,cb){var err=null;try{this.truncateSync(len)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.truncateSync=function truncateSync(len){try{this._FS.ftruncate(this._stream.fd,len)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.write(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.read(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.sync=function sync(cb){cb()};EmscriptenFile2.prototype.syncSync=function syncSync(){};EmscriptenFile2.prototype.chown=function chown(uid,gid,cb){var err=null;try{this.chownSync(uid,gid)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chownSync=function chownSync(uid,gid){try{this._FS.fchown(this._stream.fd,uid,gid)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.chmod=function chmod(mode,cb){var err=null;try{this.chmodSync(mode)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chmodSync=function chmodSync(mode){try{this._FS.fchmod(this._stream.fd,mode)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.utimes=function utimes(atime,mtime,cb){var err=null;try{this.utimesSync(atime,mtime)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.utimesSync=function utimesSync(atime,mtime){this._fs.utimesSync(this._path,atime,mtime)};return EmscriptenFile2}(BaseFile);var EmscriptenFileSystem=function(SynchronousFileSystem$$1){function EmscriptenFileSystem2(_FS){SynchronousFileSystem$$1.call(this);this._FS=_FS}if(SynchronousFileSystem$$1)EmscriptenFileSystem2.__proto__=SynchronousFileSystem$$1;EmscriptenFileSystem2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);EmscriptenFileSystem2.prototype.constructor=EmscriptenFileSystem2;EmscriptenFileSystem2.Create=function Create(opts,cb){cb(null,new EmscriptenFileSystem2(opts.FS))};EmscriptenFileSystem2.isAvailable=function isAvailable(){return true};EmscriptenFileSystem2.prototype.getName=function getName(){return this._FS.DB_NAME()};EmscriptenFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};EmscriptenFileSystem2.prototype.supportsLinks=function supportsLinks(){return true};EmscriptenFileSystem2.prototype.supportsProps=function supportsProps(){return true};EmscriptenFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};EmscriptenFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){try{this._FS.rename(oldPath,newPath)}catch(e){if(e.errno===ErrorCode.ENOENT){throw convertError(e,this.existsSync(oldPath)?newPath:oldPath)}else{throw convertError(e)}}};EmscriptenFileSystem2.prototype.statSync=function statSync(p,isLstat){try{var stats=isLstat?this._FS.lstat(p):this._FS.stat(p);var itemType=this.modeToFileType(stats.mode);return new Stats(itemType,stats.size,stats.mode,stats.atime,stats.mtime,stats.ctime)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.openSync=function openSync(p,flag,mode){try{var stream=this._FS.open(p,flag.getFlagString(),mode);if(this._FS.isDir(stream.node.mode)){this._FS.close(stream);throw ApiError.EISDIR(p)}return new EmscriptenFile(this,this._FS,p,stream)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.unlinkSync=function unlinkSync(p){try{this._FS.unlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.rmdirSync=function rmdirSync(p){try{this._FS.rmdir(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){try{this._FS.mkdir(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readdirSync=function readdirSync(p){try{return this._FS.readdir(p).filter(function(p2){return p2!=="."&&p2!==".."})}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.truncateSync=function truncateSync(p,len){try{this._FS.truncate(p,len)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readFileSync=function readFileSync(p,encoding,flag){try{var data=this._FS.readFile(p,{flags:flag.getFlagString()});var buff=uint8Array2Buffer(data);if(encoding){return buff.toString(encoding)}else{return buff}}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.writeFileSync=function writeFileSync(p,data,encoding,flag,mode){try{if(encoding){data=Buffer2.from(data,encoding)}var u8=buffer2Uint8array(data);this._FS.writeFile(p,u8,{flags:flag.getFlagString(),encoding:"binary"});this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){try{isLchmod?this._FS.lchmod(p,mode):this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){try{isLchown?this._FS.lchown(p,uid,gid):this._FS.chown(p,uid,gid)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){try{this._FS.symlink(srcpath,dstpath)}catch(e){throw convertError(e)}};EmscriptenFileSystem2.prototype.readlinkSync=function readlinkSync(p){try{return this._FS.readlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.utimesSync=function utimesSync(p,atime,mtime){try{this._FS.utime(p,atime.getTime(),mtime.getTime())}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.modeToFileType=function modeToFileType(mode){if(this._FS.isDir(mode)){return FileType.DIRECTORY}else if(this._FS.isFile(mode)){return FileType.FILE}else if(this._FS.isLink(mode)){return FileType.SYMLINK}else{throw ApiError.EPERM("Invalid mode: "+mode)}};return EmscriptenFileSystem2}(SynchronousFileSystem);EmscriptenFileSystem.Name="EmscriptenFileSystem";EmscriptenFileSystem.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var FolderAdapter=function(BaseFileSystem$$1){function FolderAdapter2(folder,wrapped){BaseFileSystem$$1.call(this);this._folder=folder;this._wrapped=wrapped}if(BaseFileSystem$$1)FolderAdapter2.__proto__=BaseFileSystem$$1;FolderAdapter2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);FolderAdapter2.prototype.constructor=FolderAdapter2;FolderAdapter2.Create=function Create(opts,cb){cb(null,new FolderAdapter2(opts.folder,opts.wrapped))};FolderAdapter2.isAvailable=function isAvailable(){return true};FolderAdapter2.prototype.initialize=function initialize3(cb){var this$1=this;this._wrapped.exists(this._folder,function(exists2){if(exists2){cb()}else if(this$1._wrapped.isReadOnly()){cb(ApiError.ENOENT(this$1._folder))}else{this$1._wrapped.mkdir(this$1._folder,511,cb)}})};FolderAdapter2.prototype.getName=function getName(){return this._wrapped.getName()};FolderAdapter2.prototype.isReadOnly=function isReadOnly(){return this._wrapped.isReadOnly()};FolderAdapter2.prototype.supportsProps=function supportsProps(){return this._wrapped.supportsProps()};FolderAdapter2.prototype.supportsSynch=function supportsSynch(){return this._wrapped.supportsSynch()};FolderAdapter2.prototype.supportsLinks=function supportsLinks(){return false};return FolderAdapter2}(BaseFileSystem);FolderAdapter.Name="FolderAdapter";FolderAdapter.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}};function translateError(folder,e){if(e!==null&&typeof e==="object"){var err=e;var p=err.path;if(p){p="/"+path.relative(folder,p);err.message=err.message.replace(err.path,p);err.path=p}}return e}function wrapCallback(folder,cb){if(typeof cb==="function"){return function(err){if(arguments.length>0){arguments[0]=translateError(folder,err)}cb.apply(null,arguments)}}else{return cb}}function wrapFunction(name,wrapFirst,wrapSecond){if(name.slice(name.length-4)!=="Sync"){return function(){if(arguments.length>0){if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}arguments[arguments.length-1]=wrapCallback(this._folder,arguments[arguments.length-1])}return this._wrapped[name].apply(this._wrapped,arguments)}}else{return function(){try{if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}return this._wrapped[name].apply(this._wrapped,arguments)}catch(e){throw translateError(this._folder,e)}}}}["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,false)});["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,true)});var toExport;if(typeof window!=="undefined"){toExport=window}else if(typeof self!=="undefined"){toExport=self}else{toExport=global}var global$1=toExport;function isDirectoryEntry(entry){return entry.isDirectory}var _getFS=global$1.webkitRequestFileSystem||global$1.requestFileSystem||null;function _requestQuota(type,size,success,errorCallback){if(typeof navigator["webkitPersistentStorage"]!=="undefined"){switch(type){case global$1.PERSISTENT:navigator.webkitPersistentStorage.requestQuota(size,success,errorCallback);break;case global$1.TEMPORARY:navigator.webkitTemporaryStorage.requestQuota(size,success,errorCallback);break;default:errorCallback(new TypeError("Invalid storage type: "+type));break}}else{global$1.webkitStorageInfo.requestQuota(type,size,success,errorCallback)}}function _toArray(list2){return Array.prototype.slice.call(list2||[],0)}function convertError$1(err,p,expectedDir){switch(err.name){case"PathExistsError":return ApiError.EEXIST(p);case"QuotaExceededError":return ApiError.FileError(ErrorCode.ENOSPC,p);case"NotFoundError":return ApiError.ENOENT(p);case"SecurityError":return ApiError.FileError(ErrorCode.EACCES,p);case"InvalidModificationError":return ApiError.FileError(ErrorCode.EPERM,p);case"TypeMismatchError":return ApiError.FileError(expectedDir?ErrorCode.ENOTDIR:ErrorCode.EISDIR,p);case"EncodingError":case"InvalidStateError":case"NoModificationAllowedError":default:return ApiError.FileError(ErrorCode.EINVAL,p)}}var HTML5FSFile=function(PreloadFile$$1){function HTML5FSFile2(fs4,entry,path$$1,flag,stat,contents){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,contents);this._entry=entry}if(PreloadFile$$1)HTML5FSFile2.__proto__=PreloadFile$$1;HTML5FSFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);HTML5FSFile2.prototype.constructor=HTML5FSFile2;HTML5FSFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){return cb()}this._entry.createWriter(function(writer){var buffer$$1=this$1.getBuffer();var blob=new Blob([buffer2ArrayBuffer(buffer$$1)]);var length=blob.size;writer.onwriteend=function(err){writer.onwriteend=null;writer.onerror=null;writer.truncate(length);this$1.resetDirty();cb()};writer.onerror=function(err){cb(convertError$1(err,this$1.getPath(),false))};writer.write(blob)})};HTML5FSFile2.prototype.close=function close(cb){this.sync(cb)};return HTML5FSFile2}(PreloadFile);var HTML5FS=function(BaseFileSystem$$1){function HTML5FS2(size,type,deprecateMsg){if(size===void 0)size=5;if(type===void 0)type=global$1.PERSISTENT;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this.size=1024*1024*size;this.type=type;deprecationMessage(deprecateMsg,HTML5FS2.Name,{size,type})}if(BaseFileSystem$$1)HTML5FS2.__proto__=BaseFileSystem$$1;HTML5FS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);HTML5FS2.prototype.constructor=HTML5FS2;HTML5FS2.Create=function Create(opts,cb){var fs4=new HTML5FS2(opts.size,opts.type,false);fs4.allocate(function(e){return e?cb(e):cb(null,fs4)},false)};HTML5FS2.isAvailable=function isAvailable(){return!!_getFS};HTML5FS2.prototype.getName=function getName(){return HTML5FS2.Name};HTML5FS2.prototype.isReadOnly=function isReadOnly(){return false};HTML5FS2.prototype.supportsSymlinks=function supportsSymlinks(){return false};HTML5FS2.prototype.supportsProps=function supportsProps(){return false};HTML5FS2.prototype.supportsSynch=function supportsSynch(){return false};HTML5FS2.prototype.allocate=function allocate(cb,deprecateMsg){var this$1=this;if(cb===void 0)cb=function(){};if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: "+this.type+", size: "+this.size+"}, cb)' to create and allocate HTML5FS instances.")}var success=function(fs4){this$1.fs=fs4;cb()};var error=function(err){cb(convertError$1(err,"/",true))};if(this.type===global$1.PERSISTENT){_requestQuota(this.type,this.size,function(granted){_getFS(this$1.type,granted,success,error)},error)}else{_getFS(this.type,this.size,success,error)}};HTML5FS2.prototype.empty=function empty(mainCb){this._readdir("/",function(err,entries){if(err){console.error("Failed to empty FS");mainCb(err)}else{var finished=function(er){if(err){console.error("Failed to empty FS");mainCb(err)}else{mainCb()}};var deleteEntry=function(entry,cb){var succ=function(){cb()};var error=function(err2){cb(convertError$1(err2,entry.fullPath,!entry.isDirectory))};if(isDirectoryEntry(entry)){entry.removeRecursively(succ,error)}else{entry.remove(succ,error)}};eachLimit(entries,deleteEntry,finished)}})};HTML5FS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var semaphore=2;var successCount=0;var root2=this.fs.root;var currentPath=oldPath;var error=function(err){if(--semaphore<=0){cb(convertError$1(err,currentPath,false))}};var success=function(file){if(++successCount===2){return cb(new ApiError(ErrorCode.EINVAL,"Something was identified as both a file and a directory. This should never happen."))}if(oldPath===newPath){return cb()}currentPath=path.dirname(newPath);root2.getDirectory(currentPath,{},function(parentDir){currentPath=path.basename(newPath);file.moveTo(parentDir,currentPath,function(entry){cb()},function(err){if(file.isDirectory){currentPath=newPath;this$1.unlink(newPath,function(e){if(e){error(err)}else{this$1.rename(oldPath,newPath,cb)}})}else{error(err)}})},error)};root2.getFile(oldPath,{},success,error);root2.getDirectory(oldPath,{},success,error)};HTML5FS2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;var opts={create:false};var loadAsFile=function(entry){var fileFromEntry=function(file){var stat2=new Stats(FileType.FILE,file.size);cb(null,stat2)};entry.file(fileFromEntry,failedToLoad)};var loadAsDir=function(dir$$1){var size=4096;var stat2=new Stats(FileType.DIRECTORY,size);cb(null,stat2)};var failedToLoad=function(err){cb(convertError$1(err,path$$1,false))};var failedToLoadAsFile=function(){this$1.fs.root.getDirectory(path$$1,opts,loadAsDir,failedToLoad)};this.fs.root.getFile(path$$1,opts,loadAsFile,failedToLoadAsFile)};HTML5FS2.prototype.open=function open(p,flags,mode,cb){var this$1=this;var error=function(err){if(err.name==="InvalidModificationError"&&flags.isExclusive()){cb(ApiError.EEXIST(p))}else{cb(convertError$1(err,p,false))}};this.fs.root.getFile(p,{create:flags.pathNotExistsAction()===ActionType.CREATE_FILE,exclusive:flags.isExclusive()},function(entry){entry.file(function(file){var reader=new FileReader;reader.onloadend=function(event){var bfsFile=this$1._makeFile(p,entry,flags,file,reader.result);cb(null,bfsFile)};reader.onerror=function(ev){error(reader.error)};reader.readAsArrayBuffer(file)},error)},error)};HTML5FS2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};HTML5FS2.prototype.rmdir=function rmdir(path$$1,cb){var this$1=this;this.readdir(path$$1,function(e,files){if(e){cb(e)}else if(files.length>0){cb(ApiError.ENOTEMPTY(path$$1))}else{this$1._remove(path$$1,cb,false)}})};HTML5FS2.prototype.mkdir=function mkdir(path$$1,mode,cb){var opts={create:true,exclusive:true};var success=function(dir$$1){cb()};var error=function(err){cb(convertError$1(err,path$$1,true))};this.fs.root.getDirectory(path$$1,opts,success,error)};HTML5FS2.prototype.readdir=function readdir(path$$1,cb){this._readdir(path$$1,function(e,entries){if(entries){var rv=[];for(var i2=0,list2=entries;i20){throw ApiError.ENOTEMPTY(p)}else{this.removeEntry(p,true)}};SyncKeyValueFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data)};SyncKeyValueFileSystem2.prototype.readdirSync=function readdirSync(p){var tx=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(tx,p,this.findINode(tx,p)))};SyncKeyValueFileSystem2.prototype._syncSync=function _syncSync(p,data,stats){var tx=this.store.beginTransaction("readwrite"),fileInodeId=this._findINode(tx,path.dirname(p),path.basename(p)),fileInode=this.getINode(tx,p,fileInodeId),inodeChanged=fileInode.update(stats);try{tx.put(fileInode.id,data,true);if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true)}}catch(e){tx.abort();throw e}tx.commit()};SyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(){var tx=this.store.beginTransaction("readwrite");if(tx.get(ROOT_NODE_ID)===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false);tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false);tx.commit()}};SyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename){var this$1=this;var readDirectory=function(inode){var dirList=this$1.getDirListing(tx,parent,inode);if(dirList[filename]){return dirList[filename]}else{throw ApiError.ENOENT(path.resolve(parent,filename))}};if(parent==="/"){if(filename===""){return ROOT_NODE_ID}else{return readDirectory(this.getINode(tx,parent,ROOT_NODE_ID))}}else{return readDirectory(this.getINode(tx,parent+path.sep+filename,this._findINode(tx,path.dirname(parent),path.basename(parent))))}};SyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p){return this.getINode(tx,p,this._findINode(tx,path.dirname(p),path.basename(p)))};SyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id){var inode=tx.get(id);if(inode===void 0){throw ApiError.ENOENT(p)}return Inode.fromBuffer(inode)};SyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode){if(!inode.isDirectory()){throw ApiError.ENOTDIR(p)}var data=tx.get(inode.id);if(data===void 0){throw ApiError.ENOENT(p)}return JSON.parse(data.toString())};SyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data){var retries=0;var currId;while(retries<5){try{currId=GenerateRandomID();tx.put(currId,data,false);return currId}catch(e){}}throw new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store.")};SyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data){var parentDir=path.dirname(p),fname=path.basename(p),parentNode=this.findINode(tx,parentDir),dirListing=this.getDirListing(tx,parentDir,parentNode),currTime=new Date().getTime();if(p==="/"){throw ApiError.EEXIST(p)}if(dirListing[fname]){throw ApiError.EEXIST(p)}var fileNode;try{var dataId=this.addNewNode(tx,data);fileNode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);var fileNodeId=this.addNewNode(tx,fileNode.toBuffer());dirListing[fname]=fileNodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true)}catch(e){tx.abort();throw e}tx.commit();return fileNode};SyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir){var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),parentNode=this.findINode(tx,parent),parentListing=this.getDirListing(tx,parent,parentNode),fileName=path.basename(p);if(!parentListing[fileName]){throw ApiError.ENOENT(p)}var fileNodeId=parentListing[fileName];delete parentListing[fileName];var fileNode=this.getINode(tx,p,fileNodeId);if(!isDir&&fileNode.isDirectory()){throw ApiError.EISDIR(p)}else if(isDir&&!fileNode.isDirectory()){throw ApiError.ENOTDIR(p)}try{tx.del(fileNode.id);tx.del(fileNodeId);tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true)}catch(e){tx.abort();throw e}tx.commit()};return SyncKeyValueFileSystem2}(SynchronousFileSystem);var AsyncKeyValueFile=function(PreloadFile$$1){function AsyncKeyValueFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)AsyncKeyValueFile2.__proto__=PreloadFile$$1;AsyncKeyValueFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);AsyncKeyValueFile2.prototype.constructor=AsyncKeyValueFile2;AsyncKeyValueFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};AsyncKeyValueFile2.prototype.close=function close(cb){this.sync(cb)};return AsyncKeyValueFile2}(PreloadFile);var AsyncKeyValueFileSystem=function(BaseFileSystem$$1){function AsyncKeyValueFileSystem2(){BaseFileSystem$$1.apply(this,arguments)}if(BaseFileSystem$$1)AsyncKeyValueFileSystem2.__proto__=BaseFileSystem$$1;AsyncKeyValueFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);AsyncKeyValueFileSystem2.prototype.constructor=AsyncKeyValueFileSystem2;AsyncKeyValueFileSystem2.isAvailable=function isAvailable(){return true};AsyncKeyValueFileSystem2.prototype.init=function init(store,cb){this.store=store;this.makeRootDirectory(cb)};AsyncKeyValueFileSystem2.prototype.getName=function getName(){return this.store.name()};AsyncKeyValueFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};AsyncKeyValueFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};AsyncKeyValueFileSystem2.prototype.supportsProps=function supportsProps(){return false};AsyncKeyValueFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};AsyncKeyValueFileSystem2.prototype.empty=function empty(cb){var this$1=this;this.store.clear(function(e){if(noError(e,cb)){this$1.makeRootDirectory(cb)}})};AsyncKeyValueFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");var oldParent=path.dirname(oldPath),oldName=path.basename(oldPath);var newParent=path.dirname(newPath),newName=path.basename(newPath);var inodes={};var lists={};var errorOccurred=false;if((newParent+"/").indexOf(oldPath+"/")===0){return cb(new ApiError(ErrorCode.EBUSY,oldParent))}var theOleSwitcharoo=function(){if(errorOccurred||!lists.hasOwnProperty(oldParent)||!lists.hasOwnProperty(newParent)){return}var oldParentList=lists[oldParent],oldParentINode=inodes[oldParent],newParentList=lists[newParent],newParentINode=inodes[newParent];if(!oldParentList[oldName]){cb(ApiError.ENOENT(oldPath))}else{var fileId=oldParentList[oldName];delete oldParentList[oldName];var completeRename=function(){newParentList[newName]=fileId;tx.put(oldParentINode.id,Buffer2.from(JSON.stringify(oldParentList)),true,function(e){if(noErrorTx(e,tx,cb)){if(oldParent===newParent){tx.commit(cb)}else{tx.put(newParentINode.id,Buffer2.from(JSON.stringify(newParentList)),true,function(e2){if(noErrorTx(e2,tx,cb)){tx.commit(cb)}})}}})};if(newParentList[newName]){this$1.getINode(tx,newPath,newParentList[newName],function(e,inode){if(noErrorTx(e,tx,cb)){if(inode.isFile()){tx.del(inode.id,function(e2){if(noErrorTx(e2,tx,cb)){tx.del(newParentList[newName],function(e3){if(noErrorTx(e3,tx,cb)){completeRename()}})}})}else{tx.abort(function(e2){cb(ApiError.EPERM(newPath))})}}})}else{completeRename()}}};var processInodeAndListings=function(p){this$1.findINodeAndDirListing(tx,p,function(e,node,dirList){if(e){if(!errorOccurred){errorOccurred=true;tx.abort(function(){cb(e)})}}else{inodes[p]=node;lists[p]=dirList;theOleSwitcharoo()}})};processInodeAndListings(oldParent);if(oldParent!==newParent){processInodeAndListings(newParent)}};AsyncKeyValueFileSystem2.prototype.stat=function stat(p,isLstat,cb){var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){cb(null,inode.toStats())}})};AsyncKeyValueFileSystem2.prototype.createFile=function createFile(p,flag,mode,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),data=emptyBuffer();this.commitNewFile(tx,p,FileType.FILE,mode,data,function(e,newFile){if(noError(e,cb)){cb(null,new AsyncKeyValueFile(this$1,p,flag,newFile.toStats(),data))}})};AsyncKeyValueFileSystem2.prototype.openFile=function openFile(p,flag,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){tx.get(inode.id,function(e2,data){if(noError(e2,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,new AsyncKeyValueFile(this$1,p,flag,inode.toStats(),data))}}})}})};AsyncKeyValueFileSystem2.prototype.unlink=function unlink(p,cb){this.removeEntry(p,false,cb)};AsyncKeyValueFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;this.readdir(p,function(err,files){if(err){cb(err)}else if(files.length>0){cb(ApiError.ENOTEMPTY(p))}else{this$1.removeEntry(p,true,cb)}})};AsyncKeyValueFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data,cb)};AsyncKeyValueFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,dirListing){if(noError(e2,cb)){cb(null,Object.keys(dirListing))}})}})};AsyncKeyValueFileSystem2.prototype._sync=function _sync(p,data,stats,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");this._findINode(tx,path.dirname(p),path.basename(p),function(e,fileInodeId){if(noErrorTx(e,tx,cb)){this$1.getINode(tx,p,fileInodeId,function(e2,fileInode){if(noErrorTx(e2,tx,cb)){var inodeChanged=fileInode.update(stats);tx.put(fileInode.id,data,true,function(e3){if(noErrorTx(e3,tx,cb)){if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(cb)}})}else{tx.commit(cb)}}})}})}})};AsyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(cb){var tx=this.store.beginTransaction("readwrite");tx.get(ROOT_NODE_ID,function(e,data){if(e||data===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false,function(e2){if(noErrorTx(e2,tx,cb)){tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false,function(e3){if(e3){tx.abort(function(){cb(e3)})}else{tx.commit(cb)}})}})}else{tx.commit(cb)}})};AsyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename,cb){var this$1=this;var handleDirectoryListings=function(e,inode,dirList){if(e){cb(e)}else if(dirList[filename]){cb(null,dirList[filename])}else{cb(ApiError.ENOENT(path.resolve(parent,filename)))}};if(parent==="/"){if(filename===""){cb(null,ROOT_NODE_ID)}else{this.getINode(tx,parent,ROOT_NODE_ID,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,parent,inode,function(e2,dirList){handleDirectoryListings(e2,inode,dirList)})}})}}else{this.findINodeAndDirListing(tx,parent,handleDirectoryListings)}};AsyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p,cb){var this$1=this;this._findINode(tx,path.dirname(p),path.basename(p),function(e,id){if(noError(e,cb)){this$1.getINode(tx,p,id,cb)}})};AsyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id,cb){tx.get(id,function(e,data){if(noError(e,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,Inode.fromBuffer(data))}}})};AsyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode,cb){if(!inode.isDirectory()){cb(ApiError.ENOTDIR(p))}else{tx.get(inode.id,function(e,data){if(noError(e,cb)){try{cb(null,JSON.parse(data.toString()))}catch(e2){cb(ApiError.ENOENT(p))}}})}};AsyncKeyValueFileSystem2.prototype.findINodeAndDirListing=function findINodeAndDirListing(tx,p,cb){var this$1=this;this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,listing){if(noError(e2,cb)){cb(null,inode,listing)}})}})};AsyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data,cb){var retries=0,currId;var reroll=function(){if(++retries===5){cb(new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store."))}else{currId=GenerateRandomID();tx.put(currId,data,false,function(e,committed){if(e||!committed){reroll()}else{cb(null,currId)}})}};reroll()};AsyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data,cb){var this$1=this;var parentDir=path.dirname(p),fname=path.basename(p),currTime=new Date().getTime();if(p==="/"){return cb(ApiError.EEXIST(p))}this.findINodeAndDirListing(tx,parentDir,function(e,parentNode,dirListing){if(noErrorTx(e,tx,cb)){if(dirListing[fname]){tx.abort(function(){cb(ApiError.EEXIST(p))})}else{this$1.addNewNode(tx,data,function(e2,dataId){if(noErrorTx(e2,tx,cb)){var fileInode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);this$1.addNewNode(tx,fileInode.toBuffer(),function(e3,fileInodeId){if(noErrorTx(e3,tx,cb)){dirListing[fname]=fileInodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(function(e5){if(noErrorTx(e5,tx,cb)){cb(null,fileInode)}})}})}})}})}}})};AsyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),fileName=path.basename(p);this.findINodeAndDirListing(tx,parent,function(e,parentNode,parentListing){if(noErrorTx(e,tx,cb)){if(!parentListing[fileName]){tx.abort(function(){cb(ApiError.ENOENT(p))})}else{var fileNodeId=parentListing[fileName];delete parentListing[fileName];this$1.getINode(tx,p,fileNodeId,function(e2,fileNode){if(noErrorTx(e2,tx,cb)){if(!isDir&&fileNode.isDirectory()){tx.abort(function(){cb(ApiError.EISDIR(p))})}else if(isDir&&!fileNode.isDirectory()){tx.abort(function(){cb(ApiError.ENOTDIR(p))})}else{tx.del(fileNode.id,function(e3){if(noErrorTx(e3,tx,cb)){tx.del(fileNodeId,function(e4){if(noErrorTx(e4,tx,cb)){tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true,function(e5){if(noErrorTx(e5,tx,cb)){tx.commit(cb)}})}})}})}}})}}})};return AsyncKeyValueFileSystem2}(BaseFileSystem);var InMemoryStore=function InMemoryStore2(){this.store={}};InMemoryStore.prototype.name=function name(){return InMemoryFileSystem.Name};InMemoryStore.prototype.clear=function clear(){this.store={}};InMemoryStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};InMemoryStore.prototype.get=function get(key){return this.store[key]};InMemoryStore.prototype.put=function put(key,data,overwrite){if(!overwrite&&this.store.hasOwnProperty(key)){return false}this.store[key]=data;return true};InMemoryStore.prototype.del=function del(key){delete this.store[key]};var InMemoryFileSystem=function(SyncKeyValueFileSystem$$1){function InMemoryFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new InMemoryStore})}if(SyncKeyValueFileSystem$$1)InMemoryFileSystem2.__proto__=SyncKeyValueFileSystem$$1;InMemoryFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);InMemoryFileSystem2.prototype.constructor=InMemoryFileSystem2;InMemoryFileSystem2.Create=function Create(options,cb){cb(null,new InMemoryFileSystem2)};return InMemoryFileSystem2}(SyncKeyValueFileSystem);InMemoryFileSystem.Name="InMemory";InMemoryFileSystem.Options={};var indexedDB=global$1.indexedDB||global$1.mozIndexedDB||global$1.webkitIndexedDB||global$1.msIndexedDB;function convertError$2(e,message){if(message===void 0)message=e.toString();switch(e.name){case"NotFoundError":return new ApiError(ErrorCode.ENOENT,message);case"QuotaExceededError":return new ApiError(ErrorCode.ENOSPC,message);default:return new ApiError(ErrorCode.EIO,message)}}function onErrorHandler(cb,code,message){if(code===void 0)code=ErrorCode.EIO;if(message===void 0)message=null;return function(e){e.preventDefault();cb(new ApiError(code,message!==null?message:void 0))}}var IndexedDBROTransaction=function IndexedDBROTransaction2(tx,store){this.tx=tx;this.store=store};IndexedDBROTransaction.prototype.get=function get(key,cb){try{var r=this.store.get(key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){var result=event.target.result;if(result===void 0){cb(null,result)}else{cb(null,arrayBuffer2Buffer(result))}}}catch(e){cb(convertError$2(e))}};var IndexedDBRWTransaction=function(IndexedDBROTransaction2){function IndexedDBRWTransaction2(tx,store){IndexedDBROTransaction2.call(this,tx,store)}if(IndexedDBROTransaction2)IndexedDBRWTransaction2.__proto__=IndexedDBROTransaction2;IndexedDBRWTransaction2.prototype=Object.create(IndexedDBROTransaction2&&IndexedDBROTransaction2.prototype);IndexedDBRWTransaction2.prototype.constructor=IndexedDBRWTransaction2;IndexedDBRWTransaction2.prototype.put=function put(key,data,overwrite,cb){try{var arraybuffer=buffer2ArrayBuffer(data);var r;if(overwrite){r=this.store.put(arraybuffer,key)}else{r=this.store.add(arraybuffer,key)}r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb(null,true)}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.del=function del(key,cb){try{var r=this.store["delete"](key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb()}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.commit=function commit(cb){setTimeout(cb,0)};IndexedDBRWTransaction2.prototype.abort=function abort(cb){var _e=null;try{this.tx.abort()}catch(e){_e=convertError$2(e)}finally{cb(_e)}};return IndexedDBRWTransaction2}(IndexedDBROTransaction);var IndexedDBStore=function IndexedDBStore2(cb,storeName){var this$1=this;if(storeName===void 0)storeName="browserfs";this.storeName=storeName;var openReq=indexedDB.open(this.storeName,1);openReq.onupgradeneeded=function(event){var db=event.target.result;if(db.objectStoreNames.contains(this$1.storeName)){db.deleteObjectStore(this$1.storeName)}db.createObjectStore(this$1.storeName)};openReq.onsuccess=function(event){this$1.db=event.target.result;cb(null,this$1)};openReq.onerror=onErrorHandler(cb,ErrorCode.EACCES)};IndexedDBStore.prototype.name=function name(){return IndexedDBFileSystem.Name+" - "+this.storeName};IndexedDBStore.prototype.clear=function clear(cb){try{var tx=this.db.transaction(this.storeName,"readwrite"),objectStore=tx.objectStore(this.storeName),r=objectStore.clear();r.onsuccess=function(event){setTimeout(cb,0)};r.onerror=onErrorHandler(cb)}catch(e){cb(convertError$2(e))}};IndexedDBStore.prototype.beginTransaction=function beginTransaction(type){if(type===void 0)type="readonly";var tx=this.db.transaction(this.storeName,type),objectStore=tx.objectStore(this.storeName);if(type==="readwrite"){return new IndexedDBRWTransaction(tx,objectStore)}else if(type==="readonly"){return new IndexedDBROTransaction(tx,objectStore)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid transaction type.")}};var IndexedDBFileSystem=function(AsyncKeyValueFileSystem$$1){function IndexedDBFileSystem2(cb,storeName,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;AsyncKeyValueFileSystem$$1.call(this);this.store=new IndexedDBStore(function(e){if(e){cb(e)}else{this$1.init(this$1.store,function(e2){cb(e2,this$1)})}},storeName);deprecationMessage(deprecateMsg,IndexedDBFileSystem2.Name,{storeName})}if(AsyncKeyValueFileSystem$$1)IndexedDBFileSystem2.__proto__=AsyncKeyValueFileSystem$$1;IndexedDBFileSystem2.prototype=Object.create(AsyncKeyValueFileSystem$$1&&AsyncKeyValueFileSystem$$1.prototype);IndexedDBFileSystem2.prototype.constructor=IndexedDBFileSystem2;IndexedDBFileSystem2.Create=function Create(opts,cb){new IndexedDBFileSystem2(cb,opts.storeName,false)};IndexedDBFileSystem2.isAvailable=function isAvailable(){try{return typeof indexedDB!=="undefined"&&null!==indexedDB.open("__browserfs_test__")}catch(e){return false}};return IndexedDBFileSystem2}(AsyncKeyValueFileSystem);IndexedDBFileSystem.Name="IndexedDB";IndexedDBFileSystem.Options={storeName:{type:"string",optional:true,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var supportsBinaryString=false;var binaryEncoding;try{global$1.localStorage.setItem("__test__",String.fromCharCode(55296));supportsBinaryString=global$1.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(e){supportsBinaryString=false}binaryEncoding=supportsBinaryString?"binary_string":"binary_string_ie";if(!Buffer2.isEncoding(binaryEncoding)){binaryEncoding="base64"}var LocalStorageStore=function LocalStorageStore2(){};LocalStorageStore.prototype.name=function name(){return LocalStorageFileSystem.Name};LocalStorageStore.prototype.clear=function clear(){global$1.localStorage.clear()};LocalStorageStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};LocalStorageStore.prototype.get=function get(key){try{var data=global$1.localStorage.getItem(key);if(data!==null){return Buffer2.from(data,binaryEncoding)}}catch(e){}return void 0};LocalStorageStore.prototype.put=function put(key,data,overwrite){try{if(!overwrite&&global$1.localStorage.getItem(key)!==null){return false}global$1.localStorage.setItem(key,data.toString(binaryEncoding));return true}catch(e){throw new ApiError(ErrorCode.ENOSPC,"LocalStorage is full.")}};LocalStorageStore.prototype.del=function del(key){try{global$1.localStorage.removeItem(key)}catch(e){throw new ApiError(ErrorCode.EIO,"Unable to delete key "+key+": "+e)}};var LocalStorageFileSystem=function(SyncKeyValueFileSystem$$1){function LocalStorageFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new LocalStorageStore})}if(SyncKeyValueFileSystem$$1)LocalStorageFileSystem2.__proto__=SyncKeyValueFileSystem$$1;LocalStorageFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);LocalStorageFileSystem2.prototype.constructor=LocalStorageFileSystem2;LocalStorageFileSystem2.Create=function Create(options,cb){cb(null,new LocalStorageFileSystem2)};LocalStorageFileSystem2.isAvailable=function isAvailable(){return typeof global$1.localStorage!=="undefined"};return LocalStorageFileSystem2}(SyncKeyValueFileSystem);LocalStorageFileSystem.Name="LocalStorage";LocalStorageFileSystem.Options={};var MountableFileSystem=function(BaseFileSystem$$1){function MountableFileSystem2(){BaseFileSystem$$1.call(this);this.mountList=[];this.mntMap={};this.rootFs=new InMemoryFileSystem}if(BaseFileSystem$$1)MountableFileSystem2.__proto__=BaseFileSystem$$1;MountableFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);MountableFileSystem2.prototype.constructor=MountableFileSystem2;MountableFileSystem2.Create=function Create(opts,cb){var fs4=new MountableFileSystem2;Object.keys(opts).forEach(function(mountPoint){fs4.mount(mountPoint,opts[mountPoint])});cb(null,fs4)};MountableFileSystem2.isAvailable=function isAvailable(){return true};MountableFileSystem2.prototype.mount=function mount(mountPoint,fs4){if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already taken.")}mkdirpSync(mountPoint,511,this.rootFs);this.mntMap[mountPoint]=fs4;this.mountList.push(mountPoint);this.mountList=this.mountList.sort(function(a,b){return b.length-a.length})};MountableFileSystem2.prototype.umount=function umount(mountPoint){var this$1=this;if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(!this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already unmounted.")}delete this.mntMap[mountPoint];this.mountList.splice(this.mountList.indexOf(mountPoint),1);while(mountPoint!=="/"){if(this$1.rootFs.readdirSync(mountPoint).length===0){this$1.rootFs.rmdirSync(mountPoint);mountPoint=path.dirname(mountPoint)}else{break}}};MountableFileSystem2.prototype._getFs=function _getFs(path$$1){var this$1=this;var mountList=this.mountList,len=mountList.length;for(var i2=0;i21?mountPoint.length:0);if(path$$1===""){path$$1="/"}return{fs:this$1.mntMap[mountPoint],path:path$$1}}}return{fs:this.rootFs,path:path$$1}};MountableFileSystem2.prototype.getName=function getName(){return MountableFileSystem2.Name};MountableFileSystem2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};MountableFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};MountableFileSystem2.prototype.supportsLinks=function supportsLinks(){return false};MountableFileSystem2.prototype.supportsProps=function supportsProps(){return false};MountableFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};MountableFileSystem2.prototype.standardizeError=function standardizeError(err,path$$1,realPath){var index=err.message.indexOf(path$$1);if(index!==-1){err.message=err.message.substr(0,index)+realPath+err.message.substr(index+path$$1.length);err.path=realPath}return err};MountableFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){return fs1rv.fs.rename(fs1rv.path,fs2rv.path,function(e){if(e){this$1.standardizeError(this$1.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath)}cb(e)})}return _fsMock.readFile(oldPath,function(err,data){if(err){return cb(err)}_fsMock.writeFile(newPath,data,function(err2){if(err2){return cb(err2)}_fsMock.unlink(oldPath,cb)})})};MountableFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){try{return fs1rv.fs.renameSync(fs1rv.path,fs2rv.path)}catch(e){this.standardizeError(this.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath);throw e}}var data=_fsMock.readFileSync(oldPath);_fsMock.writeFileSync(newPath,data);return _fsMock.unlinkSync(oldPath)};MountableFileSystem2.prototype.readdirSync=function readdirSync(p){var fsInfo=this._getFs(p);var rv=null;if(fsInfo.fs!==this.rootFs){try{rv=this.rootFs.readdirSync(p)}catch(e){}}try{var rv2=fsInfo.fs.readdirSync(fsInfo.path);if(rv===null){return rv2}else{return rv2.concat(rv.filter(function(val){return rv2.indexOf(val)===-1}))}}catch(e){if(rv===null){throw this.standardizeError(e,fsInfo.path,p)}else{return rv}}};MountableFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);fsInfo.fs.readdir(fsInfo.path,function(err,files){if(fsInfo.fs!==this$1.rootFs){try{var rv=this$1.rootFs.readdirSync(p);if(files){files=files.concat(rv.filter(function(val){return files.indexOf(val)===-1}))}else{files=rv}}catch(e){if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}}}else if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}cb(null,files)})};MountableFileSystem2.prototype.rmdirSync=function rmdirSync(p){var fsInfo=this._getFs(p);if(this._containsMountPt(p)){throw ApiError.ENOTEMPTY(p)}else{try{fsInfo.fs.rmdirSync(fsInfo.path)}catch(e){throw this.standardizeError(e,fsInfo.path,p)}}};MountableFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);if(this._containsMountPt(p)){cb(ApiError.ENOTEMPTY(p))}else{fsInfo.fs.rmdir(fsInfo.path,function(err){cb(err?this$1.standardizeError(err,fsInfo.path,p):null)})}};MountableFileSystem2.prototype._containsMountPt=function _containsMountPt(p){var mountPoints=this.mountList,len=mountPoints.length;for(var i2=0;i2=p.length&&pt.slice(0,p.length)===p){return true}}return false};return MountableFileSystem2}(BaseFileSystem);MountableFileSystem.Name="MountableFileSystem";MountableFileSystem.Options={};function defineFcn(name,isSync,numArgs){if(isSync){return function(){var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;try{return rv.fs[name].apply(rv.fs,args)}catch(e){this.standardizeError(e,rv.path,path$$1);throw e}}}else{return function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;if(typeof args[args.length-1]==="function"){var cb=args[args.length-1];args[args.length-1]=function(){var args2=[],len2=arguments.length;while(len2--)args2[len2]=arguments[len2];if(args2.length>0&&args2[0]instanceof ApiError){this$1.standardizeError(args2[0],rv.path,path$$1)}cb.apply(null,args2)}}return rv.fs[name].apply(rv.fs,args)}}}var fsCmdMap=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]];for(var i=0;i0){var fn=timeouts.shift();return fn()}}};if(gScope.addEventListener){gScope.addEventListener("message",handleMessage,true)}else{gScope.attachEvent("onmessage",handleMessage)}}else if(gScope.MessageChannel){var channel=new gScope.MessageChannel;channel.port1.onmessage=function(event){if(timeouts.length>0){return timeouts.shift()()}};bfsSetImmediate=function(fn){timeouts.push(fn);channel.port2.postMessage("")}}else{bfsSetImmediate=function(fn){return setTimeout(fn,0)}}}var setImmediate$3=bfsSetImmediate;var Mutex=function Mutex2(){this._locked=false;this._waiters=[]};Mutex.prototype.lock=function lock(cb){if(this._locked){this._waiters.push(cb);return}this._locked=true;cb()};Mutex.prototype.unlock=function unlock(){if(!this._locked){throw new Error("unlock of a non-locked mutex")}var next=this._waiters.shift();if(next){setImmediate$3(next);return}this._locked=false};Mutex.prototype.tryLock=function tryLock(){if(this._locked){return false}this._locked=true;return true};Mutex.prototype.isLocked=function isLocked(){return this._locked};var LockedFS=function LockedFS2(fs4){this._fs=fs4;this._mu=new Mutex};LockedFS.prototype.getName=function getName(){return"LockedFS<"+this._fs.getName()+">"};LockedFS.prototype.getFSUnlocked=function getFSUnlocked(){return this._fs};LockedFS.prototype.initialize=function initialize3(cb){this._fs.initialize(cb)};LockedFS.prototype.diskSpace=function diskSpace(p,cb){this._fs.diskSpace(p,cb)};LockedFS.prototype.isReadOnly=function isReadOnly(){return this._fs.isReadOnly()};LockedFS.prototype.supportsLinks=function supportsLinks(){return this._fs.supportsLinks()};LockedFS.prototype.supportsProps=function supportsProps(){return this._fs.supportsProps()};LockedFS.prototype.supportsSynch=function supportsSynch(){return this._fs.supportsSynch()};LockedFS.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rename(oldPath,newPath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.renameSync=function renameSync(oldPath,newPath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.renameSync(oldPath,newPath)};LockedFS.prototype.stat=function stat(p,isLstat,cb){var this$1=this;this._mu.lock(function(){this$1._fs.stat(p,isLstat,function(err,stat2){this$1._mu.unlock();cb(err,stat2)})})};LockedFS.prototype.statSync=function statSync(p,isLstat){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.statSync(p,isLstat)};LockedFS.prototype.open=function open(p,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.open(p,flag,mode,function(err,fd){this$1._mu.unlock();cb(err,fd)})})};LockedFS.prototype.openSync=function openSync(p,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.openSync(p,flag,mode)};LockedFS.prototype.unlink=function unlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.unlink(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.unlinkSync=function unlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.unlinkSync(p)};LockedFS.prototype.rmdir=function rmdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rmdir(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.rmdirSync=function rmdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.rmdirSync(p)};LockedFS.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.mkdir(p,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.mkdirSync=function mkdirSync(p,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.mkdirSync(p,mode)};LockedFS.prototype.readdir=function readdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readdir(p,function(err,files){this$1._mu.unlock();cb(err,files)})})};LockedFS.prototype.readdirSync=function readdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readdirSync(p)};LockedFS.prototype.exists=function exists2(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.exists(p,function(exists3){this$1._mu.unlock();cb(exists3)})})};LockedFS.prototype.existsSync=function existsSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.existsSync(p)};LockedFS.prototype.realpath=function realpath(p,cache,cb){var this$1=this;this._mu.lock(function(){this$1._fs.realpath(p,cache,function(err,resolvedPath){this$1._mu.unlock();cb(err,resolvedPath)})})};LockedFS.prototype.realpathSync=function realpathSync(p,cache){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.realpathSync(p,cache)};LockedFS.prototype.truncate=function truncate(p,len,cb){var this$1=this;this._mu.lock(function(){this$1._fs.truncate(p,len,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.truncateSync=function truncateSync(p,len){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.truncateSync(p,len)};LockedFS.prototype.readFile=function readFile2(fname,encoding,flag,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readFile(fname,encoding,flag,function(err,data){this$1._mu.unlock();cb(err,data)})})};LockedFS.prototype.readFileSync=function readFileSync(fname,encoding,flag){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readFileSync(fname,encoding,flag)};LockedFS.prototype.writeFile=function writeFile2(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.writeFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.writeFileSync=function writeFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.writeFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.appendFile=function appendFile3(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.appendFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.appendFileSync=function appendFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.appendFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chmod(p,isLchmod,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chmodSync=function chmodSync(p,isLchmod,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chmodSync(p,isLchmod,mode)};LockedFS.prototype.chown=function chown(p,isLchown,uid,gid,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chown(p,isLchown,uid,gid,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chownSync=function chownSync(p,isLchown,uid,gid){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chownSync(p,isLchown,uid,gid)};LockedFS.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;this._mu.lock(function(){this$1._fs.utimes(p,atime,mtime,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.utimesSync=function utimesSync(p,atime,mtime){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.utimesSync(p,atime,mtime)};LockedFS.prototype.link=function link(srcpath,dstpath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.link(srcpath,dstpath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.linkSync=function linkSync(srcpath,dstpath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.linkSync(srcpath,dstpath)};LockedFS.prototype.symlink=function symlink(srcpath,dstpath,type,cb){var this$1=this;this._mu.lock(function(){this$1._fs.symlink(srcpath,dstpath,type,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.symlinkSync(srcpath,dstpath,type)};LockedFS.prototype.readlink=function readlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readlink(p,function(err,linkString){this$1._mu.unlock();cb(err,linkString)})})};LockedFS.prototype.readlinkSync=function readlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readlinkSync(p)};var deletionLogPath="/.deletedFiles.log";function makeModeWritable(mode){return 146|mode}function getFlag(f){return FileFlag.getFileFlag(f)}var OverlayFile=function(PreloadFile$$1){function OverlayFile2(fs4,path$$1,flag,stats,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stats,data)}if(PreloadFile$$1)OverlayFile2.__proto__=PreloadFile$$1;OverlayFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);OverlayFile2.prototype.constructor=OverlayFile2;OverlayFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){cb(null);return}this._fs._syncAsync(this,function(err){this$1.resetDirty();cb(err)})};OverlayFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};OverlayFile2.prototype.close=function close(cb){this.sync(cb)};OverlayFile2.prototype.closeSync=function closeSync(){this.syncSync()};return OverlayFile2}(PreloadFile);var UnlockedOverlayFS=function(BaseFileSystem$$1){function UnlockedOverlayFS2(writable,readable){BaseFileSystem$$1.call(this);this._isInitialized=false;this._initializeCallbacks=[];this._deletedFiles={};this._deleteLog="";this._deleteLogUpdatePending=false;this._deleteLogUpdateNeeded=false;this._deleteLogError=null;this._writable=writable;this._readable=readable;if(this._writable.isReadOnly()){throw new ApiError(ErrorCode.EINVAL,"Writable file system must be writable.")}}if(BaseFileSystem$$1)UnlockedOverlayFS2.__proto__=BaseFileSystem$$1;UnlockedOverlayFS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);UnlockedOverlayFS2.prototype.constructor=UnlockedOverlayFS2;UnlockedOverlayFS2.isAvailable=function isAvailable(){return true};UnlockedOverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return{readable:this._readable,writable:this._writable}};UnlockedOverlayFS2.prototype._syncAsync=function _syncAsync(file,cb){var this$1=this;this.createParentDirectoriesAsync(file.getPath(),function(err){if(err){return cb(err)}this$1._writable.writeFile(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode,cb)})};UnlockedOverlayFS2.prototype._syncSync=function _syncSync(file){this.createParentDirectories(file.getPath());this._writable.writeFileSync(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode)};UnlockedOverlayFS2.prototype.getName=function getName(){return OverlayFS.Name};UnlockedOverlayFS2.prototype.initialize=function initialize3(cb){var this$1=this;var callbackArray=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbackArray.forEach(function(cb2){return cb2(e)})};if(this._isInitialized){return cb()}callbackArray.push(cb);if(callbackArray.length!==1){return}this._writable.readFile(deletionLogPath,"utf8",getFlag("r"),function(err,data){if(err){if(err.errno!==ErrorCode.ENOENT){return end(err)}}else{this$1._deleteLog=data}this$1._reparseDeletionLog();end()})};UnlockedOverlayFS2.prototype.isReadOnly=function isReadOnly(){return false};UnlockedOverlayFS2.prototype.supportsSynch=function supportsSynch(){return this._readable.supportsSynch()&&this._writable.supportsSynch()};UnlockedOverlayFS2.prototype.supportsLinks=function supportsLinks(){return false};UnlockedOverlayFS2.prototype.supportsProps=function supportsProps(){return this._readable.supportsProps()&&this._writable.supportsProps()};UnlockedOverlayFS2.prototype.getDeletionLog=function getDeletionLog(){return this._deleteLog};UnlockedOverlayFS2.prototype.restoreDeletionLog=function restoreDeletionLog(log){this._deleteLog=log;this._reparseDeletionLog();this.updateLog("")};UnlockedOverlayFS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(oldPath,cb)||this.checkPathAsync(newPath,cb)){return}if(oldPath===deletionLogPath||newPath===deletionLogPath){return cb(ApiError.EPERM("Cannot rename deletion log."))}if(oldPath===newPath){return cb()}this.stat(oldPath,false,function(oldErr,oldStats){if(oldErr){return cb(oldErr)}return this$1.stat(newPath,false,function(newErr,newStats){var self2=this$1;function copyDirContents(files){var file=files.shift();if(!file){return cb()}var oldFile=path.resolve(oldPath,file);var newFile=path.resolve(newPath,file);self2.rename(oldFile,newFile,function(err){if(err){return cb(err)}copyDirContents(files)})}var mode=511;if(oldStats.isDirectory()){if(newErr){if(newErr.errno!==ErrorCode.ENOENT){return cb(newErr)}return this$1._writable.exists(oldPath,function(exists2){if(exists2){return this$1._writable.rename(oldPath,newPath,cb)}this$1._writable.mkdir(newPath,mode,function(mkdirErr){if(mkdirErr){return cb(mkdirErr)}this$1._readable.readdir(oldPath,function(err,files){if(err){return cb()}copyDirContents(files)})})})}mode=newStats.mode;if(!newStats.isDirectory()){return cb(ApiError.ENOTDIR(newPath))}this$1.readdir(newPath,function(readdirErr,files){if(files&&files.length){return cb(ApiError.ENOTEMPTY(newPath))}this$1._readable.readdir(oldPath,function(err,files2){if(err){return cb()}copyDirContents(files2)})})}if(newStats&&newStats.isDirectory()){return cb(ApiError.EISDIR(newPath))}this$1.readFile(oldPath,null,getFlag("r"),function(err,data){if(err){return cb(err)}return this$1.writeFile(newPath,data,null,getFlag("w"),oldStats.mode,function(err2){if(err2){return cb(err2)}return this$1.unlink(oldPath,cb)})})})})};UnlockedOverlayFS2.prototype.renameSync=function renameSync(oldPath,newPath){var this$1=this;this.checkInitialized();this.checkPath(oldPath);this.checkPath(newPath);if(oldPath===deletionLogPath||newPath===deletionLogPath){throw ApiError.EPERM("Cannot rename deletion log.")}var oldStats=this.statSync(oldPath,false);if(oldStats.isDirectory()){if(oldPath===newPath){return}var mode=511;if(this.existsSync(newPath)){var stats=this.statSync(newPath,false);mode=stats.mode;if(stats.isDirectory()){if(this.readdirSync(newPath).length>0){throw ApiError.ENOTEMPTY(newPath)}}else{throw ApiError.ENOTDIR(newPath)}}if(this._writable.existsSync(oldPath)){this._writable.renameSync(oldPath,newPath)}else if(!this._writable.existsSync(newPath)){this._writable.mkdirSync(newPath,mode)}if(this._readable.existsSync(oldPath)){this._readable.readdirSync(oldPath).forEach(function(name){this$1.renameSync(path.resolve(oldPath,name),path.resolve(newPath,name))})}}else{if(this.existsSync(newPath)&&this.statSync(newPath,false).isDirectory()){throw ApiError.EISDIR(newPath)}this.writeFileSync(newPath,this.readFileSync(oldPath,null,getFlag("r")),null,getFlag("w"),oldStats.mode)}if(oldPath!==newPath&&this.existsSync(oldPath)){this.unlinkSync(oldPath)}};UnlockedOverlayFS2.prototype.stat=function stat(p,isLstat,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this._writable.stat(p,isLstat,function(err,stat2){if(err&&err.errno===ErrorCode.ENOENT){if(this$1._deletedFiles[p]){cb(ApiError.ENOENT(p))}this$1._readable.stat(p,isLstat,function(err2,stat3){if(stat3){stat3=stat3.clone();stat3.mode=makeModeWritable(stat3.mode)}cb(err2,stat3)})}else{cb(err,stat2)}})};UnlockedOverlayFS2.prototype.statSync=function statSync(p,isLstat){this.checkInitialized();try{return this._writable.statSync(p,isLstat)}catch(e){if(this._deletedFiles[p]){throw ApiError.ENOENT(p)}var oldStat=this._readable.statSync(p,isLstat).clone();oldStat.mode=makeModeWritable(oldStat.mode);return oldStat}};UnlockedOverlayFS2.prototype.open=function open(p,flag,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.stat(p,false,function(err,stats){if(stats){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}this$1._writable.open(p,flag,mode,cb)});case ActionType.NOP:return this$1._writable.exists(p,function(exists2){if(exists2){this$1._writable.open(p,flag,mode,cb)}else{stats=stats.clone();stats.mode=mode;this$1._readable.readFile(p,null,getFlag("r"),function(readFileErr,data){if(readFileErr){return cb(readFileErr)}if(stats.size===-1){stats.size=data.length}var f=new OverlayFile(this$1,p,flag,stats,data);cb(null,f)})}});default:return cb(ApiError.EEXIST(p))}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}return this$1._writable.open(p,flag,mode,cb)});default:return cb(ApiError.ENOENT(p))}}})};UnlockedOverlayFS2.prototype.openSync=function openSync(p,flag,mode){this.checkInitialized();this.checkPath(p);if(p===deletionLogPath){throw ApiError.EPERM("Cannot open deletion log.")}if(this.existsSync(p)){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);case ActionType.NOP:if(this._writable.existsSync(p)){return this._writable.openSync(p,flag,mode)}else{var buf=this._readable.readFileSync(p,null,getFlag("r"));var stats=this._readable.statSync(p,false).clone();stats.mode=mode;return new OverlayFile(this,p,flag,stats,buf)}default:throw ApiError.EEXIST(p)}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);default:throw ApiError.ENOENT(p)}}};UnlockedOverlayFS2.prototype.unlink=function unlink(p,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){return this$1._writable.unlink(p,function(err){if(err){return cb(err)}this$1.exists(p,function(readableExists){if(readableExists){this$1.deletePath(p)}cb(null)})})}else{this$1.deletePath(p);cb(null)}})})};UnlockedOverlayFS2.prototype.unlinkSync=function unlinkSync(p){this.checkInitialized();this.checkPath(p);if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.unlinkSync(p)}if(this.existsSync(p)){this.deletePath(p)}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.rmdir=function rmdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}var rmdirLower=function(){this$1.readdir(p,function(err,files){if(err){return cb(err)}if(files.length){return cb(ApiError.ENOTEMPTY(p))}this$1.deletePath(p);cb(null)})};this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){this$1._writable.rmdir(p,function(err){if(err){return cb(err)}this$1._readable.exists(p,function(readableExists){if(readableExists){rmdirLower()}else{cb()}})})}else{rmdirLower()}})})};UnlockedOverlayFS2.prototype.rmdirSync=function rmdirSync(p){this.checkInitialized();if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.rmdirSync(p)}if(this.existsSync(p)){if(this.readdirSync(p).length>0){throw ApiError.ENOTEMPTY(p)}else{this.deletePath(p)}}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.exists(p,function(exists2){if(exists2){return cb(ApiError.EEXIST(p))}this$1.createParentDirectoriesAsync(p,function(err){if(err){return cb(err)}this$1._writable.mkdir(p,mode,cb)})})};UnlockedOverlayFS2.prototype.mkdirSync=function mkdirSync(p,mode){this.checkInitialized();if(this.existsSync(p)){throw ApiError.EEXIST(p)}else{this.createParentDirectories(p);this._writable.mkdirSync(p,mode)}};UnlockedOverlayFS2.prototype.readdir=function readdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.stat(p,false,function(err,dirStats){if(err){return cb(err)}if(!dirStats.isDirectory()){return cb(ApiError.ENOTDIR(p))}this$1._writable.readdir(p,function(err2,wFiles){if(err2&&err2.code!=="ENOENT"){return cb(err2)}else if(err2||!wFiles){wFiles=[]}this$1._readable.readdir(p,function(err3,rFiles){if(err3||!rFiles){rFiles=[]}var seenMap={};var filtered=wFiles.concat(rFiles.filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]})).filter(function(fPath){var result=!seenMap[fPath];seenMap[fPath]=true;return result});cb(null,filtered)})})})};UnlockedOverlayFS2.prototype.readdirSync=function readdirSync(p){var this$1=this;this.checkInitialized();var dirStats=this.statSync(p,false);if(!dirStats.isDirectory()){throw ApiError.ENOTDIR(p)}var contents=[];try{contents=contents.concat(this._writable.readdirSync(p))}catch(e){}try{contents=contents.concat(this._readable.readdirSync(p).filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]}))}catch(e){}var seenMap={};return contents.filter(function(fileP){var result=!seenMap[fileP];seenMap[fileP]=true;return result})};UnlockedOverlayFS2.prototype.exists=function exists2(p,cb){var this$1=this;this.checkInitialized();this._writable.exists(p,function(existsWritable){if(existsWritable){return cb(true)}this$1._readable.exists(p,function(existsReadable){cb(existsReadable&&this$1._deletedFiles[p]!==true)})})};UnlockedOverlayFS2.prototype.existsSync=function existsSync(p){this.checkInitialized();return this._writable.existsSync(p)||this._readable.existsSync(p)&&this._deletedFiles[p]!==true};UnlockedOverlayFS2.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chmod(p,isLchmod,mode,cb)}})};UnlockedOverlayFS2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chmodSync(p,isLchmod,mode)})};UnlockedOverlayFS2.prototype.chown=function chown(p,isLchmod,uid,gid,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chown(p,isLchmod,uid,gid,cb)}})};UnlockedOverlayFS2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chownSync(p,isLchown,uid,gid)})};UnlockedOverlayFS2.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.utimes(p,atime,mtime,cb)}})};UnlockedOverlayFS2.prototype.utimesSync=function utimesSync(p,atime,mtime){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.utimesSync(p,atime,mtime)})};UnlockedOverlayFS2.prototype.deletePath=function deletePath(p){this._deletedFiles[p]=true;this.updateLog("d"+p+"\n")};UnlockedOverlayFS2.prototype.updateLog=function updateLog(addition){var this$1=this;this._deleteLog+=addition;if(this._deleteLogUpdatePending){this._deleteLogUpdateNeeded=true}else{this._deleteLogUpdatePending=true;this._writable.writeFile(deletionLogPath,this._deleteLog,"utf8",FileFlag.getFileFlag("w"),420,function(e){this$1._deleteLogUpdatePending=false;if(e){this$1._deleteLogError=e}else if(this$1._deleteLogUpdateNeeded){this$1._deleteLogUpdateNeeded=false;this$1.updateLog("")}})}};UnlockedOverlayFS2.prototype._reparseDeletionLog=function _reparseDeletionLog(){var this$1=this;this._deletedFiles={};this._deleteLog.split("\n").forEach(function(path$$1){this$1._deletedFiles[path$$1.slice(1)]=path$$1.slice(0,1)==="d"})};UnlockedOverlayFS2.prototype.checkInitialized=function checkInitialized(){if(!this._isInitialized){throw new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;throw e}};UnlockedOverlayFS2.prototype.checkInitAsync=function checkInitAsync(cb){if(!this._isInitialized){cb(new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it."));return false}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;cb(e);return false}return true};UnlockedOverlayFS2.prototype.checkPath=function checkPath(p){if(p===deletionLogPath){throw ApiError.EPERM(p)}};UnlockedOverlayFS2.prototype.checkPathAsync=function checkPathAsync(p,cb){if(p===deletionLogPath){cb(ApiError.EPERM(p));return true}return false};UnlockedOverlayFS2.prototype.createParentDirectoriesAsync=function createParentDirectoriesAsync(p,cb){var parent=path.dirname(p);var toCreate=[];var self2=this;this._writable.stat(parent,false,statDone);function statDone(err,stat){if(err){toCreate.push(parent);parent=path.dirname(parent);self2._writable.stat(parent,false,statDone)}else{createParents()}}function createParents(){if(!toCreate.length){return cb()}var dir=toCreate.pop();self2._readable.stat(dir,false,function(err,stats){if(!stats){return cb()}self2._writable.mkdir(dir,stats.mode,function(err2){if(err2){return cb(err2)}createParents()})})}};UnlockedOverlayFS2.prototype.createParentDirectories=function createParentDirectories(p){var this$1=this;var parent=path.dirname(p),toCreate=[];while(!this._writable.existsSync(parent)){toCreate.push(parent);parent=path.dirname(parent)}toCreate=toCreate.reverse();toCreate.forEach(function(p2){this$1._writable.mkdirSync(p2,this$1.statSync(p2,false).mode)})};UnlockedOverlayFS2.prototype.operateOnWritable=function operateOnWritable(p,f){if(this.existsSync(p)){if(!this._writable.existsSync(p)){this.copyToWritable(p)}f()}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.operateOnWritableAsync=function operateOnWritableAsync(p,cb){var this$1=this;this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(existsWritable){if(existsWritable){cb()}else{return this$1.copyToWritableAsync(p,cb)}})})};UnlockedOverlayFS2.prototype.copyToWritable=function copyToWritable(p){var pStats=this.statSync(p,false);if(pStats.isDirectory()){this._writable.mkdirSync(p,pStats.mode)}else{this.writeFileSync(p,this._readable.readFileSync(p,null,getFlag("r")),null,getFlag("w"),this.statSync(p,false).mode)}};UnlockedOverlayFS2.prototype.copyToWritableAsync=function copyToWritableAsync(p,cb){var this$1=this;this.stat(p,false,function(err,pStats){if(err){return cb(err)}if(pStats.isDirectory()){return this$1._writable.mkdir(p,pStats.mode,cb)}this$1._readable.readFile(p,null,getFlag("r"),function(err2,data){if(err2){return cb(err2)}this$1.writeFile(p,data,null,getFlag("w"),pStats.mode,cb)})})};return UnlockedOverlayFS2}(BaseFileSystem);var OverlayFS=function(LockedFS$$1){function OverlayFS2(writable,readable,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;LockedFS$$1.call(this,new UnlockedOverlayFS(writable,readable));deprecationMessage(deprecateMsg,OverlayFS2.Name,{readable:"readable file system",writable:"writable file system"})}if(LockedFS$$1)OverlayFS2.__proto__=LockedFS$$1;OverlayFS2.prototype=Object.create(LockedFS$$1&&LockedFS$$1.prototype);OverlayFS2.prototype.constructor=OverlayFS2;OverlayFS2.Create=function Create(opts,cb){try{var fs4=new OverlayFS2(opts.writable,opts.readable,false);fs4.initialize(function(e){cb(e,fs4)},false)}catch(e){cb(e)}};OverlayFS2.isAvailable=function isAvailable(){return UnlockedOverlayFS.isAvailable()};OverlayFS2.prototype.initialize=function initialize3(cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.")}LockedFS$$1.prototype.initialize.call(this,cb)};OverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return LockedFS$$1.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()};OverlayFS2.prototype.unwrap=function unwrap(){return LockedFS$$1.prototype.getFSUnlocked.call(this)};return OverlayFS2}(LockedFS);OverlayFS.Name="OverlayFS";OverlayFS.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var SpecialArgType;(function(SpecialArgType2){SpecialArgType2[SpecialArgType2["CB"]=0]="CB";SpecialArgType2[SpecialArgType2["FD"]=1]="FD";SpecialArgType2[SpecialArgType2["API_ERROR"]=2]="API_ERROR";SpecialArgType2[SpecialArgType2["STATS"]=3]="STATS";SpecialArgType2[SpecialArgType2["PROBE"]=4]="PROBE";SpecialArgType2[SpecialArgType2["FILEFLAG"]=5]="FILEFLAG";SpecialArgType2[SpecialArgType2["BUFFER"]=6]="BUFFER";SpecialArgType2[SpecialArgType2["ERROR"]=7]="ERROR"})(SpecialArgType||(SpecialArgType={}));var CallbackArgumentConverter=function CallbackArgumentConverter2(){this._callbacks={};this._nextId=0};CallbackArgumentConverter.prototype.toRemoteArg=function toRemoteArg(cb){var id=this._nextId++;this._callbacks[id]=cb;return{type:SpecialArgType.CB,id}};CallbackArgumentConverter.prototype.toLocalArg=function toLocalArg(id){var cb=this._callbacks[id];delete this._callbacks[id];return cb};var FileDescriptorArgumentConverter=function FileDescriptorArgumentConverter2(){this._fileDescriptors={};this._nextId=0};FileDescriptorArgumentConverter.prototype.toRemoteArg=function toRemoteArg(fd,p,flag,cb){var id=this._nextId++;var data;var stat;this._fileDescriptors[id]=fd;fd.stat(function(err,stats){if(err){cb(err)}else{stat=bufferToTransferrableObject(stats.toBuffer());if(flag.isReadable()){fd.read(Buffer2.alloc(stats.size),0,stats.size,0,function(err2,bytesRead,buff){if(err2){cb(err2)}else{data=bufferToTransferrableObject(buff);cb(null,{type:SpecialArgType.FD,id,data,stat,path:p,flag:flag.getFlagString()})}})}else{cb(null,{type:SpecialArgType.FD,id,data:new ArrayBuffer(0),stat,path:p,flag:flag.getFlagString()})}}})};FileDescriptorArgumentConverter.prototype.applyFdAPIRequest=function applyFdAPIRequest(request,cb){var this$1=this;var fdArg=request.args[0];this._applyFdChanges(fdArg,function(err,fd){if(err){cb(err)}else{fd[request.method](function(e){if(request.method==="close"){delete this$1._fileDescriptors[fdArg.id]}cb(e)})}})};FileDescriptorArgumentConverter.prototype._applyFdChanges=function _applyFdChanges(remoteFd,cb){var fd=this._fileDescriptors[remoteFd.id],data=transferrableObjectToBuffer(remoteFd.data),remoteStats=Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));var flag=FileFlag.getFileFlag(remoteFd.flag);if(flag.isWriteable()){fd.write(data,0,data.length,flag.isAppendable()?fd.getPos():0,function(e){function applyStatChanges(){fd.stat(function(e2,stats){if(e2){cb(e2)}else{if(stats.mode!==remoteStats.mode){fd.chmod(remoteStats.mode,function(e3){cb(e3,fd)})}else{cb(e2,fd)}}})}if(e){cb(e)}else{if(!flag.isAppendable()){fd.truncate(data.length,function(){applyStatChanges()})}else{applyStatChanges()}}})}else{cb(null,fd)}};function apiErrorLocal2Remote(e){return{type:SpecialArgType.API_ERROR,errorData:bufferToTransferrableObject(e.writeToBuffer())}}function apiErrorRemote2Local(e){return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData))}function errorLocal2Remote(e){return{type:SpecialArgType.ERROR,name:e.name,message:e.message,stack:e.stack}}function errorRemote2Local(e){var cnstr=global$1[e.name];if(typeof cnstr!=="function"){cnstr=Error}var err=new cnstr(e.message);err.stack=e.stack;return err}function statsLocal2Remote(stats){return{type:SpecialArgType.STATS,statsData:bufferToTransferrableObject(stats.toBuffer())}}function statsRemote2Local(stats){return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData))}function fileFlagLocal2Remote(flag){return{type:SpecialArgType.FILEFLAG,flagStr:flag.getFlagString()}}function fileFlagRemote2Local(remoteFlag){return FileFlag.getFileFlag(remoteFlag.flagStr)}function bufferToTransferrableObject(buff){return buffer2ArrayBuffer(buff)}function transferrableObjectToBuffer(buff){return arrayBuffer2Buffer(buff)}function bufferLocal2Remote(buff){return{type:SpecialArgType.BUFFER,data:bufferToTransferrableObject(buff)}}function bufferRemote2Local(buffArg){return transferrableObjectToBuffer(buffArg.data)}function isAPIRequest(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}function isAPIResponse(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}var WorkerFile=function(PreloadFile$$1){function WorkerFile2(_fs,_path,_flag,_stat,remoteFdId,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents);this._remoteFdId=remoteFdId}if(PreloadFile$$1)WorkerFile2.__proto__=PreloadFile$$1;WorkerFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);WorkerFile2.prototype.constructor=WorkerFile2;WorkerFile2.prototype.getRemoteFdId=function getRemoteFdId(){return this._remoteFdId};WorkerFile2.prototype.toRemoteArg=function toRemoteArg(){return{type:SpecialArgType.FD,id:this._remoteFdId,data:bufferToTransferrableObject(this.getBuffer()),stat:bufferToTransferrableObject(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}};WorkerFile2.prototype.sync=function sync(cb){this._syncClose("sync",cb)};WorkerFile2.prototype.close=function close(cb){this._syncClose("close",cb)};WorkerFile2.prototype._syncClose=function _syncClose(type,cb){var this$1=this;if(this.isDirty()){this._fs.syncClose(type,this,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};return WorkerFile2}(PreloadFile);var WorkerFS=function(BaseFileSystem$$1){function WorkerFS2(worker,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._callbackConverter=new CallbackArgumentConverter;this._isInitialized=false;this._isReadOnly=false;this._supportLinks=false;this._supportProps=false;this._worker=worker;deprecationMessage(deprecateMsg,WorkerFS2.Name,{worker:"Web Worker instance"});this._worker.addEventListener("message",function(e){var resp=e.data;if(isAPIResponse(resp)){var i2;var args=resp.args;var fixedArgs=new Array(args.length);for(i2=0;i20){countdown=-1;message={browserfsMessage:true,cbId,args:[apiErrorLocal2Remote(err)]};worker.postMessage(message)}}for(i2=0;i20){var inode=void 0;var next=queue.pop();var pwd=next[0];var tree=next[1];var parent=next[2];for(var node in tree){if(tree.hasOwnProperty(node)){var children=tree[node];var name=pwd+"/"+node;if(children){idx._index[name]=inode=new DirInode;queue.push([name,children,inode])}else{inode=new FileInode(new Stats(FileType.FILE,-1,365))}if(parent){parent._ls[node]=inode}}}}return idx};FileIndex.prototype.fileIterator=function fileIterator(cb){var this$1=this;for(var path$$1 in this$1._index){if(this$1._index.hasOwnProperty(path$$1)){var dir=this$1._index[path$$1];var files=dir.getListing();for(var i2=0,list2=files;i20&&prefixUrl.charAt(prefixUrl.length-1)!=="/"){prefixUrl=prefixUrl+"/"}this.prefixUrl=prefixUrl;var listing=null;if(typeof listingUrlOrObj==="string"){listing=this._requestFileSync(listingUrlOrObj,"json");if(!listing){throw new Error("Unable to find listing at URL: ${listingUrlOrObj}")}}else{listing=listingUrlOrObj}deprecationMessage(deprecateMsg,XmlHttpRequest2.Name,{index:typeof listingUrlOrObj==="string"?listingUrlOrObj:"file index as an object",baseUrl:prefixUrl});this._index=FileIndex.fromListing(listing)}if(BaseFileSystem$$1)XmlHttpRequest2.__proto__=BaseFileSystem$$1;XmlHttpRequest2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);XmlHttpRequest2.prototype.constructor=XmlHttpRequest2;XmlHttpRequest2.Create=function Create(opts,cb){if(opts.index===void 0){opts.index="index.json"}if(typeof opts.index==="string"){XmlHttpRequest2.FromURL(opts.index,cb,opts.baseUrl,false)}else{cb(null,new XmlHttpRequest2(opts.index,opts.baseUrl,false))}};XmlHttpRequest2.isAvailable=function isAvailable(){return typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest!==null};XmlHttpRequest2.FromURL=function FromURL(url,cb,baseUrl,deprecateMsg){if(baseUrl===void 0)baseUrl=url.slice(0,url.lastIndexOf("/")+1);if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn(`[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: "`+url+'", baseUrl: "'+baseUrl+`" }, cb)' instead.`)}asyncDownloadFile(url,"json",function(e,data){if(e){cb(e)}else{cb(null,new XmlHttpRequest2(data,baseUrl,false))}})};XmlHttpRequest2.prototype.empty=function empty(){this._index.fileIterator(function(file){file.fileData=null})};XmlHttpRequest2.prototype.getName=function getName(){return XmlHttpRequest2.Name};XmlHttpRequest2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};XmlHttpRequest2.prototype.isReadOnly=function isReadOnly(){return true};XmlHttpRequest2.prototype.supportsLinks=function supportsLinks(){return false};XmlHttpRequest2.prototype.supportsProps=function supportsProps(){return false};XmlHttpRequest2.prototype.supportsSynch=function supportsSynch(){return true};XmlHttpRequest2.prototype.preloadFile=function preloadFile(path$$1,buffer$$1){var inode=this._index.getInode(path$$1);if(isFileInode(inode)){if(inode===null){throw ApiError.ENOENT(path$$1)}var stats=inode.getData();stats.size=buffer$$1.length;stats.fileData=buffer$$1}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.stat=function stat(path$$1,isLstat,cb){var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){this._requestFileSizeAsync(path$$1,function(e,size){if(e){return cb(e)}stats.size=size;cb(null,stats.clone())})}else{cb(null,stats.clone())}}else if(isDirInode(inode)){stats=inode.getStats();cb(null,stats)}else{cb(ApiError.FileError(ErrorCode.EINVAL,path$$1))}};XmlHttpRequest2.prototype.statSync=function statSync(path$$1,isLstat){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){stats.size=this._requestFileSizeSync(path$$1)}}else if(isDirInode(inode)){stats=inode.getStats()}else{throw ApiError.FileError(ErrorCode.EINVAL,path$$1)}return stats};XmlHttpRequest2.prototype.open=function open(path$$1,flags,mode,cb){if(flags.isWriteable()){return cb(new ApiError(ErrorCode.EPERM,path$$1))}var self2=this;var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:return cb(ApiError.EEXIST(path$$1));case ActionType.NOP:if(stats.fileData){return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),stats.fileData))}this._requestFileAsync(path$$1,"buffer",function(err,buffer$$1){if(err){return cb(err)}stats.size=buffer$$1.length;stats.fileData=buffer$$1;return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),buffer$$1))});break;default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileMode object."))}}else{return cb(ApiError.EISDIR(path$$1))}};XmlHttpRequest2.prototype.openSync=function openSync(path$$1,flags,mode){if(flags.isWriteable()){throw new ApiError(ErrorCode.EPERM,path$$1)}var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:throw ApiError.EEXIST(path$$1);case ActionType.NOP:if(stats.fileData){return new NoSyncFile(this,path$$1,flags,stats.clone(),stats.fileData)}var buffer$$1=this._requestFileSync(path$$1,"buffer");stats.size=buffer$$1.length;stats.fileData=buffer$$1;return new NoSyncFile(this,path$$1,flags,stats.clone(),buffer$$1);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileMode object.")}}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.readdir=function readdir(path$$1,cb){try{cb(null,this.readdirSync(path$$1))}catch(e){cb(e)}};XmlHttpRequest2.prototype.readdirSync=function readdirSync(path$$1){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}else if(isDirInode(inode)){return inode.getListing()}else{throw ApiError.ENOTDIR(path$$1)}};XmlHttpRequest2.prototype.readFile=function readFile2(fname,encoding,flag,cb){var oldCb=cb;this.open(fname,flag,420,function(err,fd){if(err){return cb(err)}cb=function(err2,arg){fd.close(function(err22){if(!err2){err2=err22}return oldCb(err2,arg)})};var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){cb(err,copyingSlice(fdBuff))}else{tryToString(fdBuff,encoding,cb)}})};XmlHttpRequest2.prototype.readFileSync=function readFileSync(fname,encoding,flag){var fd=this.openSync(fname,flag,420);try{var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){return copyingSlice(fdBuff)}return fdBuff.toString(encoding)}finally{fd.closeSync()}};XmlHttpRequest2.prototype.getXhrPath=function getXhrPath(filePath){if(filePath.charAt(0)==="/"){filePath=filePath.slice(1)}return this.prefixUrl+filePath};XmlHttpRequest2.prototype._requestFileAsync=function _requestFileAsync(p,type,cb){asyncDownloadFile(this.getXhrPath(p),type,cb)};XmlHttpRequest2.prototype._requestFileSync=function _requestFileSync(p,type){return syncDownloadFile(this.getXhrPath(p),type)};XmlHttpRequest2.prototype._requestFileSizeAsync=function _requestFileSizeAsync(path$$1,cb){getFileSizeAsync(this.getXhrPath(path$$1),cb)};XmlHttpRequest2.prototype._requestFileSizeSync=function _requestFileSizeSync(path$$1){return getFileSizeSync(this.getXhrPath(path$$1))};return XmlHttpRequest2}(BaseFileSystem);XmlHttpRequest.Name="XmlHttpRequest";XmlHttpRequest.Options={index:{type:["string","object"],optional:true,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:true,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."}};var ExtendedASCII=function ExtendedASCII2(){};ExtendedASCII.str2byte=function str2byte(str,buf){var length=str.length>buf.length?buf.length:str.length;for(var i2=0;i2127){var charIdx=ExtendedASCII.extendedChars.indexOf(str.charAt(i2));if(charIdx>-1){charCode=charIdx+128}}buf[charCode]=i2}return length};ExtendedASCII.byte2str=function byte2str(buff){var chars=new Array(buff.length);for(var i2=0;i2127){chars[i2]=ExtendedASCII.extendedChars[charCode-128]}else{chars[i2]=String.fromCharCode(charCode)}}return chars.join("")};ExtendedASCII.byteLength=function byteLength(str){return str.length};ExtendedASCII.extendedChars=["\xC7","\xFC","\xE9","\xE2","\xE4","\xE0","\xE5","\xE7","\xEA","\xEB","\xE8","\xEF","\xEE","\xEC","\xC4","\xC5","\xC9","\xE6","\xC6","\xF4","\xF6","\xF2","\xFB","\xF9","\xFF","\xD6","\xDC","\xF8","\xA3","\xD8","\xD7","\u0192","\xE1","\xED","\xF3","\xFA","\xF1","\xD1","\xAA","\xBA","\xBF","\xAE","\xAC","\xBD","\xBC","\xA1","\xAB","\xBB","_","_","_","\xA6","\xA6","\xC1","\xC2","\xC0","\xA9","\xA6","\xA6","+","+","\xA2","\xA5","+","+","-","-","+","-","+","\xE3","\xC3","+","+","-","-","\xA6","-","+","\xA4","\xF0","\xD0","\xCA","\xCB","\xC8","i","\xCD","\xCE","\xCF","+","+","_","_","\xA6","\xCC","_","\xD3","\xDF","\xD4","\xD2","\xF5","\xD5","\xB5","\xFE","\xDE","\xDA","\xDB","\xD9","\xFD","\xDD","\xAF","\xB4","\xAD","\xB1","_","\xBE","\xB6","\xA7","\xF7","\xB8","\xB0","\xA8","\xB7","\xB9","\xB3","\xB2","_"," "];var inflateRaw=__webpack_require__(31).inflateRaw;var decompressionMethods={};var ExternalFileAttributeType;(function(ExternalFileAttributeType2){ExternalFileAttributeType2[ExternalFileAttributeType2["MSDOS"]=0]="MSDOS";ExternalFileAttributeType2[ExternalFileAttributeType2["AMIGA"]=1]="AMIGA";ExternalFileAttributeType2[ExternalFileAttributeType2["OPENVMS"]=2]="OPENVMS";ExternalFileAttributeType2[ExternalFileAttributeType2["UNIX"]=3]="UNIX";ExternalFileAttributeType2[ExternalFileAttributeType2["VM_CMS"]=4]="VM_CMS";ExternalFileAttributeType2[ExternalFileAttributeType2["ATARI_ST"]=5]="ATARI_ST";ExternalFileAttributeType2[ExternalFileAttributeType2["OS2_HPFS"]=6]="OS2_HPFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MAC"]=7]="MAC";ExternalFileAttributeType2[ExternalFileAttributeType2["Z_SYSTEM"]=8]="Z_SYSTEM";ExternalFileAttributeType2[ExternalFileAttributeType2["CP_M"]=9]="CP_M";ExternalFileAttributeType2[ExternalFileAttributeType2["NTFS"]=10]="NTFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MVS"]=11]="MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["VSE"]=12]="VSE";ExternalFileAttributeType2[ExternalFileAttributeType2["ACORN_RISC"]=13]="ACORN_RISC";ExternalFileAttributeType2[ExternalFileAttributeType2["VFAT"]=14]="VFAT";ExternalFileAttributeType2[ExternalFileAttributeType2["ALT_MVS"]=15]="ALT_MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["BEOS"]=16]="BEOS";ExternalFileAttributeType2[ExternalFileAttributeType2["TANDEM"]=17]="TANDEM";ExternalFileAttributeType2[ExternalFileAttributeType2["OS_400"]=18]="OS_400";ExternalFileAttributeType2[ExternalFileAttributeType2["OSX"]=19]="OSX"})(ExternalFileAttributeType||(ExternalFileAttributeType={}));var CompressionMethod;(function(CompressionMethod2){CompressionMethod2[CompressionMethod2["STORED"]=0]="STORED";CompressionMethod2[CompressionMethod2["SHRUNK"]=1]="SHRUNK";CompressionMethod2[CompressionMethod2["REDUCED_1"]=2]="REDUCED_1";CompressionMethod2[CompressionMethod2["REDUCED_2"]=3]="REDUCED_2";CompressionMethod2[CompressionMethod2["REDUCED_3"]=4]="REDUCED_3";CompressionMethod2[CompressionMethod2["REDUCED_4"]=5]="REDUCED_4";CompressionMethod2[CompressionMethod2["IMPLODE"]=6]="IMPLODE";CompressionMethod2[CompressionMethod2["DEFLATE"]=8]="DEFLATE";CompressionMethod2[CompressionMethod2["DEFLATE64"]=9]="DEFLATE64";CompressionMethod2[CompressionMethod2["TERSE_OLD"]=10]="TERSE_OLD";CompressionMethod2[CompressionMethod2["BZIP2"]=12]="BZIP2";CompressionMethod2[CompressionMethod2["LZMA"]=14]="LZMA";CompressionMethod2[CompressionMethod2["TERSE_NEW"]=18]="TERSE_NEW";CompressionMethod2[CompressionMethod2["LZ77"]=19]="LZ77";CompressionMethod2[CompressionMethod2["WAVPACK"]=97]="WAVPACK";CompressionMethod2[CompressionMethod2["PPMD"]=98]="PPMD"})(CompressionMethod||(CompressionMethod={}));function msdos2date(time,date){var day=date&31;var month=(date>>5&15)-1;var year=(date>>9)+1980;var second=time&31;var minute=time>>5&63;var hour=time>>11;return new Date(year,month,day,hour,minute,second)}function safeToString(buff,useUTF8,start,length){if(length===0){return""}else if(useUTF8){return buff.toString("utf8",start,start+length)}else{return ExtendedASCII.byte2str(buff.slice(start,start+length))}}var FileHeader=function FileHeader2(data){this.data=data;if(data.readUInt32LE(0)!==67324752){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))}};FileHeader.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(4)};FileHeader.prototype.flags=function flags(){return this.data.readUInt16LE(6)};FileHeader.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(8)};FileHeader.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(10),this.data.readUInt16LE(12))};FileHeader.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(10)};FileHeader.prototype.crc32=function crc32(){return this.data.readUInt32LE(14)};FileHeader.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(26)};FileHeader.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(28)};FileHeader.prototype.fileName=function fileName(){return safeToString(this.data,this.useUTF8(),30,this.fileNameLength())};FileHeader.prototype.extraField=function extraField(){var start=30+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};FileHeader.prototype.totalSize=function totalSize(){return 30+this.fileNameLength()+this.extraFieldLength()};FileHeader.prototype.useUTF8=function useUTF8(){return(this.flags()&2048)===2048};var FileData=function FileData2(header,record,data){this.header=header;this.record=record;this.data=data};FileData.prototype.decompress=function decompress(){var compressionMethod=this.header.compressionMethod();var fcn=decompressionMethods[compressionMethod];if(fcn){return fcn(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag())}else{var name=CompressionMethod[compressionMethod];if(!name){name="Unknown: "+compressionMethod}throw new ApiError(ErrorCode.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+name)}};FileData.prototype.getHeader=function getHeader(){return this.header};FileData.prototype.getRecord=function getRecord(){return this.record};FileData.prototype.getRawData=function getRawData(){return this.data};var DataDescriptor=function DataDescriptor2(data){this.data=data};DataDescriptor.prototype.crc32=function crc32(){return this.data.readUInt32LE(0)};DataDescriptor.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(4)};DataDescriptor.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(8)};var ArchiveExtraDataRecord=function ArchiveExtraDataRecord2(data){this.data=data;if(this.data.readUInt32LE(0)!==134630224){throw new ApiError(ErrorCode.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))}};ArchiveExtraDataRecord.prototype.length=function length(){return this.data.readUInt32LE(4)};ArchiveExtraDataRecord.prototype.extraFieldData=function extraFieldData(){return this.data.slice(8,8+this.length())};var DigitalSignature=function DigitalSignature2(data){this.data=data;if(this.data.readUInt32LE(0)!==84233040){throw new ApiError(ErrorCode.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))}};DigitalSignature.prototype.size=function size(){return this.data.readUInt16LE(4)};DigitalSignature.prototype.signatureData=function signatureData(){return this.data.slice(6,6+this.size())};var CentralDirectory=function CentralDirectory2(zipData,data){this.zipData=zipData;this.data=data;if(this.data.readUInt32LE(0)!==33639248){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0))}this._filename=this.produceFilename()};CentralDirectory.prototype.versionMadeBy=function versionMadeBy(){return this.data.readUInt16LE(4)};CentralDirectory.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(6)};CentralDirectory.prototype.flag=function flag(){return this.data.readUInt16LE(8)};CentralDirectory.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(10)};CentralDirectory.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(12),this.data.readUInt16LE(14))};CentralDirectory.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(12)};CentralDirectory.prototype.crc32=function crc32(){return this.data.readUInt32LE(16)};CentralDirectory.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(20)};CentralDirectory.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(24)};CentralDirectory.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(28)};CentralDirectory.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(30)};CentralDirectory.prototype.fileCommentLength=function fileCommentLength(){return this.data.readUInt16LE(32)};CentralDirectory.prototype.diskNumberStart=function diskNumberStart(){return this.data.readUInt16LE(34)};CentralDirectory.prototype.internalAttributes=function internalAttributes(){return this.data.readUInt16LE(36)};CentralDirectory.prototype.externalAttributes=function externalAttributes(){return this.data.readUInt32LE(38)};CentralDirectory.prototype.headerRelativeOffset=function headerRelativeOffset(){return this.data.readUInt32LE(42)};CentralDirectory.prototype.produceFilename=function produceFilename(){var fileName=safeToString(this.data,this.useUTF8(),46,this.fileNameLength());return fileName.replace(/\\/g,"/")};CentralDirectory.prototype.fileName=function fileName(){return this._filename};CentralDirectory.prototype.rawFileName=function rawFileName(){return this.data.slice(46,46+this.fileNameLength())};CentralDirectory.prototype.extraField=function extraField(){var start=44+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};CentralDirectory.prototype.fileComment=function fileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return safeToString(this.data,this.useUTF8(),start,this.fileCommentLength())};CentralDirectory.prototype.rawFileComment=function rawFileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(start,start+this.fileCommentLength())};CentralDirectory.prototype.totalSize=function totalSize(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()};CentralDirectory.prototype.isDirectory=function isDirectory(){var fileName=this.fileName();return(this.externalAttributes()&16?true:false)||fileName.charAt(fileName.length-1)==="/"};CentralDirectory.prototype.isFile=function isFile(){return!this.isDirectory()};CentralDirectory.prototype.useUTF8=function useUTF8(){return(this.flag()&2048)===2048};CentralDirectory.prototype.isEncrypted=function isEncrypted(){return(this.flag()&1)===1};CentralDirectory.prototype.getFileData=function getFileData(){var start=this.headerRelativeOffset();var header=new FileHeader(this.zipData.slice(start));return new FileData(header,this,this.zipData.slice(start+header.totalSize()))};CentralDirectory.prototype.getData=function getData(){return this.getFileData().decompress()};CentralDirectory.prototype.getRawData=function getRawData(){return this.getFileData().getRawData()};CentralDirectory.prototype.getStats=function getStats(){return new Stats(FileType.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var EndOfCentralDirectory=function EndOfCentralDirectory2(data){this.data=data;if(this.data.readUInt32LE(0)!==101010256){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))}};EndOfCentralDirectory.prototype.diskNumber=function diskNumber(){return this.data.readUInt16LE(4)};EndOfCentralDirectory.prototype.cdDiskNumber=function cdDiskNumber(){return this.data.readUInt16LE(6)};EndOfCentralDirectory.prototype.cdDiskEntryCount=function cdDiskEntryCount(){return this.data.readUInt16LE(8)};EndOfCentralDirectory.prototype.cdTotalEntryCount=function cdTotalEntryCount(){return this.data.readUInt16LE(10)};EndOfCentralDirectory.prototype.cdSize=function cdSize(){return this.data.readUInt32LE(12)};EndOfCentralDirectory.prototype.cdOffset=function cdOffset(){return this.data.readUInt32LE(16)};EndOfCentralDirectory.prototype.cdZipCommentLength=function cdZipCommentLength(){return this.data.readUInt16LE(20)};EndOfCentralDirectory.prototype.cdZipComment=function cdZipComment(){return safeToString(this.data,true,22,this.cdZipCommentLength())};EndOfCentralDirectory.prototype.rawCdZipComment=function rawCdZipComment(){return this.data.slice(22,22+this.cdZipCommentLength())};var ZipTOC=function ZipTOC2(index,directoryEntries,eocd,data){this.index=index;this.directoryEntries=directoryEntries;this.eocd=eocd;this.data=data};var ZipFS=function(SynchronousFileSystem$$1){function ZipFS2(input,name,deprecateMsg){if(name===void 0)name="";if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this.name=name;this._index=new FileIndex;this._directoryEntries=[];this._eocd=null;deprecationMessage(deprecateMsg,ZipFS2.Name,{zipData:"zip data as a Buffer",name});if(input instanceof ZipTOC){this._index=input.index;this._directoryEntries=input.directoryEntries;this._eocd=input.eocd;this.data=input.data}else{this.data=input;this.populateIndex()}}if(SynchronousFileSystem$$1)ZipFS2.__proto__=SynchronousFileSystem$$1;ZipFS2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);ZipFS2.prototype.constructor=ZipFS2;ZipFS2.Create=function Create(opts,cb){try{ZipFS2.computeIndex(opts.zipData,function(zipTOC){var fs4=new ZipFS2(zipTOC,opts.name,false);cb(null,fs4)},false)}catch(e){cb(e)}};ZipFS2.isAvailable=function isAvailable(){return true};ZipFS2.RegisterDecompressionMethod=function RegisterDecompressionMethod(m,fcn){decompressionMethods[m]=fcn};ZipFS2.computeIndex=function computeIndex(data,cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.")}var index=new FileIndex;var eocd=ZipFS2.getEOCD(data);if(eocd.diskNumber()!==eocd.cdDiskNumber()){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support spanned zip files.")}var cdPtr=eocd.cdOffset();if(cdPtr===4294967295){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support Zip64.")}var cdEnd=cdPtr+eocd.cdSize();ZipFS2.computeIndexResponsive(data,index,cdPtr,cdEnd,cb,[],eocd)};ZipFS2.getEOCD=function getEOCD(data){var startOffset=22;var endOffset=Math.min(startOffset+65535,data.length-1);for(var i2=startOffset;i2-1};DirectoryRecord.prototype.getRockRidgeOffset=function getRockRidgeOffset(){return this._rockRidgeOffset};DirectoryRecord.prototype.rootCheckForRockRidge=function rootCheckForRockRidge(isoData){var dir=this.getDirectory(isoData);this._rockRidgeOffset=dir.getDotEntry(isoData)._getRockRidgeOffset(isoData);if(this._rockRidgeOffset>-1){this._fileOrDir=null}};DirectoryRecord.prototype.length=function length(){return this._data[0]};DirectoryRecord.prototype.extendedAttributeRecordLength=function extendedAttributeRecordLength(){return this._data[1]};DirectoryRecord.prototype.lba=function lba(){return this._data.readUInt32LE(2)*2048};DirectoryRecord.prototype.dataLength=function dataLength(){return this._data.readUInt32LE(10)};DirectoryRecord.prototype.recordingDate=function recordingDate(){return getShortFormDate(this._data,18)};DirectoryRecord.prototype.fileFlags=function fileFlags(){return this._data[25]};DirectoryRecord.prototype.fileUnitSize=function fileUnitSize(){return this._data[26]};DirectoryRecord.prototype.interleaveGapSize=function interleaveGapSize(){return this._data[27]};DirectoryRecord.prototype.volumeSequenceNumber=function volumeSequenceNumber(){return this._data.readUInt16LE(28)};DirectoryRecord.prototype.identifier=function identifier(){return this._getString(33,this._data[32])};DirectoryRecord.prototype.fileName=function fileName(isoData){if(this.hasRockRidge()){var fn=this._rockRidgeFilename(isoData);if(fn!==null){return fn}}var ident=this.identifier();if(this.isDirectory(isoData)){return ident}var versionSeparator=ident.indexOf(";");if(versionSeparator===-1){return ident}else if(ident[versionSeparator-1]==="."){return ident.slice(0,versionSeparator-1)}else{return ident.slice(0,versionSeparator)}};DirectoryRecord.prototype.isDirectory=function isDirectory(isoData){var rv=!!(this.fileFlags()&2);if(!rv&&this.hasRockRidge()){rv=this.getSUEntries(isoData).filter(function(e){return e instanceof CLEntry}).length>0}return rv};DirectoryRecord.prototype.isSymlink=function isSymlink(isoData){return this.hasRockRidge()&&this.getSUEntries(isoData).filter(function(e){return e instanceof SLEntry}).length>0};DirectoryRecord.prototype.getSymlinkPath=function getSymlinkPath(isoData){var p="";var entries=this.getSUEntries(isoData);var getStr=this._getGetString();for(var i2=0,list2=entries;i21&&p[p.length-1]==="/"){return p.slice(0,p.length-1)}else{return p}};DirectoryRecord.prototype.getFile=function getFile(isoData){if(this.isDirectory(isoData)){throw new Error("Tried to get a File from a directory.")}if(this._fileOrDir===null){this._fileOrDir=isoData.slice(this.lba(),this.lba()+this.dataLength())}return this._fileOrDir};DirectoryRecord.prototype.getDirectory=function getDirectory(isoData){if(!this.isDirectory(isoData)){throw new Error("Tried to get a Directory from a file.")}if(this._fileOrDir===null){this._fileOrDir=this._constructDirectory(isoData)}return this._fileOrDir};DirectoryRecord.prototype.getSUEntries=function getSUEntries(isoData){if(!this._suEntries){this._constructSUEntries(isoData)}return this._suEntries};DirectoryRecord.prototype._rockRidgeFilename=function _rockRidgeFilename(isoData){var nmEntries=this.getSUEntries(isoData).filter(function(e2){return e2 instanceof NMEntry});if(nmEntries.length===0||nmEntries[0].flags()&(2|4)){return null}var str="";var getString=this._getGetString();for(var i2=0,list2=nmEntries;i20){var spEntry=suEntries[0];if(spEntry instanceof SPEntry&&spEntry.checkBytesPass()){for(var i2=1;i2K_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer2.prototype;return buf}function Buffer2(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer2[Symbol.species]===Buffer2){Object.defineProperty(Buffer2,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer2.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer2.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer2.prototype.__proto__=Uint8Array.prototype;Buffer2.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==void 0){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer2.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer2.allocUnsafe=function(size){return allocUnsafe(size)};Buffer2.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer2.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer2.alloc(+length)}Buffer2.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};Buffer2.compare=function compare(a,b){if(!Buffer2.isBuffer(a)||!Buffer2.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer2.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===void 0||start<0){start=0}if(start>this.length){return""}if(end===void 0||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer2.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer2.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer2.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer2.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===void 0){start=0}if(end===void 0){end=target?target.length:0}if(thisStart===void 0){thisStart=0}if(thisEnd===void 0){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer2.from(val,encoding)}if(Buffer2.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==void 0){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i2){if(indexSize===1){return buf[i2]}else{return buf.readUInt16BE(i2*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===void 0)encoding="utf8"}else{encoding=length;length=void 0}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===void 0||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer2.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer2.prototype.readUIntLE=function readUIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){checkOffset(offset,byteLength2,this.length)}var val=this[offset+--byteLength2];var mul=1;while(byteLength2>0&&(mul*=256)){val+=this[offset+--byteLength2]*mul}return val};Buffer2.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer2.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer2.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer2.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer2.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer2.prototype.readIntLE=function readIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readIntBE=function readIntBE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var i=byteLength2;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer2.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer2.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer2.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer2.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer2.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer2.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer2.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer2.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var i=byteLength2-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength2};Buffer2.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer2.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer2.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer2.prototype.writeIntLE=function writeIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeIntBE=function writeIntBE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=byteLength2-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer2.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer2.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer2.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer2.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer2.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer2.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer2.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3){for(i=0;i>>0;end=end===void 0?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function isArrayBufferView(obj){return typeof ArrayBuffer.isView==="function"&&ArrayBuffer.isView(obj)}function numberIsNaN(obj){return obj!==obj}}).call(exports2,__webpack_require__(1))},function(module2,exports2){"use strict";exports2.byteLength=byteLength;exports2.toByteArray=toByteArray;exports2.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len2-2]==="="?2:b64[len2-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i2,j,l,tmp,placeHolders,arr;var len2=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len2*3/4-placeHolders);l=placeHolders>0?len2-4:len2;var L=0;for(i2=0,j=0;i2>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i2=start;i2len22?len22:i2+maxChunkLength))}if(extraBytes===1){tmp=uint8[len2-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len2-2]<<8)+uint8[len2-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},function(module2,exports2){exports2.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports2.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},function(module2,exports2){module2.exports=function(module3){if(!module3.webpackPolyfill){module3.deprecate=function(){};module3.paths=[];module3.children=[];module3.webpackPolyfill=1}return module3}},function(module2,exports2,__webpack_require__){"use strict";var Process=__webpack_require__(7);var process=new Process,processProxy={};function defineKey(key2){if(processProxy[key2]){return}if(typeof process[key2]==="function"){processProxy[key2]=function(){return process[key2].apply(process,arguments)}}else{processProxy[key2]=process[key2]}}for(var key in process){defineKey(key)}processProxy.initializeTTYs=function(){if(process.stdin===null){process.initializeTTYs();processProxy.stdin=process.stdin;processProxy.stdout=process.stdout;processProxy.stderr=process.stderr}};process.nextTick(function(){processProxy.initializeTTYs()});module2.exports=processProxy},function(module2,exports2,__webpack_require__){(function(__dirname){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var events=__webpack_require__(8);var path=null;var Item=function(){function Item2(fun,array){this.fun=fun;this.array=array}Item2.prototype.run=function(){this.fun.apply(null,this.array)};return Item2}();var NextTickQueue=function(){function NextTickQueue2(){this._queue=[];this._draining=false;this._currentQueue=null;this._queueIndex=-1}NextTickQueue2.prototype.push=function(item){var _this=this;if(this._queue.push(item)===1&&!this._draining){setTimeout(function(){return _this._drainQueue()},0)}};NextTickQueue2.prototype._cleanUpNextTick=function(){this._draining=false;if(this._currentQueue&&this._currentQueue.length){this._queue=this._currentQueue.concat(this._queue)}else{this._queueIndex=-1}if(this._queue.length){this._drainQueue()}};NextTickQueue2.prototype._drainQueue=function(){var _this=this;if(this._draining){return}var timeout=setTimeout(function(){return _this._cleanUpNextTick()});this._draining=true;var len=this._queue.length;while(len){this._currentQueue=this._queue;this._queue=[];while(++this._queueIndex0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},function(module2,exports2,__webpack_require__){(function(process){"use strict";var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;function posixSplitPath(filename){var out=splitPathRe.exec(filename);out.shift();return out}var path=function(){function path2(){}path2.normalize=function(p){if(p===""){p="."}var absolute=p.charAt(0)===path2.sep;p=path2._removeDuplicateSeps(p);var components=p.split(path2.sep);var goodComponents=[];for(var idx=0;idx0&&goodComponents[0]!=="..")){goodComponents.pop()}else{goodComponents.push(c)}}if(!absolute&&goodComponents.length<2){switch(goodComponents.length){case 1:if(goodComponents[0]===""){goodComponents.unshift(".")}break;default:goodComponents.push(".")}}p=goodComponents.join(path2.sep);if(absolute&&p.charAt(0)!==path2.sep){p=path2.sep+p}return p};path2.join=function(){var paths=[];for(var _i=0;_i1&&resolved.charAt(resolved.length-1)===path2.sep){return resolved.substr(0,resolved.length-1)}if(resolved.charAt(0)!==path2.sep){if(resolved.charAt(0)==="."&&(resolved.length===1||resolved.charAt(1)===path2.sep)){resolved=resolved.length===1?"":resolved.substr(2)}var cwd=process.cwd();if(resolved!==""){resolved=this.normalize(cwd+(cwd!=="/"?path2.sep:"")+resolved)}else{resolved=cwd}}return resolved};path2.relative=function(from,to){var i;from=path2.resolve(from);to=path2.resolve(to);var fromSegs=from.split(path2.sep);var toSegs=to.split(path2.sep);toSegs.shift();fromSegs.shift();var upCount=0;var downSegs=[];for(i=0;ifromSegs.length){upCount=fromSegs.length}var rv="";for(i=0;i1&&rv.charAt(rv.length-1)===path2.sep){rv=rv.substr(0,rv.length-1)}return rv};path2.dirname=function(p){p=path2._removeDuplicateSeps(p);var absolute=p.charAt(0)===path2.sep;var sections=p.split(path2.sep);if(sections.pop()===""&§ions.length>0){sections.pop()}if(sections.length>1||sections.length===1&&!absolute){return sections.join(path2.sep)}else if(absolute){return path2.sep}else{return"."}};path2.basename=function(p,ext){if(ext===void 0){ext=""}if(p===""){return p}p=path2.normalize(p);var sections=p.split(path2.sep);var lastPart=sections[sections.length-1];if(lastPart===""&§ions.length>1){return sections[sections.length-2]}if(ext.length>0){var lastPartExt=lastPart.substr(lastPart.length-ext.length);if(lastPartExt===ext){return lastPart.substr(0,lastPart.length-ext.length)}}return lastPart};path2.extname=function(p){p=path2.normalize(p);var sections=p.split(path2.sep);p=sections.pop();if(p===""&§ions.length>0){p=sections.pop()}if(p===".."){return""}var i=p.lastIndexOf(".");if(i===-1||i===0){return""}return p.substr(i)};path2.isAbsolute=function(p){return p.length>0&&p.charAt(0)===path2.sep};path2._makeLong=function(p){return p};path2.parse=function(p){var allParts=posixSplitPath(p);return{root:allParts[0],dir:allParts[0]+allParts[1].slice(0,-1),base:allParts[2],ext:allParts[3],name:allParts[2].slice(0,allParts[2].length-allParts[3].length)}};path2.format=function(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof pathObject)}var root=pathObject.root||"";if(typeof root!=="string"){throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof pathObject.root)}var dir=pathObject.dir?pathObject.dir+path2.sep:"";var base=pathObject.base||"";return dir+base};path2._removeDuplicateSeps=function(p){p=p.replace(this._replaceRegex,this.sep);return p};path2.sep="/";path2._replaceRegex=new RegExp("//+","g");path2.delimiter=":";path2.posix=path2;path2.win32=path2;return path2}();var _=path;module2.exports=path}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(Buffer2){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var stream=__webpack_require__(11);var TTY=function(_super){__extends(TTY2,_super);function TTY2(){_super.call(this);this.isRaw=false;this.columns=80;this.rows=120;this.isTTY=true;this._bufferedWrites=[];this._waitingForWrites=false}TTY2.prototype.setRawMode=function(mode){if(this.isRaw!==mode){this.isRaw=mode;this.emit("modeChange")}};TTY2.prototype.changeColumns=function(columns){if(columns!==this.columns){this.columns=columns;this.emit("resize")}};TTY2.prototype.changeRows=function(rows){if(rows!==this.rows){this.rows=rows;this.emit("resize")}};TTY2.isatty=function(fd){return fd&&fd instanceof TTY2};TTY2.prototype._write=function(chunk,encoding,cb){var error;try{var data;if(typeof chunk==="string"){data=new Buffer2(chunk,encoding)}else{data=chunk}this._bufferedWrites.push(data);if(this._waitingForWrites){this._read(1024)}}catch(e){error=e}finally{cb(error)}};TTY2.prototype._read=function(size){if(this._bufferedWrites.length===0){this._waitingForWrites=true}else{while(this._bufferedWrites.length>0){this._waitingForWrites=this.push(this._bufferedWrites.shift());if(!this._waitingForWrites){break}}}};return TTY2}(stream.Duplex);module2.exports=TTY}).call(exports2,__webpack_require__(1))},function(module2,exports2,__webpack_require__){module2.exports=Stream;var EE=__webpack_require__(8).EventEmitter;var inherits=__webpack_require__(12);inherits(Stream,EE);Stream.Readable=__webpack_require__(13);Stream.Writable=__webpack_require__(27);Stream.Duplex=__webpack_require__(28);Stream.Transform=__webpack_require__(29);Stream.PassThrough=__webpack_require__(30);Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},function(module2,exports2){if(typeof Object.create==="function"){module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},function(module2,exports2,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(11)}catch(_){}}();exports2=module2.exports=__webpack_require__(14);exports2.Stream=Stream||exports2;exports2.Readable=exports2;exports2.Writable=__webpack_require__(22);exports2.Duplex=__webpack_require__(21);exports2.Transform=__webpack_require__(25);exports2.PassThrough=__webpack_require__(26);if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module2.exports=Stream}}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(process){"use strict";module2.exports=Readable;var processNextTick=__webpack_require__(15);var isArray=__webpack_require__(16);var Duplex;Readable.ReadableState=ReadableState;var EE=__webpack_require__(8).EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var debugUtil=__webpack_require__(19);var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=__webpack_require__(20);var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=__webpack_require__(24).StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||__webpack_require__(21);if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer2.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;iMAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===void 0){enc=void 0;_fill=0}var buf=new Buffer2(size);if(typeof _fill==="string"){var fillBuf=new Buffer2(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer2(size)};exports2.from=function from(value,encodingOrOffset,length){if(typeof Buffer2.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer2.from)){return Buffer2.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer2(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer2(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer2(value.slice(offset,offset+len))}if(Buffer2.isBuffer(value)){var out=new Buffer2(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer2(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer2(value.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")};exports2.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer2.allocUnsafeSlow==="function"){return Buffer2.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(exports2,function(){return this}())},function(module2,exports2,__webpack_require__){(function(Buffer2){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports2.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports2.isBoolean=isBoolean;function isNull(arg){return arg===null}exports2.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports2.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports2.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports2.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports2.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports2.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports2.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports2.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports2.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports2.isError=isError;function isFunction(arg){return typeof arg==="function"}exports2.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports2.isPrimitive=isPrimitive;exports2.isBuffer=Buffer2.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(exports2,__webpack_require__(1))},function(module2,exports2){},function(module2,exports2,__webpack_require__){"use strict";var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);module2.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},function(module2,exports2,__webpack_require__){"use strict";var objectKeys=Object.keys||function(obj){var keys2=[];for(var key in obj){keys2.push(key)}return keys2};module2.exports=Duplex;var processNextTick=__webpack_require__(15);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var Readable=__webpack_require__(14);var Writable=__webpack_require__(22);util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var internalUtil={deprecate:__webpack_require__(23)};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||__webpack_require__(21);if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer2.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer2.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},function(module2,exports2,__webpack_require__){"use strict";module2.exports=Transform;var Duplex=__webpack_require__(21);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==void 0)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==c.Z_OK){throw new Error(msg[status])}this.header=new GZheader;zlib_inflate.inflateGetHeader(this.strm,this.header)}Inflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_mode;var next_out_utf8,tail,utf8str;var dict;var allowBufError=false;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?c.Z_FINISH:c.Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.binstring2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_inflate.inflate(strm,c.Z_NO_FLUSH);if(status===c.Z_NEED_DICT&&dictionary){if(typeof dictionary==="string"){dict=strings.string2buf(dictionary)}else if(toString.call(dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(dictionary)}else{dict=dictionary}status=zlib_inflate.inflateSetDictionary(this.strm,dict)}if(status===c.Z_BUF_ERROR&&allowBufError===true){status=c.Z_OK;allowBufError=false}if(status!==c.Z_STREAM_END&&status!==c.Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.next_out){if(strm.avail_out===0||status===c.Z_STREAM_END||strm.avail_in===0&&(_mode===c.Z_FINISH||_mode===c.Z_SYNC_FLUSH)){if(this.options.to==="string"){next_out_utf8=strings.utf8border(strm.output,strm.next_out);tail=strm.next_out-next_out_utf8;utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail){utils.arraySet(strm.output,strm.output,next_out_utf8,tail,0)}this.onData(utf8str)}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}if(strm.avail_in===0&&strm.avail_out===0){allowBufError=true}}while((strm.avail_in>0||strm.avail_out===0)&&status!==c.Z_STREAM_END);if(status===c.Z_STREAM_END){_mode=c.Z_FINISH}if(_mode===c.Z_FINISH){status=zlib_inflate.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===c.Z_OK}if(_mode===c.Z_SYNC_FLUSH){this.onEnd(c.Z_OK);strm.avail_out=0;return true}return true};Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate.prototype.onEnd=function(status){if(status===c.Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate(input,options){var inflator=new Inflate(options);inflator.push(input,true);if(inflator.err){throw inflator.msg||msg[inflator.err]}return inflator.result}function inflateRaw(input,options){options=options||{};options.raw=true;return inflate(input,options)}exports2.Inflate=Inflate;exports2.inflate=inflate;exports2.inflateRaw=inflateRaw;exports2.ungzip=inflate},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var adler32=__webpack_require__(34);var crc32=__webpack_require__(35);var inflate_fast=__webpack_require__(36);var inflate_table=__webpack_require__(37);var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&©>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module2.exports=adler32},function(module2,exports2){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255]}return crc^-1}module2.exports=crc32},function(module2,exports2){"use strict";var BAD=30;var TYPE=12;module2.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits>>=op;bits-=op}if(bits<15){hold+=input[_in++]<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bitsdmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3;_in-=len;bits-=len<<3;hold&=(1<=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}for(;;){here_bits=len-drop;if(work[sym]end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var STR_APPLY_OK=true;var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,[0])}catch(__){STR_APPLY_OK=false}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new utils.Buf8(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1}_utf8len[254]=_utf8len[254]=1;exports2.string2buf=function(str){var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos>>6;buf[i++]=128|c&63}else if(c<65536){buf[i++]=224|c>>>12;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}else{buf[i++]=240|c>>>18;buf[i++]=128|c>>>12&63;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}}return buf};function buf2binstring(buf,len){if(len<65537){if(buf.subarray&&STR_APPLY_UIA_OK||!buf.subarray&&STR_APPLY_OK){return String.fromCharCode.apply(null,utils.shrinkBuf(buf,len))}}var result="";for(var i=0;i4){utf16buf[out++]=65533;i+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};exports2.utf8border=function(buf,max){var pos;max=max||buf.length;if(max>buf.length){max=buf.length}pos=max-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max}if(pos===0){return max}return pos+_utf8len[buf[pos]]>max?pos:max}},function(module2,exports2){"use strict";module2.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(module2,exports2){"use strict";module2.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(module2,exports2){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module2.exports=ZStream},function(module2,exports2){"use strict";function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}module2.exports=GZheader}])})}});var CSV=class{constructor(onOpen=this.onOpen,saveButtonId=null,openButtonId=null){this.onOpen=onOpen;this.notes=[];if(saveButtonId!==null){document.getElementById(saveButtonId).addEventListener("click",this.saveCSV)}if(openButtonId!==null){document.getElementById(openButtonId).addEventListener("click",this.openCSV)}}processArraysForCSV(data=["1|2|3","3|2|1"],delimiter="|",header="a,b,c",saveNotes=false){let csvDat=header+"\n";let noteIdx=0;data.forEach((line,i)=>{if(data[i]==="string"&&delimiter!==","){csvDat+=line.split(delimiter).join(",")}else{csvData+=line.join(",")}if(saveNotes===true){if(this.notes[noteIdx].idx===i){line+=this.notes[noteIdx].text;noteIdx++}}if(line.indexOf("\n")<0){csvDat+="\n"}});return csvDat}static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){var hiddenElement=document.createElement("a");hiddenElement.href="data:text/csv;charset=utf-8,"+encodeURI(csvDat);hiddenElement.target="_blank";if(name!==""){hiddenElement.download=name}else{hiddenElement.download=new Date().toISOString()+".csv"}hiddenElement.click()}static openCSV(delimiter=",",onOpen=(csvDat,header,path)=>{return csvDat,header,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;var tempcsvArr=tempcsvData.split("\n");let header=[];var csvDat=[];tempcsvArr.pop();tempcsvArr.forEach((row,i)=>{if(i==0){header=row.split(delimiter)}else{var temp=row.split(delimiter);csvDat.push(temp)}});onOpen(csvDat,header,input.value);input.value="";res({data:csvDat,header,filename:input.value})};reader.readAsText(file)};input.click()})}static openCSVRaw(onOpen=(csvDat,path)=>{return csvDat,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;onOpen(tempcsvData,input.value);input.value="";res({data:tempcsvData,filename:input.value})};reader.readAsText(file)};input.click()})}onOpen(csvDat=[],header=[]){console.log("CSV Opened!",header,csvDat)}};var parseCSVData=(data,filename,head,hasend=true,parser=(lines,filename2,head2)=>{let result={filename:filename2};let header=head2;if(typeof head2==="string")header=head2.split(",");result.header=header;for(let i=0;i{let lines;if(data.includes("\r"))lines=data.split("\r\n");else lines=data.split("\n");if(!head)head=lines[0];lines.shift();if(hasend===false)lines.pop();let result=parser(lines,filename,head);return result};function toISOLocal(d){d=new Date(d);var z=n=>("0"+n).slice(-2);var zz=n=>("00"+n).slice(-3);var off=d.getTimezoneOffset();var sign=off<0?"+":"-";off=Math.abs(off);return d.getFullYear()+"-"+z(d.getMonth()+1)+"-"+z(d.getDate())+"T"+z(d.getHours())+":"+z(d.getMinutes())+":"+z(d.getSeconds())+"."+zz(d.getMilliseconds())+"(UTC"+sign+z(off/60|0)+":00)"}var processDataForCSV=(options={})=>{if(!options.data)return void 0;if(!Array.isArray(options.data))options.data=[options.data];if(options.data&&!options.header)options.header=Object.keys(options.data[0]);let head=[...options.header];if(head.indexOf("timestamp")>-1){head.splice(head.indexOf("timestamp")+1,0,"localized")}let header=head.join(",");let headeridx=0;let lines=[];let foreach=(obj,i)=>{if(Array.isArray(obj)){for(let j=0;j{if(exists2)appendFile(options.filename,joined,options.dir);else appendFile(options.filename,header+joined,options.dir)})}return result};var BrowserFS=__toESM(require_browserfs());var fsInited=false;var fs2=BrowserFS.BFSRequire("fs");var BFSBuffer=BrowserFS.BFSRequire("buffer").Buffer;var initPromise;var initFS=async(dirs=["data"],oninit=(exists2=[])=>{},onerror=e=>{},filesystem="IndexedDB")=>{if(fsInited){if(initPromise){await initPromise}return true}else{fsInited=true;initPromise=new Promise((resolve,reject)=>{BrowserFS.FileSystem[filesystem].Create({},(e,mountableFileSystem)=>{if(e){reject(e);return}if(!mountableFileSystem){onerror(e);reject(new Error(`Error creating BrowserFS`));return}BrowserFS.initialize(mountableFileSystem);let promises=[];dirs.forEach(async dir=>{promises.push(dirExists(fs2,dir))});Promise.all(promises).then(values=>{oninit(values);resolve(true)})})});return await initPromise}};var exists=async(path="")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.exists("/"+path,function(exists2){resolve(exists2)})})};var readFile=async(path="data")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.readFile("/"+path,function(e,output){resolve(output)})})};async function readFileChunk(path="data",begin=0,end=5120,onread=data=>{}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);if(path!=""){return await new Promise(async(resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})}else{console.error("Path name is not defined");return void 0}}var getFilenames=async(directory="data",onload=directory2=>{})=>{if(!fsInited)await initFS([directory]);else await dirExists(fs2,directory);return await new Promise((resolve,reject)=>{fs2.readdir("/"+directory,(e,dir)=>{if(e){reject(e);return}if(dir){onload(dir);resolve(dir)}else resolve(void 0)})})};var writeFile=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.writeFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var appendFile2=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.appendFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var deleteFile=async(path="data",ondelete=()=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{if(path!=""){fs2.unlink("/"+path,e=>{if(e)console.error(e);ondelete();resolve(true)})}else{console.error("Path name is not defined");resolve(false)}})};var readFileAsText=async(path="data",end="end",begin=0,onread=(data,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(async(resolve,reject)=>{let size=await getFileSize(path);if(end==="end"){end=size}else if(typeof end==="number"){if(end>size)end=size}fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})};var listFiles=async(dir="data",onload=directory=>{})=>{if(!fsInited)await initFS([dir]);else await dirExists(fs2,dir);return await new Promise((resolve,reject)=>{fs2.readdir("/"+dir,(e,directory)=>{if(e){reject(e);return}if(directory){onload(directory)}resolve(directory)})})};var getFileSize=async(path="data",onread=size=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;onread(filesize);resolve(filesize)})})};var getCSVHeader=async(path="data",onopen=(header,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,65535,0,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();let lines=data.split("\n");let header=lines[0];fs2.close(fd,()=>{onopen(header,path);resolve(header)})}else resolve(void 0)})})})};var writeToCSVFromDB=async(path="data",fileSizeLimitMb=10)=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{if(path!=""){fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;fs2.open(path,"r",(e2,fd)=>{if(e2){reject(e2);return}let i=0;let maxFileSize=fileSizeLimitMb*1024*1024;let end=maxFileSize;if(filesize{if(e3){reject(e3);return}if(bytesRead!==0)CSV.saveCSV(output.toString(),path.split("/")[1]);fs2.close(fd);resolve(true)})}else{const writeChunkToFile=async()=>{if(ifilesize){end=filesize-i}let chunk=0;fs2.read(fd,end,i,"utf-8",(e3,output,bytesRead)=>{if(e3){reject(e3);return}if(bytesRead!==0){CSV.saveCSV(output.toString(),path.split("/")[1]+"_"+chunk);i+=maxFileSize;chunk++;writeChunkToFile();fs2.close(fd);resolve(true)}})}}}})})}else{console.error("File name is not defined.");resolve(false)}})};async function processCSVChunksFromDB(path="data",onData=(csvdata,start2,end2,size)=>{},maxChunkSize=1e4,start=0,end="end",options={}){let size=await getFileSize(path);let partition=start;return await new Promise((res,rej)=>{let processPartition=()=>{let endChunk=partition+maxChunkSize;if(endChunk>size){endChunk=size}readCSVChunkFromDB(path,partition,endChunk,options).then(async result=>{await onData(result,partition,endChunk,size);partition=endChunk;if(partition!==size){processPartition()}else{res(true)}}).catch(rej)};processPartition()})}async function readCSVChunkFromDB(path="data",start=0,end="end",options={}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);const transpose=options.transpose||false;let head=await getCSVHeader(path);if(head)head=head.split(",");else return void 0;let resultLengths=[];let resultNames=[];let results=transpose?[]:{};head.forEach(v=>{if(v){resultNames.push(v);resultLengths.push(1)}else resultLengths[resultLengths.length-1]++});let size=await getFileSize(path);if(end==="end")end=size;else if(end>size){start=size-(end-start);end=size}let data=(await readFileChunk(path,start,end))?.split("\n").slice(1,-1);let preprocess=value=>{try{value=JSON.parse(value)}catch{}return value};if(data)data.forEach((r,i)=>{let row=r.split(",");if(transpose){const entry={};if(options.json)row.forEach((v,idx)=>{if(options.json)entry[resultNames[idx]]=preprocess(v);else entry[resultNames[idx]]=v});results.push(entry)}else{row.forEach((v,i2)=>{const header=resultNames[i2];if(!results[header])results[header]=[];if(options.json)results[header].push(preprocess(v));else results[header].push(v)})}});return results}var directories={};var dirExists=async(fs3,directory)=>{if(!fsInited)await initFS([directory]);return await new Promise((resolve,reject)=>{if(!directory)reject(false);if(directories[directory]==="exists"||directories[directory]==="created"){resolve()}else{if(directory[0]==="/")directory=directory.substring(1);if(!directory)reject(false);fs3.exists(`/${directory}`,exists2=>{if(exists2){directories[directory]="exists";resolve()}else if(directories[directory]==="creating"){resolve()}else{directories[directory]="creating";fs3.mkdir(`/${directory}`,1,err=>{if(err){reject(err);return}directories[directory]="created";setTimeout(resolve,500)})}})}})};var BFSRoutes={initFS,dirExists,exists,readFile,readFileChunk,getFilenames,writeFile,appendFile:appendFile2,deleteFile,readFileAsText,getFileSize,getCSVHeader,listFiles};var CSV_REFERENCE={};function lerp(v0,v1,t){return(1-t)*v0+t*v1}function interpolerp(v0,v1,fit,floor=true){if(fit<=2)return[v0,v1];let a=1/fit;let result=new Array(fit);result[0]=v0;for(let i=1;i<=fit;i++){result[i]=lerp(v0,v1,a*i);if(floor)result[i]=Math.floor(result[i])}return result}var appendCSV=async(newData,filename,header,options)=>{if(!filename){let keys=Object.keys(CSV_REFERENCE);if(keys.length>0)filename=keys[keys.length-1];else filename=`csv${new Date().toISOString()}`}let csv=CSV_REFERENCE[filename];if(!csv){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);CSV_REFERENCE[filename]={header:header?header:["timestamp","localized",...keys],lastX:void 0,buffer:"",buffered:0,bufferSize:options?.bufferSize?options.bufferSize:0,toFixed:options?.toFixed?options.toFixed:0,xIncrement:options?.xIncrement?options.xIncrement:0};csv=CSV_REFERENCE[filename];const existingHeader=await getCSVHeader(filename).catch(()=>null);const isDifferent=!existingHeader||existingHeader!==csv.header.join(",");if(isDifferent)header=csv.header}if(!csv.header||csv.header?.length===0){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);csv.header=header?header:["timestamp","localized",...keys]}else if(header)csv.header=header;let maxLen=1;for(const key in newData){const value=newData[key];if(csv.header.indexOf(key)>-1&&value&&Array.isArray(value)&&value?.length>maxLen)maxLen=value?.length}let x;if(csv.xIncrement){if(!csv.lastX){if(typeof newData[csv.header[0]]!=="undefined"){x=newData[csv.header[0]]}else if(csv.header[0].toLowerCase().includes("time")||csv.header[0].toLowerCase().includes("unix"))x=Date.now()}else{if(newData[csv.header[2]]){if(Array.isArray(newData[csv.header[2]]))x=csv.lastX+csv.xIncrement*newData[csv.header[2]].length;else x=csv.lastX+csv.xIncrement}else if(newData[csv.header[0]]){if(Array.isArray(newData[csv.header[0]]))x=csv.lastX+csv.xIncrement*newData[csv.header[0]].length;else x=csv.lastX+csv.xIncrement}else x=csv.lastX+csv.xIncrement}}else if(newData[csv.header[0]])x=newData[csv.header[0]];else x=Date.now();if(typeof csv.lastX==="undefined")csv.lastX=Array.isArray(x)?x[0]:x;if(typeof x==="undefined"){if(csv.header[0].includes("time")){let now=Date.now();if(maxLen===1)x=Date.now();else{x=interpolerp(csv.lastX,now,maxLen);x.shift()}}else{let newX=csv.lastX+1;if(maxLen>1){x=new Array(maxLen).fill("");x[maxLen-1]=newX}else x=newX}}else if(maxLen>1&&x?.length!==maxLen){if(!Array.isArray(x)||x.length===1){x=interpolerp(csv.lastX,x,maxLen,true);x.shift()}else{x=interpolerp(x[0],x[x.length-1],maxLen,true);x.shift()}}let toAppend=[];if(Array.isArray(x)){let curIdcs={};for(let i=0;icurIdcs[csv.header[j]]){curIdcs[csv.header[j]]++;toAppend[i][j]=d[curIdcs[csv.header[j]]]}else{toAppend[i][j]=""}}}}else{if(i===x.length-1){toAppend[i][j]=d}else{toAppend[i][j]=""}}if(typeof toAppend[i][j]==="number"&&Math.floor(toAppend[i][j])!==toAppend[i][j])toAppend[i][j]=toAppend[i][j].toFixed(CSV_REFERENCE[filename].toFixed)}}}else{toAppend.push([]);for(let j=0;j{csvProcessed+=(options?.json?arr.map(v=>JSON.stringify(v)):arr).join(",")+"\n";if(csv.bufferSize)csv.buffered++});csv.lastX=toAppend[toAppend.length-1][0];if(csv.bufferSize){csv.buffer+=csvProcessed;if(csv.buffered>csv.bufferSize){let r=new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csv.buffer,written=>{res(written)})}else{appendFile2(filename,csv.buffer,written=>{res(written)})}})});await r;csv.buffer="";csv.buffered=0;return r}else return await Promise.resolve(true)}else{return await new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csvProcessed,written=>{res(written)})}else{appendFile2(filename,csvProcessed,written=>{res(written)})}})})}};var updateCSVHeader=(header,filename)=>{if(CSV_REFERENCE[filename]){CSV_REFERENCE[filename].header=header}};var createCSV=(filename,header,toFixed=5,bufferSize=0,xIncrement)=>{if(!CSV_REFERENCE[filename]){if(header?.indexOf("timestamp")>1){header.splice(header.indexOf("timestamp"),1);header.unshift("timestamp")}if((header?.[0].toLowerCase().includes("time")||header?.[0].toLowerCase().includes("unix"))&&header[1]!=="localized"){header.splice(1,0,"localized")}CSV_REFERENCE[filename]={header,lastX:header[1]==="localized"?Date.now():0,bufferSize,buffer:"",buffered:0,toFixed,xIncrement};return new Promise((res,rej)=>{exists(filename).then(doesExist=>{if(!doesExist){writeFile(filename,CSV_REFERENCE[filename].header?CSV_REFERENCE[filename].header.join(",")+"\n":"",written=>{res(written)}).catch(rej)}})})}};var visualizeDirectory=(dir,parentNode=document.body)=>{return new Promise(async(res,rej)=>{if(parentNode.querySelector("#bfs"+dir))parentNode.querySelector("#bfs"+dir)?.remove();parentNode.insertAdjacentHTML("beforeend",`
`);let div=parentNode.querySelector("#bfs"+dir);await listFiles(dir).then(directory=>{if(directory.length===0)div.innerHTML="No Files!";else directory.forEach(listing=>{div?.insertAdjacentHTML("beforeend",`
- Data: - ${listing} - - ${listing.indexOf(".")>-1?``:""} -
`);if(document.getElementById(`delete${listing}`)){document.getElementById(`delete${listing}`).onclick=()=>{deleteFile(dir+"/"+listing,()=>{visualizeDirectory(dir,parentNode)})}}if(document.getElementById(`download${listing}`)){document.getElementById(`download${listing}`).onclick=()=>{writeToCSVFromDB(dir+"/"+listing,10)}}});res(directory)}).catch(rej)})};var csvRoutes={appendCSV,updateCSVHeader,createCSV,visualizeDirectory,openCSV:CSV.openCSV,saveCSV:CSV.saveCSV,openCSVRaw:CSV.openCSVRaw,parseCSVData,getCSVHeader,writeToCSVFromDB,readCSVChunkFromDB,processCSVChunksFromDB,toISOLocal};export{BFSRoutes,CSV,appendCSV,appendFile2 as appendFile,createCSV,csvRoutes,deleteFile,dirExists,exists,fs2 as fs,fsInited,getCSVHeader,getFileSize,getFilenames,initFS,listFiles,parseCSVData,processCSVChunksFromDB,processDataForCSV,readCSVChunkFromDB,readFile,readFileAsText,readFileChunk,toISOLocal,updateCSVHeader,visualizeDirectory,writeFile,writeToCSVFromDB}; -/*! Bundled license information: - -browserfs/dist/browserfs.js: - (*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *) -*/ diff --git a/src/extras/dist/index.storage.services.js b/src/extras/dist/index.storage.services.js deleted file mode 100644 index 40ef601c..00000000 --- a/src/extras/dist/index.storage.services.js +++ /dev/null @@ -1,16 +0,0 @@ -(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browserfs=__commonJS({"node_modules/browserfs/dist/browserfs.js"(exports,module){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["BrowserFS"]=factory();else root["BrowserFS"]=factory()})(exports,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module2=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module2.exports,module2,module2.exports,__webpack_require__);module2.loaded=true;return module2.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module2,exports2,__webpack_require__){(function(Buffer2,global,module3,process){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var buffer=__webpack_require__(2);var path=__webpack_require__(9);var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2["EPERM"]=1]="EPERM";ErrorCode2[ErrorCode2["ENOENT"]=2]="ENOENT";ErrorCode2[ErrorCode2["EIO"]=5]="EIO";ErrorCode2[ErrorCode2["EBADF"]=9]="EBADF";ErrorCode2[ErrorCode2["EACCES"]=13]="EACCES";ErrorCode2[ErrorCode2["EBUSY"]=16]="EBUSY";ErrorCode2[ErrorCode2["EEXIST"]=17]="EEXIST";ErrorCode2[ErrorCode2["ENOTDIR"]=20]="ENOTDIR";ErrorCode2[ErrorCode2["EISDIR"]=21]="EISDIR";ErrorCode2[ErrorCode2["EINVAL"]=22]="EINVAL";ErrorCode2[ErrorCode2["EFBIG"]=27]="EFBIG";ErrorCode2[ErrorCode2["ENOSPC"]=28]="ENOSPC";ErrorCode2[ErrorCode2["EROFS"]=30]="EROFS";ErrorCode2[ErrorCode2["ENOTEMPTY"]=39]="ENOTEMPTY";ErrorCode2[ErrorCode2["ENOTSUP"]=95]="ENOTSUP"})(ErrorCode||(ErrorCode={}));var ErrorStrings={};ErrorStrings[ErrorCode.EPERM]="Operation not permitted.";ErrorStrings[ErrorCode.ENOENT]="No such file or directory.";ErrorStrings[ErrorCode.EIO]="Input/output error.";ErrorStrings[ErrorCode.EBADF]="Bad file descriptor.";ErrorStrings[ErrorCode.EACCES]="Permission denied.";ErrorStrings[ErrorCode.EBUSY]="Resource busy or locked.";ErrorStrings[ErrorCode.EEXIST]="File exists.";ErrorStrings[ErrorCode.ENOTDIR]="File is not a directory.";ErrorStrings[ErrorCode.EISDIR]="File is a directory.";ErrorStrings[ErrorCode.EINVAL]="Invalid argument.";ErrorStrings[ErrorCode.EFBIG]="File is too big.";ErrorStrings[ErrorCode.ENOSPC]="No space left on disk.";ErrorStrings[ErrorCode.EROFS]="Cannot modify a read-only file system.";ErrorStrings[ErrorCode.ENOTEMPTY]="Directory is not empty.";ErrorStrings[ErrorCode.ENOTSUP]="Operation is not supported.";var ApiError=function(Error2){function ApiError2(type,message,path$$1){if(message===void 0)message=ErrorStrings[type];Error2.call(this,message);this.syscall="";this.errno=type;this.code=ErrorCode[type];this.path=path$$1;this.stack=new Error2().stack;this.message="Error: "+this.code+": "+message+(this.path?", '"+this.path+"'":"")}if(Error2)ApiError2.__proto__=Error2;ApiError2.prototype=Object.create(Error2&&Error2.prototype);ApiError2.prototype.constructor=ApiError2;ApiError2.fromJSON=function fromJSON(json){var err=new ApiError2(0);err.errno=json.errno;err.code=json.code;err.path=json.path;err.stack=json.stack;err.message=json.message;return err};ApiError2.fromBuffer=function fromBuffer(buffer$$1,i2){if(i2===void 0)i2=0;return ApiError2.fromJSON(JSON.parse(buffer$$1.toString("utf8",i2+4,i2+4+buffer$$1.readUInt32LE(i2))))};ApiError2.FileError=function FileError(code,p){return new ApiError2(code,ErrorStrings[code],p)};ApiError2.ENOENT=function ENOENT(path$$1){return this.FileError(ErrorCode.ENOENT,path$$1)};ApiError2.EEXIST=function EEXIST(path$$1){return this.FileError(ErrorCode.EEXIST,path$$1)};ApiError2.EISDIR=function EISDIR(path$$1){return this.FileError(ErrorCode.EISDIR,path$$1)};ApiError2.ENOTDIR=function ENOTDIR(path$$1){return this.FileError(ErrorCode.ENOTDIR,path$$1)};ApiError2.EPERM=function EPERM(path$$1){return this.FileError(ErrorCode.EPERM,path$$1)};ApiError2.ENOTEMPTY=function ENOTEMPTY(path$$1){return this.FileError(ErrorCode.ENOTEMPTY,path$$1)};ApiError2.prototype.toString=function toString(){return this.message};ApiError2.prototype.toJSON=function toJSON(){return{errno:this.errno,code:this.code,path:this.path,stack:this.stack,message:this.message}};ApiError2.prototype.writeToBuffer=function writeToBuffer(buffer$$1,i2){if(buffer$$1===void 0)buffer$$1=Buffer2.alloc(this.bufferSize());if(i2===void 0)i2=0;var bytesWritten=buffer$$1.write(JSON.stringify(this.toJSON()),i2+4);buffer$$1.writeUInt32LE(bytesWritten,i2);return buffer$$1};ApiError2.prototype.bufferSize=function bufferSize(){return 4+Buffer2.byteLength(JSON.stringify(this.toJSON()))};return ApiError2}(Error);var api_error=Object.freeze({get ErrorCode(){return ErrorCode},ErrorStrings,ApiError});var ActionType;(function(ActionType2){ActionType2[ActionType2["NOP"]=0]="NOP";ActionType2[ActionType2["THROW_EXCEPTION"]=1]="THROW_EXCEPTION";ActionType2[ActionType2["TRUNCATE_FILE"]=2]="TRUNCATE_FILE";ActionType2[ActionType2["CREATE_FILE"]=3]="CREATE_FILE"})(ActionType||(ActionType={}));var FileFlag=function FileFlag2(flagStr){this.flagStr=flagStr;if(FileFlag2.validFlagStrs.indexOf(flagStr)<0){throw new ApiError(ErrorCode.EINVAL,"Invalid flag: "+flagStr)}};FileFlag.getFileFlag=function getFileFlag(flagStr){if(FileFlag.flagCache.hasOwnProperty(flagStr)){return FileFlag.flagCache[flagStr]}return FileFlag.flagCache[flagStr]=new FileFlag(flagStr)};FileFlag.prototype.getFlagString=function getFlagString(){return this.flagStr};FileFlag.prototype.isReadable=function isReadable(){return this.flagStr.indexOf("r")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isWriteable=function isWriteable(){return this.flagStr.indexOf("w")!==-1||this.flagStr.indexOf("a")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isTruncating=function isTruncating(){return this.flagStr.indexOf("w")!==-1};FileFlag.prototype.isAppendable=function isAppendable(){return this.flagStr.indexOf("a")!==-1};FileFlag.prototype.isSynchronous=function isSynchronous(){return this.flagStr.indexOf("s")!==-1};FileFlag.prototype.isExclusive=function isExclusive(){return this.flagStr.indexOf("x")!==-1};FileFlag.prototype.pathExistsAction=function pathExistsAction(){if(this.isExclusive()){return ActionType.THROW_EXCEPTION}else if(this.isTruncating()){return ActionType.TRUNCATE_FILE}else{return ActionType.NOP}};FileFlag.prototype.pathNotExistsAction=function pathNotExistsAction(){if((this.isWriteable()||this.isAppendable())&&this.flagStr!=="r+"){return ActionType.CREATE_FILE}else{return ActionType.THROW_EXCEPTION}};FileFlag.flagCache={};FileFlag.validFlagStrs=["r","r+","rs","rs+","w","wx","w+","wx+","a","ax","a+","ax+"];var FileType;(function(FileType2){FileType2[FileType2["FILE"]=32768]="FILE";FileType2[FileType2["DIRECTORY"]=16384]="DIRECTORY";FileType2[FileType2["SYMLINK"]=40960]="SYMLINK"})(FileType||(FileType={}));var Stats=function Stats2(itemType,size,mode,atime,mtime,ctime){if(atime===void 0)atime=new Date;if(mtime===void 0)mtime=new Date;if(ctime===void 0)ctime=new Date;this.size=size;this.atime=atime;this.mtime=mtime;this.ctime=ctime;this.dev=0;this.ino=0;this.rdev=0;this.nlink=1;this.blksize=4096;this.uid=0;this.gid=0;this.birthtime=new Date(0);this.fileData=null;if(!mode){switch(itemType){case FileType.FILE:this.mode=420;break;case FileType.DIRECTORY:default:this.mode=511}}else{this.mode=mode}this.blocks=Math.ceil(size/512);if(this.mode<4096){this.mode|=itemType}};Stats.fromBuffer=function fromBuffer(buffer$$1){var size=buffer$$1.readUInt32LE(0),mode=buffer$$1.readUInt32LE(4),atime=buffer$$1.readDoubleLE(8),mtime=buffer$$1.readDoubleLE(16),ctime=buffer$$1.readDoubleLE(24);return new Stats(mode&61440,size,mode&4095,new Date(atime),new Date(mtime),new Date(ctime))};Stats.prototype.toBuffer=function toBuffer(){var buffer$$1=Buffer2.alloc(32);buffer$$1.writeUInt32LE(this.size,0);buffer$$1.writeUInt32LE(this.mode,4);buffer$$1.writeDoubleLE(this.atime.getTime(),8);buffer$$1.writeDoubleLE(this.mtime.getTime(),16);buffer$$1.writeDoubleLE(this.ctime.getTime(),24);return buffer$$1};Stats.prototype.clone=function clone(){return new Stats(this.mode&61440,this.size,this.mode&4095,this.atime,this.mtime,this.ctime)};Stats.prototype.isFile=function isFile(){return(this.mode&61440)===FileType.FILE};Stats.prototype.isDirectory=function isDirectory(){return(this.mode&61440)===FileType.DIRECTORY};Stats.prototype.isSymbolicLink=function isSymbolicLink(){return(this.mode&61440)===FileType.SYMLINK};Stats.prototype.chmod=function chmod(mode){this.mode=this.mode&61440|mode};Stats.prototype.isSocket=function isSocket(){return false};Stats.prototype.isBlockDevice=function isBlockDevice(){return false};Stats.prototype.isCharacterDevice=function isCharacterDevice(){return false};Stats.prototype.isFIFO=function isFIFO(){return false};var wrapCb=function(cb,numArgs){return cb};function assertRoot(fs4){if(fs4){return fs4}throw new ApiError(ErrorCode.EIO,"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)")}function normalizeMode(mode,def){switch(typeof mode){case"number":return mode;case"string":var trueMode=parseInt(mode,8);if(!isNaN(trueMode)){return trueMode}return def;default:return def}}function normalizeTime(time){if(time instanceof Date){return time}else if(typeof time==="number"){return new Date(time*1e3)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid time.")}}function normalizePath(p){if(p.indexOf("\0")>=0){throw new ApiError(ErrorCode.EINVAL,"Path must be a string without null bytes.")}else if(p===""){throw new ApiError(ErrorCode.EINVAL,"Path must not be empty.")}return path.resolve(p)}function normalizeOptions(options,defEnc,defFlag,defMode){switch(typeof options){case"object":return{encoding:typeof options["encoding"]!=="undefined"?options["encoding"]:defEnc,flag:typeof options["flag"]!=="undefined"?options["flag"]:defFlag,mode:normalizeMode(options["mode"],defMode)};case"string":return{encoding:options,flag:defFlag,mode:defMode};default:return{encoding:defEnc,flag:defFlag,mode:defMode}}}function nopCb(){}var FS=function FS2(){this.F_OK=0;this.R_OK=4;this.W_OK=2;this.X_OK=1;this.root=null;this.fdMap={};this.nextFd=100};FS.prototype.initialize=function initialize3(rootFS){if(!rootFS.constructor.isAvailable()){throw new ApiError(ErrorCode.EINVAL,"Tried to instantiate BrowserFS with an unavailable file system.")}return this.root=rootFS};FS.prototype._toUnixTimestamp=function _toUnixTimestamp(time){if(typeof time==="number"){return time}else if(time instanceof Date){return time.getTime()/1e3}throw new Error("Cannot parse time: "+time)};FS.prototype.getRootFS=function getRootFS(){if(this.root){return this.root}else{return null}};FS.prototype.rename=function rename(oldPath,newPath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).rename(normalizePath(oldPath),normalizePath(newPath),newCb)}catch(e){newCb(e)}};FS.prototype.renameSync=function renameSync(oldPath,newPath){assertRoot(this.root).renameSync(normalizePath(oldPath),normalizePath(newPath))};FS.prototype.exists=function exists2(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).exists(normalizePath(path$$1),newCb)}catch(e){return newCb(false)}};FS.prototype.existsSync=function existsSync(path$$1){try{return assertRoot(this.root).existsSync(normalizePath(path$$1))}catch(e){return false}};FS.prototype.stat=function stat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),false,newCb)}catch(e){return newCb(e)}};FS.prototype.statSync=function statSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),false)};FS.prototype.lstat=function lstat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),true,newCb)}catch(e){return newCb(e)}};FS.prototype.lstatSync=function lstatSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),true)};FS.prototype.truncate=function truncate(path$$1,arg2,cb){if(arg2===void 0)arg2=0;if(cb===void 0)cb=nopCb;var len=0;if(typeof arg2==="function"){cb=arg2}else if(typeof arg2==="number"){len=arg2}var newCb=wrapCb(cb,1);try{if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncate(normalizePath(path$$1),len,newCb)}catch(e){return newCb(e)}};FS.prototype.truncateSync=function truncateSync(path$$1,len){if(len===void 0)len=0;if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncateSync(normalizePath(path$$1),len)};FS.prototype.unlink=function unlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).unlink(normalizePath(path$$1),newCb)}catch(e){return newCb(e)}};FS.prototype.unlinkSync=function unlinkSync(path$$1){return assertRoot(this.root).unlinkSync(normalizePath(path$$1))};FS.prototype.open=function open(path$$1,flag,arg2,cb){var this$1=this;if(cb===void 0)cb=nopCb;var mode=normalizeMode(arg2,420);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{assertRoot(this.root).open(normalizePath(path$$1),FileFlag.getFileFlag(flag),mode,function(e,file){if(file){newCb(e,this$1.getFdForFile(file))}else{newCb(e)}})}catch(e){newCb(e)}};FS.prototype.openSync=function openSync(path$$1,flag,mode){if(mode===void 0)mode=420;return this.getFdForFile(assertRoot(this.root).openSync(normalizePath(path$$1),FileFlag.getFileFlag(flag),normalizeMode(mode,420)))};FS.prototype.readFile=function readFile2(filename,arg2,cb){if(arg2===void 0)arg2={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg2,null,"r",null);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{var flag=FileFlag.getFileFlag(options["flag"]);if(!flag.isReadable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading."))}return assertRoot(this.root).readFile(normalizePath(filename),options.encoding,flag,newCb)}catch(e){return newCb(e)}};FS.prototype.readFileSync=function readFileSync(filename,arg2){if(arg2===void 0)arg2={};var options=normalizeOptions(arg2,null,"r",null);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isReadable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading.")}return assertRoot(this.root).readFileSync(normalizePath(filename),options.encoding,flag)};FS.prototype.writeFile=function writeFile2(filename,data,arg3,cb){if(arg3===void 0)arg3={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","w",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing."))}return assertRoot(this.root).writeFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){return newCb(e)}};FS.prototype.writeFileSync=function writeFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","w",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing.")}return assertRoot(this.root).writeFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.appendFile=function appendFile3(filename,data,arg3,cb){if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","a",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending."))}assertRoot(this.root).appendFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){newCb(e)}};FS.prototype.appendFileSync=function appendFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","a",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending.")}return assertRoot(this.root).appendFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.fstat=function fstat(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{var file=this.fd2file(fd);file.stat(newCb)}catch(e){newCb(e)}};FS.prototype.fstatSync=function fstatSync(fd){return this.fd2file(fd).statSync()};FS.prototype.close=function close(fd,cb){var this$1=this;if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).close(function(e){if(!e){this$1.closeFd(fd)}newCb(e)})}catch(e){newCb(e)}};FS.prototype.closeSync=function closeSync(fd){this.fd2file(fd).closeSync();this.closeFd(fd)};FS.prototype.ftruncate=function ftruncate(fd,arg2,cb){if(cb===void 0)cb=nopCb;var length=typeof arg2==="number"?arg2:0;cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(length<0){throw new ApiError(ErrorCode.EINVAL)}file.truncate(length,newCb)}catch(e){newCb(e)}};FS.prototype.ftruncateSync=function ftruncateSync(fd,len){if(len===void 0)len=0;var file=this.fd2file(fd);if(len<0){throw new ApiError(ErrorCode.EINVAL)}file.truncateSync(len)};FS.prototype.fsync=function fsync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).sync(newCb)}catch(e){newCb(e)}};FS.prototype.fsyncSync=function fsyncSync(fd){this.fd2file(fd).syncSync()};FS.prototype.fdatasync=function fdatasync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).datasync(newCb)}catch(e){newCb(e)}};FS.prototype.fdatasyncSync=function fdatasyncSync(fd){this.fd2file(fd).datasyncSync()};FS.prototype.write=function write(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var buffer$$1,offset,length,position=null;if(typeof arg2==="string"){var encoding="utf8";switch(typeof arg3){case"function":cb=arg3;break;case"number":position=arg3;encoding=typeof arg4==="string"?arg4:"utf8";cb=typeof arg5==="function"?arg5:cb;break;default:cb=typeof arg4==="function"?arg4:typeof arg5==="function"?arg5:cb;return cb(new ApiError(ErrorCode.EINVAL,"Invalid arguments."))}buffer$$1=Buffer2.from(arg2,encoding);offset=0;length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null;cb=typeof arg5==="function"?arg5:cb}var newCb=wrapCb(cb,3);try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.write(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.writeSync=function writeSync(fd,arg2,arg3,arg4,arg5){var buffer$$1,offset=0,length,position;if(typeof arg2==="string"){position=typeof arg3==="number"?arg3:null;var encoding=typeof arg4==="string"?arg4:"utf8";offset=0;buffer$$1=Buffer2.from(arg2,encoding);length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}return file.writeSync(buffer$$1,offset,length,position)};FS.prototype.read=function read(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var position,offset,length,buffer$$1,newCb;if(typeof arg2==="number"){length=arg2;position=arg3;var encoding=arg4;cb=typeof arg5==="function"?arg5:cb;offset=0;buffer$$1=Buffer2.alloc(length);newCb=wrapCb(function(err,bytesRead,buf){if(err){return cb(err)}cb(err,buf.toString(encoding),bytesRead)},3)}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5;newCb=wrapCb(cb,3)}try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.read(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.readSync=function readSync(fd,arg2,arg3,arg4,arg5){var shenanigans=false;var buffer$$1,offset,length,position,encoding="utf8";if(typeof arg2==="number"){length=arg2;position=arg3;encoding=arg4;offset=0;buffer$$1=Buffer2.alloc(length);shenanigans=true}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}var rv=file.readSync(buffer$$1,offset,length,position);if(!shenanigans){return rv}else{return[buffer$$1.toString(encoding),rv]}};FS.prototype.fchown=function fchown(fd,uid,gid,callback){if(callback===void 0)callback=nopCb;var newCb=wrapCb(callback,1);try{this.fd2file(fd).chown(uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.fchownSync=function fchownSync(fd,uid,gid){this.fd2file(fd).chownSync(uid,gid)};FS.prototype.fchmod=function fchmod(fd,mode,cb){var newCb=wrapCb(cb,1);try{var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmod(numMode,newCb)}catch(e){newCb(e)}};FS.prototype.fchmodSync=function fchmodSync(fd,mode){var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmodSync(numMode)};FS.prototype.futimes=function futimes(fd,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(typeof atime==="number"){atime=new Date(atime*1e3)}if(typeof mtime==="number"){mtime=new Date(mtime*1e3)}file.utimes(atime,mtime,newCb)}catch(e){newCb(e)}};FS.prototype.futimesSync=function futimesSync(fd,atime,mtime){this.fd2file(fd).utimesSync(normalizeTime(atime),normalizeTime(mtime))};FS.prototype.rmdir=function rmdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).rmdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.rmdirSync=function rmdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).rmdirSync(path$$1)};FS.prototype.mkdir=function mkdir(path$$1,mode,cb){if(cb===void 0)cb=nopCb;if(typeof mode==="function"){cb=mode;mode=511}var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).mkdir(path$$1,mode,newCb)}catch(e){newCb(e)}};FS.prototype.mkdirSync=function mkdirSync(path$$1,mode){assertRoot(this.root).mkdirSync(normalizePath(path$$1),normalizeMode(mode,511))};FS.prototype.readdir=function readdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readdirSync=function readdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readdirSync(path$$1)};FS.prototype.link=function link(srcpath,dstpath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).link(srcpath,dstpath,newCb)}catch(e){newCb(e)}};FS.prototype.linkSync=function linkSync(srcpath,dstpath){srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).linkSync(srcpath,dstpath)};FS.prototype.symlink=function symlink(srcpath,dstpath,arg3,cb){if(cb===void 0)cb=nopCb;var type=typeof arg3==="string"?arg3:"file";cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{if(type!=="file"&&type!=="dir"){return newCb(new ApiError(ErrorCode.EINVAL,"Invalid type: "+type))}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).symlink(srcpath,dstpath,type,newCb)}catch(e){newCb(e)}};FS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(!type){type="file"}else if(type!=="file"&&type!=="dir"){throw new ApiError(ErrorCode.EINVAL,"Invalid type: "+type)}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).symlinkSync(srcpath,dstpath,type)};FS.prototype.readlink=function readlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readlink(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readlinkSync=function readlinkSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readlinkSync(path$$1)};FS.prototype.chown=function chown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,false,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.chownSync=function chownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,false,uid,gid)};FS.prototype.lchown=function lchown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,true,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.lchownSync=function lchownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,true,uid,gid)};FS.prototype.chmod=function chmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),false,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.chmodSync=function chmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}path$$1=normalizePath(path$$1);assertRoot(this.root).chmodSync(path$$1,false,numMode)};FS.prototype.lchmod=function lchmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),true,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.lchmodSync=function lchmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<1){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmodSync(normalizePath(path$$1),true,numMode)};FS.prototype.utimes=function utimes(path$$1,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).utimes(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime),newCb)}catch(e){newCb(e)}};FS.prototype.utimesSync=function utimesSync(path$$1,atime,mtime){assertRoot(this.root).utimesSync(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime))};FS.prototype.realpath=function realpath(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;var cache=typeof arg2==="object"?arg2:{};cb=typeof arg2==="function"?arg2:nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).realpath(path$$1,cache,newCb)}catch(e){newCb(e)}};FS.prototype.realpathSync=function realpathSync(path$$1,cache){if(cache===void 0)cache={};path$$1=normalizePath(path$$1);return assertRoot(this.root).realpathSync(path$$1,cache)};FS.prototype.watchFile=function watchFile(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.unwatchFile=function unwatchFile(filename,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.watch=function watch(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.access=function access(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.accessSync=function accessSync(path$$1,mode){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createReadStream=function createReadStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createWriteStream=function createWriteStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.wrapCallbacks=function wrapCallbacks(cbWrapper){wrapCb=cbWrapper};FS.prototype.getFdForFile=function getFdForFile(file){var fd=this.nextFd++;this.fdMap[fd]=file;return fd};FS.prototype.fd2file=function fd2file(fd){var rv=this.fdMap[fd];if(rv){return rv}else{throw new ApiError(ErrorCode.EBADF,"Invalid file descriptor.")}};FS.prototype.closeFd=function closeFd(fd){delete this.fdMap[fd]};FS.Stats=Stats;var fs3=new FS;var _fsMock={};var fsProto=FS.prototype;Object.keys(fsProto).forEach(function(key){if(typeof fs3[key]==="function"){_fsMock[key]=function(){return fs3[key].apply(fs3,arguments)}}else{_fsMock[key]=fs3[key]}});_fsMock["changeFSModule"]=function(newFs){fs3=newFs};_fsMock["getFSModule"]=function(){return fs3};_fsMock["FS"]=FS;function _min(d0,d1,d2,bx,ay){return d0d2?d2+1:d0+1:bx===ay?d1:d1+1}function levenshtein(a,b){if(a===b){return 0}if(a.length>b.length){var tmp=a;a=b;b=tmp}var la=a.length;var lb=b.length;while(la>0&&a.charCodeAt(la-1)===b.charCodeAt(lb-1)){la--;lb--}var offset=0;while(offsetdd?dd+1:dy$1+1:bx0$1===vector[la+y$2]?d0:d0+1;d0=dy$1}}return dd}function deprecationMessage(print,fsName,opts){if(print){console.warn("["+fsName+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+fsName+".Create("+JSON.stringify(opts)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}}var isIE=typeof navigator!=="undefined"&&!!(/(msie) ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||navigator.userAgent.indexOf("Trident")!==-1);var isWebWorker=typeof window==="undefined";function fail(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function mkdirpSync(p,mode,fs4){if(!fs4.existsSync(p)){mkdirpSync(path.dirname(p),mode,fs4);fs4.mkdirSync(p,mode)}}function buffer2ArrayBuffer(buff){var u8=buffer2Uint8array(buff),u8offset=u8.byteOffset,u8Len=u8.byteLength;if(u8offset===0&&u8Len===u8.buffer.byteLength){return u8.buffer}else{return u8.buffer.slice(u8offset,u8offset+u8Len)}}function buffer2Uint8array(buff){if(buff instanceof Uint8Array){return buff}else{return new Uint8Array(buff)}}function arrayish2Buffer(arr){if(arr instanceof Buffer2){return arr}else if(arr instanceof Uint8Array){return uint8Array2Buffer(arr)}else{return Buffer2.from(arr)}}function uint8Array2Buffer(u8){if(u8 instanceof Buffer2){return u8}else if(u8.byteOffset===0&&u8.byteLength===u8.buffer.byteLength){return arrayBuffer2Buffer(u8.buffer)}else{return Buffer2.from(u8.buffer,u8.byteOffset,u8.byteLength)}}function arrayBuffer2Buffer(ab){return Buffer2.from(ab)}function copyingSlice(buff,start,end){if(start===void 0)start=0;if(end===void 0)end=buff.length;if(start<0||end<0||end>buff.length||start>end){throw new TypeError("Invalid slice bounds on buffer of length "+buff.length+": ["+start+", "+end+"]")}if(buff.length===0){return emptyBuffer()}else{var u8=buffer2Uint8array(buff),s0=buff[0],newS0=(s0+1)%255;buff[0]=newS0;if(u8[0]===newS0){u8[0]=s0;return uint8Array2Buffer(u8.slice(start,end))}else{buff[0]=s0;return uint8Array2Buffer(u8.subarray(start,end))}}}var emptyBuff=null;function emptyBuffer(){if(emptyBuff){return emptyBuff}return emptyBuff=Buffer2.alloc(0)}function bufferValidator(v,cb){if(Buffer2.isBuffer(v)){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"option must be a Buffer."))}}function checkOptions(fsType,opts,cb){var optsInfo=fsType.Options;var fsName=fsType.Name;var pendingValidators=0;var callbackCalled=false;var loopEnded=false;function validatorCallback(e){if(!callbackCalled){if(e){callbackCalled=true;cb(e)}pendingValidators--;if(pendingValidators===0&&loopEnded){cb()}}}var loop=function(optName2){if(optsInfo.hasOwnProperty(optName2)){var opt=optsInfo[optName2];var providedValue=opts[optName2];if(providedValue===void 0||providedValue===null){if(!opt.optional){var incorrectOptions=Object.keys(opts).filter(function(o){return!(o in optsInfo)}).map(function(a){return{str:a,distance:levenshtein(optName2,a)}}).filter(function(o){return o.distance<5}).sort(function(a,b){return a.distance-b.distance});if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Required option '"+optName2+"' not provided."+(incorrectOptions.length>0?" You provided unrecognized option '"+incorrectOptions[0].str+"'; perhaps you meant to type '"+optName2+"'.":"")+"\nOption description: "+opt.description))}}}else{var typeMatches=false;if(Array.isArray(opt.type)){typeMatches=opt.type.indexOf(typeof providedValue)!==-1}else{typeMatches=typeof providedValue===opt.type}if(!typeMatches){if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Value provided for option "+optName2+" is not the proper type. Expected "+(Array.isArray(opt.type)?"one of {"+opt.type.join(", ")+"}":opt.type)+", but received "+typeof providedValue+"\nOption description: "+opt.description))}}else if(opt.validator){pendingValidators++;opt.validator(providedValue,validatorCallback)}}}};for(var optName in optsInfo){var returned=loop(optName);if(returned)return returned.v}loopEnded=true;if(pendingValidators===0&&!callbackCalled){cb()}}var BFSUtils=Object.freeze({deprecationMessage,isIE,isWebWorker,fail,mkdirpSync,buffer2ArrayBuffer,buffer2Uint8array,arrayish2Buffer,uint8Array2Buffer,arrayBuffer2Buffer,copyingSlice,emptyBuffer,bufferValidator,checkOptions});var BFSEmscriptenStreamOps=function BFSEmscriptenStreamOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenStreamOps.prototype.open=function open(stream){var path$$1=this.fs.realPath(stream.node);var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)){stream.nfd=this.nodefs.openSync(path$$1,this.fs.flagsToPermissionString(stream.flags))}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.close=function close(stream){var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)&&stream.nfd){this.nodefs.closeSync(stream.nfd)}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.read=function read(stream,buffer$$1,offset,length,position){try{return this.nodefs.readSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.write=function write(stream,buffer$$1,offset,length,position){try{return this.nodefs.writeSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.llseek=function llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(this.FS.isFile(stream.node.mode)){try{var stat=this.nodefs.fstatSync(stream.nfd);position+=stat.size}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}}if(position<0){throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL)}stream.position=position;return position};var BFSEmscriptenNodeOps=function BFSEmscriptenNodeOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenNodeOps.prototype.getattr=function getattr(node){var path$$1=this.fs.realPath(node);var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return{dev:stat.dev,ino:stat.ino,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}};BFSEmscriptenNodeOps.prototype.setattr=function setattr(node,attr){var path$$1=this.fs.realPath(node);try{if(attr.mode!==void 0){this.nodefs.chmodSync(path$$1,attr.mode);node.mode=attr.mode}if(attr.timestamp!==void 0){var date=new Date(attr.timestamp);this.nodefs.utimesSync(path$$1,date,date)}}catch(e){if(!e.code){throw e}if(e.code!=="ENOTSUP"){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}if(attr.size!==void 0){try{this.nodefs.truncateSync(path$$1,attr.size)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}};BFSEmscriptenNodeOps.prototype.lookup=function lookup(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);var mode=this.fs.getMode(path$$1);return this.fs.createNode(parent,name,mode)};BFSEmscriptenNodeOps.prototype.mknod=function mknod(parent,name,mode,dev){var node=this.fs.createNode(parent,name,mode,dev);var path$$1=this.fs.realPath(node);try{if(this.FS.isDir(node.mode)){this.nodefs.mkdirSync(path$$1,node.mode)}else{this.nodefs.writeFileSync(path$$1,"",{mode:node.mode})}}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return node};BFSEmscriptenNodeOps.prototype.rename=function rename(oldNode,newDir,newName){var oldPath=this.fs.realPath(oldNode);var newPath=this.PATH.join2(this.fs.realPath(newDir),newName);try{this.nodefs.renameSync(oldPath,newPath);oldNode.name=newName;oldNode.parent=newDir}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.unlink=function unlink(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.unlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.rmdir=function rmdir(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.rmdirSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readdir=function readdir(node){var path$$1=this.fs.realPath(node);try{var contents=this.nodefs.readdirSync(path$$1);contents.push(".","..");return contents}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.symlink=function symlink(parent,newName,oldPath){var newPath=this.PATH.join2(this.fs.realPath(parent),newName);try{this.nodefs.symlinkSync(oldPath,newPath)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readlink=function readlink(node){var path$$1=this.fs.realPath(node);try{return this.nodefs.readlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};var BFSEmscriptenFS=function BFSEmscriptenFS2(_FS,_PATH,_ERRNO_CODES,nodefs){if(_FS===void 0)_FS=self["FS"];if(_PATH===void 0)_PATH=self["PATH"];if(_ERRNO_CODES===void 0)_ERRNO_CODES=self["ERRNO_CODES"];if(nodefs===void 0)nodefs=_fsMock;this.flagsToPermissionStringMap={0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"};this.nodefs=nodefs;this.FS=_FS;this.PATH=_PATH;this.ERRNO_CODES=_ERRNO_CODES;this.node_ops=new BFSEmscriptenNodeOps(this);this.stream_ops=new BFSEmscriptenStreamOps(this)};BFSEmscriptenFS.prototype.mount=function mount(m){return this.createNode(null,"/",this.getMode(m.opts.root),0)};BFSEmscriptenFS.prototype.createNode=function createNode(parent,name,mode,dev){var FS2=this.FS;if(!FS2.isDir(mode)&&!FS2.isFile(mode)&&!FS2.isLink(mode)){throw new FS2.ErrnoError(this.ERRNO_CODES.EINVAL)}var node=FS2.createNode(parent,name,mode);node.node_ops=this.node_ops;node.stream_ops=this.stream_ops;return node};BFSEmscriptenFS.prototype.getMode=function getMode(path$$1){var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return stat.mode};BFSEmscriptenFS.prototype.realPath=function realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return this.PATH.join.apply(null,parts)};BFSEmscriptenFS.prototype.flagsToPermissionString=function flagsToPermissionString(flags){var parsedFlags=typeof flags==="string"?parseInt(flags,10):flags;parsedFlags&=8191;if(parsedFlags in this.flagsToPermissionStringMap){return this.flagsToPermissionStringMap[parsedFlags]}else{return flags}};BFSEmscriptenFS.prototype.getNodeFS=function getNodeFS(){return this.nodefs};BFSEmscriptenFS.prototype.getFS=function getFS(){return this.FS};BFSEmscriptenFS.prototype.getPATH=function getPATH(){return this.PATH};BFSEmscriptenFS.prototype.getERRNO_CODES=function getERRNO_CODES(){return this.ERRNO_CODES};var BaseFileSystem=function BaseFileSystem2(){};BaseFileSystem.prototype.supportsLinks=function supportsLinks(){return false};BaseFileSystem.prototype.diskSpace=function diskSpace(p,cb){cb(0,0)};BaseFileSystem.prototype.openFile=function openFile(p,flag,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFile=function createFile(p,flag,mode,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.open=function open(p,flag,mode,cb){var this$1=this;var mustBeFile=function(e,stats){if(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.stat(path.dirname(p),false,function(e2,parentStats){if(e2){cb(e2)}else if(parentStats&&!parentStats.isDirectory()){cb(ApiError.ENOTDIR(path.dirname(p)))}else{this$1.createFile(p,flag,mode,cb)}});case ActionType.THROW_EXCEPTION:return cb(ApiError.ENOENT(p));default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}else{if(stats&&stats.isDirectory()){return cb(ApiError.EISDIR(p))}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:return cb(ApiError.EEXIST(p));case ActionType.TRUNCATE_FILE:return this$1.openFile(p,flag,function(e2,fd){if(e2){cb(e2)}else if(fd){fd.truncate(0,function(){fd.sync(function(){cb(null,fd)})})}else{fail()}});case ActionType.NOP:return this$1.openFile(p,flag,cb);default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}};this.stat(p,false,mustBeFile)};BaseFileSystem.prototype.rename=function rename(oldPath,newPath,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.renameSync=function renameSync(oldPath,newPath){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.stat=function stat(p,isLstat,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.statSync=function statSync(p,isLstat){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openFileSync=function openFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFileSync=function createFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openSync=function openSync(p,flag,mode){var stats;try{stats=this.statSync(p,false)}catch(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:var parentStats=this.statSync(path.dirname(p),false);if(!parentStats.isDirectory()){throw ApiError.ENOTDIR(path.dirname(p))}return this.createFileSync(p,flag,mode);case ActionType.THROW_EXCEPTION:throw ApiError.ENOENT(p);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}}if(stats.isDirectory()){throw ApiError.EISDIR(p)}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:throw ApiError.EEXIST(p);case ActionType.TRUNCATE_FILE:this.unlinkSync(p);return this.createFileSync(p,flag,stats.mode);case ActionType.NOP:return this.openFileSync(p,flag,mode);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}};BaseFileSystem.prototype.unlink=function unlink(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.unlinkSync=function unlinkSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.rmdir=function rmdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.rmdirSync=function rmdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.mkdir=function mkdir(p,mode,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.mkdirSync=function mkdirSync(p,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.readdir=function readdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.readdirSync=function readdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.exists=function exists2(p,cb){this.stat(p,null,function(err){cb(!err)})};BaseFileSystem.prototype.existsSync=function existsSync(p){try{this.statSync(p,true);return true}catch(e){return false}};BaseFileSystem.prototype.realpath=function realpath(p,cache,cb){if(this.supportsLinks()){var splitPath=p.split(path.sep);for(var i2=0;i2this._buffer.length){var buf=Buffer2.alloc(len-this._buffer.length,0);this.writeSync(buf,0,buf.length,this._buffer.length);if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}return}this._stat.size=len;var newBuff=Buffer2.alloc(len);this._buffer.copy(newBuff,0,0,len);this._buffer=newBuff;if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}};PreloadFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){this._dirty=true;if(position===void 0||position===null){position=this.getPos()}if(!this._flag.isWriteable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a writeable mode.")}var endFp=position+length;if(endFp>this._stat.size){this._stat.size=endFp;if(endFp>this._buffer.length){var newBuff=Buffer2.alloc(endFp);this._buffer.copy(newBuff);this._buffer=newBuff}}var len=buffer$$1.copy(this._buffer,position,offset,offset+length);this._stat.mtime=new Date;if(this._flag.isSynchronous()){this.syncSync();return len}this.setPos(position+len);return len};PreloadFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){if(!this._flag.isReadable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a readable mode.")}if(position===void 0||position===null){position=this.getPos()}var endRead=position+length;if(endRead>this._stat.size){length=this._stat.size-position}var rv=this._buffer.copy(buffer$$1,offset,position,position+length);this._stat.atime=new Date;this._pos=position+length;return rv};PreloadFile2.prototype.chmod=function chmod(mode,cb){try{this.chmodSync(mode);cb()}catch(e){cb(e)}};PreloadFile2.prototype.chmodSync=function chmodSync(mode){if(!this._fs.supportsProps()){throw new ApiError(ErrorCode.ENOTSUP)}this._dirty=true;this._stat.chmod(mode);this.syncSync()};PreloadFile2.prototype.isDirty=function isDirty(){return this._dirty};PreloadFile2.prototype.resetDirty=function resetDirty(){this._dirty=false};return PreloadFile2}(BaseFile);var NoSyncFile=function(PreloadFile2){function NoSyncFile2(_fs,_path,_flag,_stat,contents){PreloadFile2.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile2)NoSyncFile2.__proto__=PreloadFile2;NoSyncFile2.prototype=Object.create(PreloadFile2&&PreloadFile2.prototype);NoSyncFile2.prototype.constructor=NoSyncFile2;NoSyncFile2.prototype.sync=function sync(cb){cb()};NoSyncFile2.prototype.syncSync=function syncSync(){};NoSyncFile2.prototype.close=function close(cb){cb()};NoSyncFile2.prototype.closeSync=function closeSync(){};return NoSyncFile2}(PreloadFile);var MirrorFile=function(PreloadFile$$1){function MirrorFile2(fs4,path$$1,flag,stat,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,data)}if(PreloadFile$$1)MirrorFile2.__proto__=PreloadFile$$1;MirrorFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);MirrorFile2.prototype.constructor=MirrorFile2;MirrorFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};MirrorFile2.prototype.closeSync=function closeSync(){this.syncSync()};return MirrorFile2}(PreloadFile);var AsyncMirror=function(SynchronousFileSystem$$1){function AsyncMirror2(sync,async,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this._queue=[];this._queueRunning=false;this._isInitialized=false;this._initializeCallbacks=[];this._sync=sync;this._async=async;if(!sync.supportsSynch()){throw new Error("The first argument to AsyncMirror needs to be a synchronous file system.")}deprecationMessage(deprecateMsg,AsyncMirror2.Name,{sync:"sync file system instance",async:"async file system instance"})}if(SynchronousFileSystem$$1)AsyncMirror2.__proto__=SynchronousFileSystem$$1;AsyncMirror2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);AsyncMirror2.prototype.constructor=AsyncMirror2;AsyncMirror2.Create=function Create(opts,cb){try{var fs4=new AsyncMirror2(opts.sync,opts.async,false);fs4.initialize(function(e){if(e){cb(e)}else{cb(null,fs4)}},false)}catch(e){cb(e)}};AsyncMirror2.isAvailable=function isAvailable(){return true};AsyncMirror2.prototype.getName=function getName(){return AsyncMirror2.Name};AsyncMirror2.prototype._syncSync=function _syncSync(fd){this._sync.writeFileSync(fd.getPath(),fd.getBuffer(),null,FileFlag.getFileFlag("w"),fd.getStats().mode);this.enqueueOp({apiMethod:"writeFile",arguments:[fd.getPath(),fd.getBuffer(),null,fd.getFlag(),fd.getStats().mode]})};AsyncMirror2.prototype.initialize=function initialize3(userCb,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.")}var callbacks=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbacks.forEach(function(cb){return cb(e)})};if(!this._isInitialized){if(callbacks.push(userCb)===1){var copyDirectory=function(p,mode,cb){if(p!=="/"){this$1._sync.mkdirSync(p,mode)}this$1._async.readdir(p,function(err,files){var i2=0;function copyNextFile(err2){if(err2){cb(err2)}else if(i20){var op2=this$1._queue.shift(),args=op2.arguments;args.push(doNextOp);this$1._async[op2.apiMethod].apply(this$1._async,args)}else{this$1._queueRunning=false}};doNextOp()}};return AsyncMirror2}(SynchronousFileSystem);AsyncMirror.Name="AsyncMirror";AsyncMirror.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to."},async:{type:"object",description:"The asynchronous file system to mirror."}};function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}var nativeMax=Math.max;function overRest$1(func,start,transform){start=nativeMax(start===void 0?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}var breakLoop={};function noop(){}function once(fn){return function(){if(fn===null){return}var callFn=fn;fn=null;callFn.apply(this,arguments)}}var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator;var getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()};function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index-1&&value%1==0&&value++numRun){switch(error.status){case Dropbox.ApiError.SERVER_ERROR:case Dropbox.ApiError.NETWORK_ERROR:case Dropbox.ApiError.RATE_LIMITED:setTimeout(function(){performOp(interceptCb)},timeoutDuration*1e3);break;default:cb.apply(null,arguments);break}}else{cb.apply(null,arguments)}};performOp(interceptCb)};CachedDropboxClient.prototype.getCachedInfo=function getCachedInfo(p){return this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.putCachedInfo=function putCachedInfo(p,cache){this._cache[p.toLowerCase()]=cache};CachedDropboxClient.prototype.deleteCachedInfo=function deleteCachedInfo(p){delete this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.getCachedDirInfo=function getCachedDirInfo(p){var info=this.getCachedInfo(p);if(isDirInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.getCachedFileInfo=function getCachedFileInfo(p){var info=this.getCachedInfo(p);if(isFileInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.updateCachedDirInfo=function updateCachedDirInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.contentHash!==null&&(cachedInfo===void 0||cachedInfo.stat.contentHash!==stat.contentHash)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedFileInfo=function updateCachedFileInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.versionTag!==null&&(cachedInfo===void 0||cachedInfo.stat.versionTag!==stat.versionTag)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedInfo=function updateCachedInfo(p,stat,contents){if(contents===void 0)contents=null;if(stat.isFile&&isArrayBuffer(contents)){this.updateCachedFileInfo(p,stat,contents)}else if(stat.isFolder&&Array.isArray(contents)){this.updateCachedDirInfo(p,stat,contents)}};var DropboxFile=function(PreloadFile$$1){function DropboxFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)DropboxFile2.__proto__=PreloadFile$$1;DropboxFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);DropboxFile2.prototype.constructor=DropboxFile2;DropboxFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){var buffer$$1=this.getBuffer(),arrayBuffer=buffer2ArrayBuffer(buffer$$1);this._fs._writeFileStrict(this.getPath(),arrayBuffer,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};DropboxFile2.prototype.close=function close(cb){this.sync(cb)};return DropboxFile2}(PreloadFile);var DropboxFileSystem=function(BaseFileSystem$$1){function DropboxFileSystem2(client,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._client=new CachedDropboxClient(client);deprecationMessage(deprecateMsg,DropboxFileSystem2.Name,{client:"authenticated dropbox client instance"});constructErrorCodeLookup()}if(BaseFileSystem$$1)DropboxFileSystem2.__proto__=BaseFileSystem$$1;DropboxFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);DropboxFileSystem2.prototype.constructor=DropboxFileSystem2;DropboxFileSystem2.Create=function Create(opts,cb){cb(null,new DropboxFileSystem2(opts.client,false))};DropboxFileSystem2.isAvailable=function isAvailable(){return typeof Dropbox!=="undefined"};DropboxFileSystem2.prototype.getName=function getName(){return DropboxFileSystem2.Name};DropboxFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};DropboxFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};DropboxFileSystem2.prototype.supportsProps=function supportsProps(){return false};DropboxFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};DropboxFileSystem2.prototype.empty=function empty(mainCb){var this$1=this;this._client.readdir("/",function(error,files){if(error){mainCb(this$1.convert(error,"/"))}else{var deleteFile2=function(file,cb){var p=path.join("/",file);this$1._client.remove(p,function(err){cb(err?this$1.convert(err,p):null)})};var finished=function(err){if(err){mainCb(err)}else{mainCb()}};eachLimit(files,deleteFile2,finished)}})};DropboxFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._client.move(oldPath,newPath,function(error){if(error){this$1._client.stat(newPath,function(error2,stat){if(error2||stat.isFolder){var missingPath=error.response.error.indexOf(oldPath)>-1?oldPath:newPath;cb(this$1.convert(error,missingPath))}else{this$1._client.remove(newPath,function(error22){if(error22){cb(this$1.convert(error22,newPath))}else{this$1.rename(oldPath,newPath,cb)}})}})}else{cb()}})};DropboxFileSystem2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;this._client.stat(path$$1,function(error,stat2){if(error){cb(this$1.convert(error,path$$1))}else if(stat2&&stat2.isRemoved){cb(ApiError.FileError(ErrorCode.ENOENT,path$$1))}else{var stats=new Stats(this$1._statType(stat2),stat2.size);return cb(null,stats)}})};DropboxFileSystem2.prototype.open=function open(path$$1,flags,mode,cb){var this$1=this;this._client.readFile(path$$1,function(error,content,dbStat){if(error){if(flags.isReadable()){cb(this$1.convert(error,path$$1))}else{switch(error.status){case Dropbox.ApiError.NOT_FOUND:var ab=new ArrayBuffer(0);return this$1._writeFileStrict(path$$1,ab,function(error2,stat){if(error2){cb(error2)}else{var file2=this$1._makeFile(path$$1,flags,stat,arrayBuffer2Buffer(ab));cb(null,file2)}});default:return cb(this$1.convert(error,path$$1))}}}else{var buffer$$1;if(content===null){buffer$$1=emptyBuffer()}else{buffer$$1=arrayBuffer2Buffer(content)}var file=this$1._makeFile(path$$1,flags,dbStat,buffer$$1);return cb(null,file)}})};DropboxFileSystem2.prototype._writeFileStrict=function _writeFileStrict(p,data,cb){var this$1=this;var parent=path.dirname(p);this.stat(parent,false,function(error,stat){if(error){cb(ApiError.FileError(ErrorCode.ENOENT,parent))}else{this$1._client.writeFile(p,data,function(error2,stat2){if(error2){cb(this$1.convert(error2,p))}else{cb(null,stat2)}})}})};DropboxFileSystem2.prototype._statType=function _statType(stat){return stat.isFile?FileType.FILE:FileType.DIRECTORY};DropboxFileSystem2.prototype._makeFile=function _makeFile(path$$1,flag,stat,buffer$$1){var type=this._statType(stat);var stats=new Stats(type,stat.size);return new DropboxFile(this,path$$1,flag,stats,buffer$$1)};DropboxFileSystem2.prototype._remove=function _remove(path$$1,cb,isFile){var this$1=this;this._client.stat(path$$1,function(error,stat){if(error){cb(this$1.convert(error,path$$1))}else{if(stat.isFile&&!isFile){cb(ApiError.FileError(ErrorCode.ENOTDIR,path$$1))}else if(!stat.isFile&&isFile){cb(ApiError.FileError(ErrorCode.EISDIR,path$$1))}else{this$1._client.remove(path$$1,function(error2){if(error2){cb(this$1.convert(error2,path$$1))}else{cb(null)}})}}})};DropboxFileSystem2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};DropboxFileSystem2.prototype.rmdir=function rmdir(path$$1,cb){this._remove(path$$1,cb,false)};DropboxFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;var parent=path.dirname(p);this._client.stat(parent,function(error,stat){if(error){cb(this$1.convert(error,parent))}else{this$1._client.mkdir(p,function(error2){if(error2){cb(ApiError.FileError(ErrorCode.EEXIST,p))}else{cb(null)}})}})};DropboxFileSystem2.prototype.readdir=function readdir(path$$1,cb){var this$1=this;this._client.readdir(path$$1,function(error,files){if(error){return cb(this$1.convert(error))}else{return cb(null,files)}})};DropboxFileSystem2.prototype.convert=function convert(err,path$$1){if(path$$1===void 0)path$$1=null;var errorCode=errorCodeLookup[err.status];if(errorCode===void 0){errorCode=ErrorCode.EIO}if(!path$$1){return new ApiError(errorCode)}else{return ApiError.FileError(errorCode,path$$1)}};return DropboxFileSystem2}(BaseFileSystem);DropboxFileSystem.Name="Dropbox";DropboxFileSystem.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.",validator:function(opt,cb){if(opt.isAuthenticated&&opt.isAuthenticated()){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK."))}}}};function convertError(e,path$$1){if(path$$1===void 0)path$$1="";var errno=e.errno;var parent=e.node;var paths=[];while(parent){paths.unshift(parent.name);if(parent===parent.parent){break}parent=parent.parent}return new ApiError(errno,ErrorStrings[errno],paths.length>0?"/"+paths.join("/"):path$$1)}var EmscriptenFile=function(BaseFile$$1){function EmscriptenFile2(_fs,_FS,_path,_stream){BaseFile$$1.call(this);this._fs=_fs;this._FS=_FS;this._path=_path;this._stream=_stream}if(BaseFile$$1)EmscriptenFile2.__proto__=BaseFile$$1;EmscriptenFile2.prototype=Object.create(BaseFile$$1&&BaseFile$$1.prototype);EmscriptenFile2.prototype.constructor=EmscriptenFile2;EmscriptenFile2.prototype.getPos=function getPos(){return void 0};EmscriptenFile2.prototype.close=function close(cb){var err=null;try{this.closeSync()}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.closeSync=function closeSync(){try{this._FS.close(this._stream)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.stat=function stat(cb){try{cb(null,this.statSync())}catch(e){cb(e)}};EmscriptenFile2.prototype.statSync=function statSync(){try{return this._fs.statSync(this._path,false)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.truncate=function truncate(len,cb){var err=null;try{this.truncateSync(len)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.truncateSync=function truncateSync(len){try{this._FS.ftruncate(this._stream.fd,len)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.write(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.read(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.sync=function sync(cb){cb()};EmscriptenFile2.prototype.syncSync=function syncSync(){};EmscriptenFile2.prototype.chown=function chown(uid,gid,cb){var err=null;try{this.chownSync(uid,gid)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chownSync=function chownSync(uid,gid){try{this._FS.fchown(this._stream.fd,uid,gid)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.chmod=function chmod(mode,cb){var err=null;try{this.chmodSync(mode)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chmodSync=function chmodSync(mode){try{this._FS.fchmod(this._stream.fd,mode)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.utimes=function utimes(atime,mtime,cb){var err=null;try{this.utimesSync(atime,mtime)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.utimesSync=function utimesSync(atime,mtime){this._fs.utimesSync(this._path,atime,mtime)};return EmscriptenFile2}(BaseFile);var EmscriptenFileSystem=function(SynchronousFileSystem$$1){function EmscriptenFileSystem2(_FS){SynchronousFileSystem$$1.call(this);this._FS=_FS}if(SynchronousFileSystem$$1)EmscriptenFileSystem2.__proto__=SynchronousFileSystem$$1;EmscriptenFileSystem2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);EmscriptenFileSystem2.prototype.constructor=EmscriptenFileSystem2;EmscriptenFileSystem2.Create=function Create(opts,cb){cb(null,new EmscriptenFileSystem2(opts.FS))};EmscriptenFileSystem2.isAvailable=function isAvailable(){return true};EmscriptenFileSystem2.prototype.getName=function getName(){return this._FS.DB_NAME()};EmscriptenFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};EmscriptenFileSystem2.prototype.supportsLinks=function supportsLinks(){return true};EmscriptenFileSystem2.prototype.supportsProps=function supportsProps(){return true};EmscriptenFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};EmscriptenFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){try{this._FS.rename(oldPath,newPath)}catch(e){if(e.errno===ErrorCode.ENOENT){throw convertError(e,this.existsSync(oldPath)?newPath:oldPath)}else{throw convertError(e)}}};EmscriptenFileSystem2.prototype.statSync=function statSync(p,isLstat){try{var stats=isLstat?this._FS.lstat(p):this._FS.stat(p);var itemType=this.modeToFileType(stats.mode);return new Stats(itemType,stats.size,stats.mode,stats.atime,stats.mtime,stats.ctime)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.openSync=function openSync(p,flag,mode){try{var stream=this._FS.open(p,flag.getFlagString(),mode);if(this._FS.isDir(stream.node.mode)){this._FS.close(stream);throw ApiError.EISDIR(p)}return new EmscriptenFile(this,this._FS,p,stream)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.unlinkSync=function unlinkSync(p){try{this._FS.unlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.rmdirSync=function rmdirSync(p){try{this._FS.rmdir(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){try{this._FS.mkdir(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readdirSync=function readdirSync(p){try{return this._FS.readdir(p).filter(function(p2){return p2!=="."&&p2!==".."})}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.truncateSync=function truncateSync(p,len){try{this._FS.truncate(p,len)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readFileSync=function readFileSync(p,encoding,flag){try{var data=this._FS.readFile(p,{flags:flag.getFlagString()});var buff=uint8Array2Buffer(data);if(encoding){return buff.toString(encoding)}else{return buff}}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.writeFileSync=function writeFileSync(p,data,encoding,flag,mode){try{if(encoding){data=Buffer2.from(data,encoding)}var u8=buffer2Uint8array(data);this._FS.writeFile(p,u8,{flags:flag.getFlagString(),encoding:"binary"});this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){try{isLchmod?this._FS.lchmod(p,mode):this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){try{isLchown?this._FS.lchown(p,uid,gid):this._FS.chown(p,uid,gid)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){try{this._FS.symlink(srcpath,dstpath)}catch(e){throw convertError(e)}};EmscriptenFileSystem2.prototype.readlinkSync=function readlinkSync(p){try{return this._FS.readlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.utimesSync=function utimesSync(p,atime,mtime){try{this._FS.utime(p,atime.getTime(),mtime.getTime())}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.modeToFileType=function modeToFileType(mode){if(this._FS.isDir(mode)){return FileType.DIRECTORY}else if(this._FS.isFile(mode)){return FileType.FILE}else if(this._FS.isLink(mode)){return FileType.SYMLINK}else{throw ApiError.EPERM("Invalid mode: "+mode)}};return EmscriptenFileSystem2}(SynchronousFileSystem);EmscriptenFileSystem.Name="EmscriptenFileSystem";EmscriptenFileSystem.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var FolderAdapter=function(BaseFileSystem$$1){function FolderAdapter2(folder,wrapped){BaseFileSystem$$1.call(this);this._folder=folder;this._wrapped=wrapped}if(BaseFileSystem$$1)FolderAdapter2.__proto__=BaseFileSystem$$1;FolderAdapter2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);FolderAdapter2.prototype.constructor=FolderAdapter2;FolderAdapter2.Create=function Create(opts,cb){cb(null,new FolderAdapter2(opts.folder,opts.wrapped))};FolderAdapter2.isAvailable=function isAvailable(){return true};FolderAdapter2.prototype.initialize=function initialize3(cb){var this$1=this;this._wrapped.exists(this._folder,function(exists2){if(exists2){cb()}else if(this$1._wrapped.isReadOnly()){cb(ApiError.ENOENT(this$1._folder))}else{this$1._wrapped.mkdir(this$1._folder,511,cb)}})};FolderAdapter2.prototype.getName=function getName(){return this._wrapped.getName()};FolderAdapter2.prototype.isReadOnly=function isReadOnly(){return this._wrapped.isReadOnly()};FolderAdapter2.prototype.supportsProps=function supportsProps(){return this._wrapped.supportsProps()};FolderAdapter2.prototype.supportsSynch=function supportsSynch(){return this._wrapped.supportsSynch()};FolderAdapter2.prototype.supportsLinks=function supportsLinks(){return false};return FolderAdapter2}(BaseFileSystem);FolderAdapter.Name="FolderAdapter";FolderAdapter.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}};function translateError(folder,e){if(e!==null&&typeof e==="object"){var err=e;var p=err.path;if(p){p="/"+path.relative(folder,p);err.message=err.message.replace(err.path,p);err.path=p}}return e}function wrapCallback(folder,cb){if(typeof cb==="function"){return function(err){if(arguments.length>0){arguments[0]=translateError(folder,err)}cb.apply(null,arguments)}}else{return cb}}function wrapFunction(name,wrapFirst,wrapSecond){if(name.slice(name.length-4)!=="Sync"){return function(){if(arguments.length>0){if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}arguments[arguments.length-1]=wrapCallback(this._folder,arguments[arguments.length-1])}return this._wrapped[name].apply(this._wrapped,arguments)}}else{return function(){try{if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}return this._wrapped[name].apply(this._wrapped,arguments)}catch(e){throw translateError(this._folder,e)}}}}["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,false)});["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,true)});var toExport;if(typeof window!=="undefined"){toExport=window}else if(typeof self!=="undefined"){toExport=self}else{toExport=global}var global$1=toExport;function isDirectoryEntry(entry){return entry.isDirectory}var _getFS=global$1.webkitRequestFileSystem||global$1.requestFileSystem||null;function _requestQuota(type,size,success,errorCallback){if(typeof navigator["webkitPersistentStorage"]!=="undefined"){switch(type){case global$1.PERSISTENT:navigator.webkitPersistentStorage.requestQuota(size,success,errorCallback);break;case global$1.TEMPORARY:navigator.webkitTemporaryStorage.requestQuota(size,success,errorCallback);break;default:errorCallback(new TypeError("Invalid storage type: "+type));break}}else{global$1.webkitStorageInfo.requestQuota(type,size,success,errorCallback)}}function _toArray(list2){return Array.prototype.slice.call(list2||[],0)}function convertError$1(err,p,expectedDir){switch(err.name){case"PathExistsError":return ApiError.EEXIST(p);case"QuotaExceededError":return ApiError.FileError(ErrorCode.ENOSPC,p);case"NotFoundError":return ApiError.ENOENT(p);case"SecurityError":return ApiError.FileError(ErrorCode.EACCES,p);case"InvalidModificationError":return ApiError.FileError(ErrorCode.EPERM,p);case"TypeMismatchError":return ApiError.FileError(expectedDir?ErrorCode.ENOTDIR:ErrorCode.EISDIR,p);case"EncodingError":case"InvalidStateError":case"NoModificationAllowedError":default:return ApiError.FileError(ErrorCode.EINVAL,p)}}var HTML5FSFile=function(PreloadFile$$1){function HTML5FSFile2(fs4,entry,path$$1,flag,stat,contents){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,contents);this._entry=entry}if(PreloadFile$$1)HTML5FSFile2.__proto__=PreloadFile$$1;HTML5FSFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);HTML5FSFile2.prototype.constructor=HTML5FSFile2;HTML5FSFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){return cb()}this._entry.createWriter(function(writer){var buffer$$1=this$1.getBuffer();var blob=new Blob([buffer2ArrayBuffer(buffer$$1)]);var length=blob.size;writer.onwriteend=function(err){writer.onwriteend=null;writer.onerror=null;writer.truncate(length);this$1.resetDirty();cb()};writer.onerror=function(err){cb(convertError$1(err,this$1.getPath(),false))};writer.write(blob)})};HTML5FSFile2.prototype.close=function close(cb){this.sync(cb)};return HTML5FSFile2}(PreloadFile);var HTML5FS=function(BaseFileSystem$$1){function HTML5FS2(size,type,deprecateMsg){if(size===void 0)size=5;if(type===void 0)type=global$1.PERSISTENT;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this.size=1024*1024*size;this.type=type;deprecationMessage(deprecateMsg,HTML5FS2.Name,{size,type})}if(BaseFileSystem$$1)HTML5FS2.__proto__=BaseFileSystem$$1;HTML5FS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);HTML5FS2.prototype.constructor=HTML5FS2;HTML5FS2.Create=function Create(opts,cb){var fs4=new HTML5FS2(opts.size,opts.type,false);fs4.allocate(function(e){return e?cb(e):cb(null,fs4)},false)};HTML5FS2.isAvailable=function isAvailable(){return!!_getFS};HTML5FS2.prototype.getName=function getName(){return HTML5FS2.Name};HTML5FS2.prototype.isReadOnly=function isReadOnly(){return false};HTML5FS2.prototype.supportsSymlinks=function supportsSymlinks(){return false};HTML5FS2.prototype.supportsProps=function supportsProps(){return false};HTML5FS2.prototype.supportsSynch=function supportsSynch(){return false};HTML5FS2.prototype.allocate=function allocate(cb,deprecateMsg){var this$1=this;if(cb===void 0)cb=function(){};if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: "+this.type+", size: "+this.size+"}, cb)' to create and allocate HTML5FS instances.")}var success=function(fs4){this$1.fs=fs4;cb()};var error=function(err){cb(convertError$1(err,"/",true))};if(this.type===global$1.PERSISTENT){_requestQuota(this.type,this.size,function(granted){_getFS(this$1.type,granted,success,error)},error)}else{_getFS(this.type,this.size,success,error)}};HTML5FS2.prototype.empty=function empty(mainCb){this._readdir("/",function(err,entries){if(err){console.error("Failed to empty FS");mainCb(err)}else{var finished=function(er){if(err){console.error("Failed to empty FS");mainCb(err)}else{mainCb()}};var deleteEntry=function(entry,cb){var succ=function(){cb()};var error=function(err2){cb(convertError$1(err2,entry.fullPath,!entry.isDirectory))};if(isDirectoryEntry(entry)){entry.removeRecursively(succ,error)}else{entry.remove(succ,error)}};eachLimit(entries,deleteEntry,finished)}})};HTML5FS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var semaphore=2;var successCount=0;var root2=this.fs.root;var currentPath=oldPath;var error=function(err){if(--semaphore<=0){cb(convertError$1(err,currentPath,false))}};var success=function(file){if(++successCount===2){return cb(new ApiError(ErrorCode.EINVAL,"Something was identified as both a file and a directory. This should never happen."))}if(oldPath===newPath){return cb()}currentPath=path.dirname(newPath);root2.getDirectory(currentPath,{},function(parentDir){currentPath=path.basename(newPath);file.moveTo(parentDir,currentPath,function(entry){cb()},function(err){if(file.isDirectory){currentPath=newPath;this$1.unlink(newPath,function(e){if(e){error(err)}else{this$1.rename(oldPath,newPath,cb)}})}else{error(err)}})},error)};root2.getFile(oldPath,{},success,error);root2.getDirectory(oldPath,{},success,error)};HTML5FS2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;var opts={create:false};var loadAsFile=function(entry){var fileFromEntry=function(file){var stat2=new Stats(FileType.FILE,file.size);cb(null,stat2)};entry.file(fileFromEntry,failedToLoad)};var loadAsDir=function(dir$$1){var size=4096;var stat2=new Stats(FileType.DIRECTORY,size);cb(null,stat2)};var failedToLoad=function(err){cb(convertError$1(err,path$$1,false))};var failedToLoadAsFile=function(){this$1.fs.root.getDirectory(path$$1,opts,loadAsDir,failedToLoad)};this.fs.root.getFile(path$$1,opts,loadAsFile,failedToLoadAsFile)};HTML5FS2.prototype.open=function open(p,flags,mode,cb){var this$1=this;var error=function(err){if(err.name==="InvalidModificationError"&&flags.isExclusive()){cb(ApiError.EEXIST(p))}else{cb(convertError$1(err,p,false))}};this.fs.root.getFile(p,{create:flags.pathNotExistsAction()===ActionType.CREATE_FILE,exclusive:flags.isExclusive()},function(entry){entry.file(function(file){var reader=new FileReader;reader.onloadend=function(event){var bfsFile=this$1._makeFile(p,entry,flags,file,reader.result);cb(null,bfsFile)};reader.onerror=function(ev){error(reader.error)};reader.readAsArrayBuffer(file)},error)},error)};HTML5FS2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};HTML5FS2.prototype.rmdir=function rmdir(path$$1,cb){var this$1=this;this.readdir(path$$1,function(e,files){if(e){cb(e)}else if(files.length>0){cb(ApiError.ENOTEMPTY(path$$1))}else{this$1._remove(path$$1,cb,false)}})};HTML5FS2.prototype.mkdir=function mkdir(path$$1,mode,cb){var opts={create:true,exclusive:true};var success=function(dir$$1){cb()};var error=function(err){cb(convertError$1(err,path$$1,true))};this.fs.root.getDirectory(path$$1,opts,success,error)};HTML5FS2.prototype.readdir=function readdir(path$$1,cb){this._readdir(path$$1,function(e,entries){if(entries){var rv=[];for(var i2=0,list2=entries;i20){throw ApiError.ENOTEMPTY(p)}else{this.removeEntry(p,true)}};SyncKeyValueFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data)};SyncKeyValueFileSystem2.prototype.readdirSync=function readdirSync(p){var tx=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(tx,p,this.findINode(tx,p)))};SyncKeyValueFileSystem2.prototype._syncSync=function _syncSync(p,data,stats){var tx=this.store.beginTransaction("readwrite"),fileInodeId=this._findINode(tx,path.dirname(p),path.basename(p)),fileInode=this.getINode(tx,p,fileInodeId),inodeChanged=fileInode.update(stats);try{tx.put(fileInode.id,data,true);if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true)}}catch(e){tx.abort();throw e}tx.commit()};SyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(){var tx=this.store.beginTransaction("readwrite");if(tx.get(ROOT_NODE_ID)===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false);tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false);tx.commit()}};SyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename){var this$1=this;var readDirectory=function(inode){var dirList=this$1.getDirListing(tx,parent,inode);if(dirList[filename]){return dirList[filename]}else{throw ApiError.ENOENT(path.resolve(parent,filename))}};if(parent==="/"){if(filename===""){return ROOT_NODE_ID}else{return readDirectory(this.getINode(tx,parent,ROOT_NODE_ID))}}else{return readDirectory(this.getINode(tx,parent+path.sep+filename,this._findINode(tx,path.dirname(parent),path.basename(parent))))}};SyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p){return this.getINode(tx,p,this._findINode(tx,path.dirname(p),path.basename(p)))};SyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id){var inode=tx.get(id);if(inode===void 0){throw ApiError.ENOENT(p)}return Inode.fromBuffer(inode)};SyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode){if(!inode.isDirectory()){throw ApiError.ENOTDIR(p)}var data=tx.get(inode.id);if(data===void 0){throw ApiError.ENOENT(p)}return JSON.parse(data.toString())};SyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data){var retries=0;var currId;while(retries<5){try{currId=GenerateRandomID();tx.put(currId,data,false);return currId}catch(e){}}throw new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store.")};SyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data){var parentDir=path.dirname(p),fname=path.basename(p),parentNode=this.findINode(tx,parentDir),dirListing=this.getDirListing(tx,parentDir,parentNode),currTime=new Date().getTime();if(p==="/"){throw ApiError.EEXIST(p)}if(dirListing[fname]){throw ApiError.EEXIST(p)}var fileNode;try{var dataId=this.addNewNode(tx,data);fileNode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);var fileNodeId=this.addNewNode(tx,fileNode.toBuffer());dirListing[fname]=fileNodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true)}catch(e){tx.abort();throw e}tx.commit();return fileNode};SyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir){var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),parentNode=this.findINode(tx,parent),parentListing=this.getDirListing(tx,parent,parentNode),fileName=path.basename(p);if(!parentListing[fileName]){throw ApiError.ENOENT(p)}var fileNodeId=parentListing[fileName];delete parentListing[fileName];var fileNode=this.getINode(tx,p,fileNodeId);if(!isDir&&fileNode.isDirectory()){throw ApiError.EISDIR(p)}else if(isDir&&!fileNode.isDirectory()){throw ApiError.ENOTDIR(p)}try{tx.del(fileNode.id);tx.del(fileNodeId);tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true)}catch(e){tx.abort();throw e}tx.commit()};return SyncKeyValueFileSystem2}(SynchronousFileSystem);var AsyncKeyValueFile=function(PreloadFile$$1){function AsyncKeyValueFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)AsyncKeyValueFile2.__proto__=PreloadFile$$1;AsyncKeyValueFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);AsyncKeyValueFile2.prototype.constructor=AsyncKeyValueFile2;AsyncKeyValueFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};AsyncKeyValueFile2.prototype.close=function close(cb){this.sync(cb)};return AsyncKeyValueFile2}(PreloadFile);var AsyncKeyValueFileSystem=function(BaseFileSystem$$1){function AsyncKeyValueFileSystem2(){BaseFileSystem$$1.apply(this,arguments)}if(BaseFileSystem$$1)AsyncKeyValueFileSystem2.__proto__=BaseFileSystem$$1;AsyncKeyValueFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);AsyncKeyValueFileSystem2.prototype.constructor=AsyncKeyValueFileSystem2;AsyncKeyValueFileSystem2.isAvailable=function isAvailable(){return true};AsyncKeyValueFileSystem2.prototype.init=function init(store,cb){this.store=store;this.makeRootDirectory(cb)};AsyncKeyValueFileSystem2.prototype.getName=function getName(){return this.store.name()};AsyncKeyValueFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};AsyncKeyValueFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};AsyncKeyValueFileSystem2.prototype.supportsProps=function supportsProps(){return false};AsyncKeyValueFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};AsyncKeyValueFileSystem2.prototype.empty=function empty(cb){var this$1=this;this.store.clear(function(e){if(noError(e,cb)){this$1.makeRootDirectory(cb)}})};AsyncKeyValueFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");var oldParent=path.dirname(oldPath),oldName=path.basename(oldPath);var newParent=path.dirname(newPath),newName=path.basename(newPath);var inodes={};var lists={};var errorOccurred=false;if((newParent+"/").indexOf(oldPath+"/")===0){return cb(new ApiError(ErrorCode.EBUSY,oldParent))}var theOleSwitcharoo=function(){if(errorOccurred||!lists.hasOwnProperty(oldParent)||!lists.hasOwnProperty(newParent)){return}var oldParentList=lists[oldParent],oldParentINode=inodes[oldParent],newParentList=lists[newParent],newParentINode=inodes[newParent];if(!oldParentList[oldName]){cb(ApiError.ENOENT(oldPath))}else{var fileId=oldParentList[oldName];delete oldParentList[oldName];var completeRename=function(){newParentList[newName]=fileId;tx.put(oldParentINode.id,Buffer2.from(JSON.stringify(oldParentList)),true,function(e){if(noErrorTx(e,tx,cb)){if(oldParent===newParent){tx.commit(cb)}else{tx.put(newParentINode.id,Buffer2.from(JSON.stringify(newParentList)),true,function(e2){if(noErrorTx(e2,tx,cb)){tx.commit(cb)}})}}})};if(newParentList[newName]){this$1.getINode(tx,newPath,newParentList[newName],function(e,inode){if(noErrorTx(e,tx,cb)){if(inode.isFile()){tx.del(inode.id,function(e2){if(noErrorTx(e2,tx,cb)){tx.del(newParentList[newName],function(e3){if(noErrorTx(e3,tx,cb)){completeRename()}})}})}else{tx.abort(function(e2){cb(ApiError.EPERM(newPath))})}}})}else{completeRename()}}};var processInodeAndListings=function(p){this$1.findINodeAndDirListing(tx,p,function(e,node,dirList){if(e){if(!errorOccurred){errorOccurred=true;tx.abort(function(){cb(e)})}}else{inodes[p]=node;lists[p]=dirList;theOleSwitcharoo()}})};processInodeAndListings(oldParent);if(oldParent!==newParent){processInodeAndListings(newParent)}};AsyncKeyValueFileSystem2.prototype.stat=function stat(p,isLstat,cb){var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){cb(null,inode.toStats())}})};AsyncKeyValueFileSystem2.prototype.createFile=function createFile(p,flag,mode,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),data=emptyBuffer();this.commitNewFile(tx,p,FileType.FILE,mode,data,function(e,newFile){if(noError(e,cb)){cb(null,new AsyncKeyValueFile(this$1,p,flag,newFile.toStats(),data))}})};AsyncKeyValueFileSystem2.prototype.openFile=function openFile(p,flag,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){tx.get(inode.id,function(e2,data){if(noError(e2,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,new AsyncKeyValueFile(this$1,p,flag,inode.toStats(),data))}}})}})};AsyncKeyValueFileSystem2.prototype.unlink=function unlink(p,cb){this.removeEntry(p,false,cb)};AsyncKeyValueFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;this.readdir(p,function(err,files){if(err){cb(err)}else if(files.length>0){cb(ApiError.ENOTEMPTY(p))}else{this$1.removeEntry(p,true,cb)}})};AsyncKeyValueFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data,cb)};AsyncKeyValueFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,dirListing){if(noError(e2,cb)){cb(null,Object.keys(dirListing))}})}})};AsyncKeyValueFileSystem2.prototype._sync=function _sync(p,data,stats,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");this._findINode(tx,path.dirname(p),path.basename(p),function(e,fileInodeId){if(noErrorTx(e,tx,cb)){this$1.getINode(tx,p,fileInodeId,function(e2,fileInode){if(noErrorTx(e2,tx,cb)){var inodeChanged=fileInode.update(stats);tx.put(fileInode.id,data,true,function(e3){if(noErrorTx(e3,tx,cb)){if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(cb)}})}else{tx.commit(cb)}}})}})}})};AsyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(cb){var tx=this.store.beginTransaction("readwrite");tx.get(ROOT_NODE_ID,function(e,data){if(e||data===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false,function(e2){if(noErrorTx(e2,tx,cb)){tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false,function(e3){if(e3){tx.abort(function(){cb(e3)})}else{tx.commit(cb)}})}})}else{tx.commit(cb)}})};AsyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename,cb){var this$1=this;var handleDirectoryListings=function(e,inode,dirList){if(e){cb(e)}else if(dirList[filename]){cb(null,dirList[filename])}else{cb(ApiError.ENOENT(path.resolve(parent,filename)))}};if(parent==="/"){if(filename===""){cb(null,ROOT_NODE_ID)}else{this.getINode(tx,parent,ROOT_NODE_ID,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,parent,inode,function(e2,dirList){handleDirectoryListings(e2,inode,dirList)})}})}}else{this.findINodeAndDirListing(tx,parent,handleDirectoryListings)}};AsyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p,cb){var this$1=this;this._findINode(tx,path.dirname(p),path.basename(p),function(e,id){if(noError(e,cb)){this$1.getINode(tx,p,id,cb)}})};AsyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id,cb){tx.get(id,function(e,data){if(noError(e,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,Inode.fromBuffer(data))}}})};AsyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode,cb){if(!inode.isDirectory()){cb(ApiError.ENOTDIR(p))}else{tx.get(inode.id,function(e,data){if(noError(e,cb)){try{cb(null,JSON.parse(data.toString()))}catch(e2){cb(ApiError.ENOENT(p))}}})}};AsyncKeyValueFileSystem2.prototype.findINodeAndDirListing=function findINodeAndDirListing(tx,p,cb){var this$1=this;this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,listing){if(noError(e2,cb)){cb(null,inode,listing)}})}})};AsyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data,cb){var retries=0,currId;var reroll=function(){if(++retries===5){cb(new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store."))}else{currId=GenerateRandomID();tx.put(currId,data,false,function(e,committed){if(e||!committed){reroll()}else{cb(null,currId)}})}};reroll()};AsyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data,cb){var this$1=this;var parentDir=path.dirname(p),fname=path.basename(p),currTime=new Date().getTime();if(p==="/"){return cb(ApiError.EEXIST(p))}this.findINodeAndDirListing(tx,parentDir,function(e,parentNode,dirListing){if(noErrorTx(e,tx,cb)){if(dirListing[fname]){tx.abort(function(){cb(ApiError.EEXIST(p))})}else{this$1.addNewNode(tx,data,function(e2,dataId){if(noErrorTx(e2,tx,cb)){var fileInode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);this$1.addNewNode(tx,fileInode.toBuffer(),function(e3,fileInodeId){if(noErrorTx(e3,tx,cb)){dirListing[fname]=fileInodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(function(e5){if(noErrorTx(e5,tx,cb)){cb(null,fileInode)}})}})}})}})}}})};AsyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),fileName=path.basename(p);this.findINodeAndDirListing(tx,parent,function(e,parentNode,parentListing){if(noErrorTx(e,tx,cb)){if(!parentListing[fileName]){tx.abort(function(){cb(ApiError.ENOENT(p))})}else{var fileNodeId=parentListing[fileName];delete parentListing[fileName];this$1.getINode(tx,p,fileNodeId,function(e2,fileNode){if(noErrorTx(e2,tx,cb)){if(!isDir&&fileNode.isDirectory()){tx.abort(function(){cb(ApiError.EISDIR(p))})}else if(isDir&&!fileNode.isDirectory()){tx.abort(function(){cb(ApiError.ENOTDIR(p))})}else{tx.del(fileNode.id,function(e3){if(noErrorTx(e3,tx,cb)){tx.del(fileNodeId,function(e4){if(noErrorTx(e4,tx,cb)){tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true,function(e5){if(noErrorTx(e5,tx,cb)){tx.commit(cb)}})}})}})}}})}}})};return AsyncKeyValueFileSystem2}(BaseFileSystem);var InMemoryStore=function InMemoryStore2(){this.store={}};InMemoryStore.prototype.name=function name(){return InMemoryFileSystem.Name};InMemoryStore.prototype.clear=function clear(){this.store={}};InMemoryStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};InMemoryStore.prototype.get=function get(key){return this.store[key]};InMemoryStore.prototype.put=function put(key,data,overwrite){if(!overwrite&&this.store.hasOwnProperty(key)){return false}this.store[key]=data;return true};InMemoryStore.prototype.del=function del(key){delete this.store[key]};var InMemoryFileSystem=function(SyncKeyValueFileSystem$$1){function InMemoryFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new InMemoryStore})}if(SyncKeyValueFileSystem$$1)InMemoryFileSystem2.__proto__=SyncKeyValueFileSystem$$1;InMemoryFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);InMemoryFileSystem2.prototype.constructor=InMemoryFileSystem2;InMemoryFileSystem2.Create=function Create(options,cb){cb(null,new InMemoryFileSystem2)};return InMemoryFileSystem2}(SyncKeyValueFileSystem);InMemoryFileSystem.Name="InMemory";InMemoryFileSystem.Options={};var indexedDB=global$1.indexedDB||global$1.mozIndexedDB||global$1.webkitIndexedDB||global$1.msIndexedDB;function convertError$2(e,message){if(message===void 0)message=e.toString();switch(e.name){case"NotFoundError":return new ApiError(ErrorCode.ENOENT,message);case"QuotaExceededError":return new ApiError(ErrorCode.ENOSPC,message);default:return new ApiError(ErrorCode.EIO,message)}}function onErrorHandler(cb,code,message){if(code===void 0)code=ErrorCode.EIO;if(message===void 0)message=null;return function(e){e.preventDefault();cb(new ApiError(code,message!==null?message:void 0))}}var IndexedDBROTransaction=function IndexedDBROTransaction2(tx,store){this.tx=tx;this.store=store};IndexedDBROTransaction.prototype.get=function get(key,cb){try{var r=this.store.get(key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){var result=event.target.result;if(result===void 0){cb(null,result)}else{cb(null,arrayBuffer2Buffer(result))}}}catch(e){cb(convertError$2(e))}};var IndexedDBRWTransaction=function(IndexedDBROTransaction2){function IndexedDBRWTransaction2(tx,store){IndexedDBROTransaction2.call(this,tx,store)}if(IndexedDBROTransaction2)IndexedDBRWTransaction2.__proto__=IndexedDBROTransaction2;IndexedDBRWTransaction2.prototype=Object.create(IndexedDBROTransaction2&&IndexedDBROTransaction2.prototype);IndexedDBRWTransaction2.prototype.constructor=IndexedDBRWTransaction2;IndexedDBRWTransaction2.prototype.put=function put(key,data,overwrite,cb){try{var arraybuffer=buffer2ArrayBuffer(data);var r;if(overwrite){r=this.store.put(arraybuffer,key)}else{r=this.store.add(arraybuffer,key)}r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb(null,true)}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.del=function del(key,cb){try{var r=this.store["delete"](key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb()}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.commit=function commit(cb){setTimeout(cb,0)};IndexedDBRWTransaction2.prototype.abort=function abort(cb){var _e=null;try{this.tx.abort()}catch(e){_e=convertError$2(e)}finally{cb(_e)}};return IndexedDBRWTransaction2}(IndexedDBROTransaction);var IndexedDBStore=function IndexedDBStore2(cb,storeName){var this$1=this;if(storeName===void 0)storeName="browserfs";this.storeName=storeName;var openReq=indexedDB.open(this.storeName,1);openReq.onupgradeneeded=function(event){var db=event.target.result;if(db.objectStoreNames.contains(this$1.storeName)){db.deleteObjectStore(this$1.storeName)}db.createObjectStore(this$1.storeName)};openReq.onsuccess=function(event){this$1.db=event.target.result;cb(null,this$1)};openReq.onerror=onErrorHandler(cb,ErrorCode.EACCES)};IndexedDBStore.prototype.name=function name(){return IndexedDBFileSystem.Name+" - "+this.storeName};IndexedDBStore.prototype.clear=function clear(cb){try{var tx=this.db.transaction(this.storeName,"readwrite"),objectStore=tx.objectStore(this.storeName),r=objectStore.clear();r.onsuccess=function(event){setTimeout(cb,0)};r.onerror=onErrorHandler(cb)}catch(e){cb(convertError$2(e))}};IndexedDBStore.prototype.beginTransaction=function beginTransaction(type){if(type===void 0)type="readonly";var tx=this.db.transaction(this.storeName,type),objectStore=tx.objectStore(this.storeName);if(type==="readwrite"){return new IndexedDBRWTransaction(tx,objectStore)}else if(type==="readonly"){return new IndexedDBROTransaction(tx,objectStore)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid transaction type.")}};var IndexedDBFileSystem=function(AsyncKeyValueFileSystem$$1){function IndexedDBFileSystem2(cb,storeName,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;AsyncKeyValueFileSystem$$1.call(this);this.store=new IndexedDBStore(function(e){if(e){cb(e)}else{this$1.init(this$1.store,function(e2){cb(e2,this$1)})}},storeName);deprecationMessage(deprecateMsg,IndexedDBFileSystem2.Name,{storeName})}if(AsyncKeyValueFileSystem$$1)IndexedDBFileSystem2.__proto__=AsyncKeyValueFileSystem$$1;IndexedDBFileSystem2.prototype=Object.create(AsyncKeyValueFileSystem$$1&&AsyncKeyValueFileSystem$$1.prototype);IndexedDBFileSystem2.prototype.constructor=IndexedDBFileSystem2;IndexedDBFileSystem2.Create=function Create(opts,cb){new IndexedDBFileSystem2(cb,opts.storeName,false)};IndexedDBFileSystem2.isAvailable=function isAvailable(){try{return typeof indexedDB!=="undefined"&&null!==indexedDB.open("__browserfs_test__")}catch(e){return false}};return IndexedDBFileSystem2}(AsyncKeyValueFileSystem);IndexedDBFileSystem.Name="IndexedDB";IndexedDBFileSystem.Options={storeName:{type:"string",optional:true,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var supportsBinaryString=false;var binaryEncoding;try{global$1.localStorage.setItem("__test__",String.fromCharCode(55296));supportsBinaryString=global$1.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(e){supportsBinaryString=false}binaryEncoding=supportsBinaryString?"binary_string":"binary_string_ie";if(!Buffer2.isEncoding(binaryEncoding)){binaryEncoding="base64"}var LocalStorageStore=function LocalStorageStore2(){};LocalStorageStore.prototype.name=function name(){return LocalStorageFileSystem.Name};LocalStorageStore.prototype.clear=function clear(){global$1.localStorage.clear()};LocalStorageStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};LocalStorageStore.prototype.get=function get(key){try{var data=global$1.localStorage.getItem(key);if(data!==null){return Buffer2.from(data,binaryEncoding)}}catch(e){}return void 0};LocalStorageStore.prototype.put=function put(key,data,overwrite){try{if(!overwrite&&global$1.localStorage.getItem(key)!==null){return false}global$1.localStorage.setItem(key,data.toString(binaryEncoding));return true}catch(e){throw new ApiError(ErrorCode.ENOSPC,"LocalStorage is full.")}};LocalStorageStore.prototype.del=function del(key){try{global$1.localStorage.removeItem(key)}catch(e){throw new ApiError(ErrorCode.EIO,"Unable to delete key "+key+": "+e)}};var LocalStorageFileSystem=function(SyncKeyValueFileSystem$$1){function LocalStorageFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new LocalStorageStore})}if(SyncKeyValueFileSystem$$1)LocalStorageFileSystem2.__proto__=SyncKeyValueFileSystem$$1;LocalStorageFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);LocalStorageFileSystem2.prototype.constructor=LocalStorageFileSystem2;LocalStorageFileSystem2.Create=function Create(options,cb){cb(null,new LocalStorageFileSystem2)};LocalStorageFileSystem2.isAvailable=function isAvailable(){return typeof global$1.localStorage!=="undefined"};return LocalStorageFileSystem2}(SyncKeyValueFileSystem);LocalStorageFileSystem.Name="LocalStorage";LocalStorageFileSystem.Options={};var MountableFileSystem=function(BaseFileSystem$$1){function MountableFileSystem2(){BaseFileSystem$$1.call(this);this.mountList=[];this.mntMap={};this.rootFs=new InMemoryFileSystem}if(BaseFileSystem$$1)MountableFileSystem2.__proto__=BaseFileSystem$$1;MountableFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);MountableFileSystem2.prototype.constructor=MountableFileSystem2;MountableFileSystem2.Create=function Create(opts,cb){var fs4=new MountableFileSystem2;Object.keys(opts).forEach(function(mountPoint){fs4.mount(mountPoint,opts[mountPoint])});cb(null,fs4)};MountableFileSystem2.isAvailable=function isAvailable(){return true};MountableFileSystem2.prototype.mount=function mount(mountPoint,fs4){if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already taken.")}mkdirpSync(mountPoint,511,this.rootFs);this.mntMap[mountPoint]=fs4;this.mountList.push(mountPoint);this.mountList=this.mountList.sort(function(a,b){return b.length-a.length})};MountableFileSystem2.prototype.umount=function umount(mountPoint){var this$1=this;if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(!this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already unmounted.")}delete this.mntMap[mountPoint];this.mountList.splice(this.mountList.indexOf(mountPoint),1);while(mountPoint!=="/"){if(this$1.rootFs.readdirSync(mountPoint).length===0){this$1.rootFs.rmdirSync(mountPoint);mountPoint=path.dirname(mountPoint)}else{break}}};MountableFileSystem2.prototype._getFs=function _getFs(path$$1){var this$1=this;var mountList=this.mountList,len=mountList.length;for(var i2=0;i21?mountPoint.length:0);if(path$$1===""){path$$1="/"}return{fs:this$1.mntMap[mountPoint],path:path$$1}}}return{fs:this.rootFs,path:path$$1}};MountableFileSystem2.prototype.getName=function getName(){return MountableFileSystem2.Name};MountableFileSystem2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};MountableFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};MountableFileSystem2.prototype.supportsLinks=function supportsLinks(){return false};MountableFileSystem2.prototype.supportsProps=function supportsProps(){return false};MountableFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};MountableFileSystem2.prototype.standardizeError=function standardizeError(err,path$$1,realPath){var index=err.message.indexOf(path$$1);if(index!==-1){err.message=err.message.substr(0,index)+realPath+err.message.substr(index+path$$1.length);err.path=realPath}return err};MountableFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){return fs1rv.fs.rename(fs1rv.path,fs2rv.path,function(e){if(e){this$1.standardizeError(this$1.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath)}cb(e)})}return _fsMock.readFile(oldPath,function(err,data){if(err){return cb(err)}_fsMock.writeFile(newPath,data,function(err2){if(err2){return cb(err2)}_fsMock.unlink(oldPath,cb)})})};MountableFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){try{return fs1rv.fs.renameSync(fs1rv.path,fs2rv.path)}catch(e){this.standardizeError(this.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath);throw e}}var data=_fsMock.readFileSync(oldPath);_fsMock.writeFileSync(newPath,data);return _fsMock.unlinkSync(oldPath)};MountableFileSystem2.prototype.readdirSync=function readdirSync(p){var fsInfo=this._getFs(p);var rv=null;if(fsInfo.fs!==this.rootFs){try{rv=this.rootFs.readdirSync(p)}catch(e){}}try{var rv2=fsInfo.fs.readdirSync(fsInfo.path);if(rv===null){return rv2}else{return rv2.concat(rv.filter(function(val){return rv2.indexOf(val)===-1}))}}catch(e){if(rv===null){throw this.standardizeError(e,fsInfo.path,p)}else{return rv}}};MountableFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);fsInfo.fs.readdir(fsInfo.path,function(err,files){if(fsInfo.fs!==this$1.rootFs){try{var rv=this$1.rootFs.readdirSync(p);if(files){files=files.concat(rv.filter(function(val){return files.indexOf(val)===-1}))}else{files=rv}}catch(e){if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}}}else if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}cb(null,files)})};MountableFileSystem2.prototype.rmdirSync=function rmdirSync(p){var fsInfo=this._getFs(p);if(this._containsMountPt(p)){throw ApiError.ENOTEMPTY(p)}else{try{fsInfo.fs.rmdirSync(fsInfo.path)}catch(e){throw this.standardizeError(e,fsInfo.path,p)}}};MountableFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);if(this._containsMountPt(p)){cb(ApiError.ENOTEMPTY(p))}else{fsInfo.fs.rmdir(fsInfo.path,function(err){cb(err?this$1.standardizeError(err,fsInfo.path,p):null)})}};MountableFileSystem2.prototype._containsMountPt=function _containsMountPt(p){var mountPoints=this.mountList,len=mountPoints.length;for(var i2=0;i2=p.length&&pt.slice(0,p.length)===p){return true}}return false};return MountableFileSystem2}(BaseFileSystem);MountableFileSystem.Name="MountableFileSystem";MountableFileSystem.Options={};function defineFcn(name,isSync,numArgs){if(isSync){return function(){var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;try{return rv.fs[name].apply(rv.fs,args)}catch(e){this.standardizeError(e,rv.path,path$$1);throw e}}}else{return function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;if(typeof args[args.length-1]==="function"){var cb=args[args.length-1];args[args.length-1]=function(){var args2=[],len2=arguments.length;while(len2--)args2[len2]=arguments[len2];if(args2.length>0&&args2[0]instanceof ApiError){this$1.standardizeError(args2[0],rv.path,path$$1)}cb.apply(null,args2)}}return rv.fs[name].apply(rv.fs,args)}}}var fsCmdMap=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]];for(var i=0;i0){var fn=timeouts.shift();return fn()}}};if(gScope.addEventListener){gScope.addEventListener("message",handleMessage,true)}else{gScope.attachEvent("onmessage",handleMessage)}}else if(gScope.MessageChannel){var channel=new gScope.MessageChannel;channel.port1.onmessage=function(event){if(timeouts.length>0){return timeouts.shift()()}};bfsSetImmediate=function(fn){timeouts.push(fn);channel.port2.postMessage("")}}else{bfsSetImmediate=function(fn){return setTimeout(fn,0)}}}var setImmediate$3=bfsSetImmediate;var Mutex=function Mutex2(){this._locked=false;this._waiters=[]};Mutex.prototype.lock=function lock(cb){if(this._locked){this._waiters.push(cb);return}this._locked=true;cb()};Mutex.prototype.unlock=function unlock(){if(!this._locked){throw new Error("unlock of a non-locked mutex")}var next=this._waiters.shift();if(next){setImmediate$3(next);return}this._locked=false};Mutex.prototype.tryLock=function tryLock(){if(this._locked){return false}this._locked=true;return true};Mutex.prototype.isLocked=function isLocked(){return this._locked};var LockedFS=function LockedFS2(fs4){this._fs=fs4;this._mu=new Mutex};LockedFS.prototype.getName=function getName(){return"LockedFS<"+this._fs.getName()+">"};LockedFS.prototype.getFSUnlocked=function getFSUnlocked(){return this._fs};LockedFS.prototype.initialize=function initialize3(cb){this._fs.initialize(cb)};LockedFS.prototype.diskSpace=function diskSpace(p,cb){this._fs.diskSpace(p,cb)};LockedFS.prototype.isReadOnly=function isReadOnly(){return this._fs.isReadOnly()};LockedFS.prototype.supportsLinks=function supportsLinks(){return this._fs.supportsLinks()};LockedFS.prototype.supportsProps=function supportsProps(){return this._fs.supportsProps()};LockedFS.prototype.supportsSynch=function supportsSynch(){return this._fs.supportsSynch()};LockedFS.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rename(oldPath,newPath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.renameSync=function renameSync(oldPath,newPath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.renameSync(oldPath,newPath)};LockedFS.prototype.stat=function stat(p,isLstat,cb){var this$1=this;this._mu.lock(function(){this$1._fs.stat(p,isLstat,function(err,stat2){this$1._mu.unlock();cb(err,stat2)})})};LockedFS.prototype.statSync=function statSync(p,isLstat){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.statSync(p,isLstat)};LockedFS.prototype.open=function open(p,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.open(p,flag,mode,function(err,fd){this$1._mu.unlock();cb(err,fd)})})};LockedFS.prototype.openSync=function openSync(p,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.openSync(p,flag,mode)};LockedFS.prototype.unlink=function unlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.unlink(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.unlinkSync=function unlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.unlinkSync(p)};LockedFS.prototype.rmdir=function rmdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rmdir(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.rmdirSync=function rmdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.rmdirSync(p)};LockedFS.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.mkdir(p,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.mkdirSync=function mkdirSync(p,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.mkdirSync(p,mode)};LockedFS.prototype.readdir=function readdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readdir(p,function(err,files){this$1._mu.unlock();cb(err,files)})})};LockedFS.prototype.readdirSync=function readdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readdirSync(p)};LockedFS.prototype.exists=function exists2(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.exists(p,function(exists3){this$1._mu.unlock();cb(exists3)})})};LockedFS.prototype.existsSync=function existsSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.existsSync(p)};LockedFS.prototype.realpath=function realpath(p,cache,cb){var this$1=this;this._mu.lock(function(){this$1._fs.realpath(p,cache,function(err,resolvedPath){this$1._mu.unlock();cb(err,resolvedPath)})})};LockedFS.prototype.realpathSync=function realpathSync(p,cache){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.realpathSync(p,cache)};LockedFS.prototype.truncate=function truncate(p,len,cb){var this$1=this;this._mu.lock(function(){this$1._fs.truncate(p,len,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.truncateSync=function truncateSync(p,len){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.truncateSync(p,len)};LockedFS.prototype.readFile=function readFile2(fname,encoding,flag,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readFile(fname,encoding,flag,function(err,data){this$1._mu.unlock();cb(err,data)})})};LockedFS.prototype.readFileSync=function readFileSync(fname,encoding,flag){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readFileSync(fname,encoding,flag)};LockedFS.prototype.writeFile=function writeFile2(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.writeFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.writeFileSync=function writeFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.writeFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.appendFile=function appendFile3(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.appendFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.appendFileSync=function appendFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.appendFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chmod(p,isLchmod,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chmodSync=function chmodSync(p,isLchmod,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chmodSync(p,isLchmod,mode)};LockedFS.prototype.chown=function chown(p,isLchown,uid,gid,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chown(p,isLchown,uid,gid,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chownSync=function chownSync(p,isLchown,uid,gid){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chownSync(p,isLchown,uid,gid)};LockedFS.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;this._mu.lock(function(){this$1._fs.utimes(p,atime,mtime,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.utimesSync=function utimesSync(p,atime,mtime){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.utimesSync(p,atime,mtime)};LockedFS.prototype.link=function link(srcpath,dstpath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.link(srcpath,dstpath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.linkSync=function linkSync(srcpath,dstpath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.linkSync(srcpath,dstpath)};LockedFS.prototype.symlink=function symlink(srcpath,dstpath,type,cb){var this$1=this;this._mu.lock(function(){this$1._fs.symlink(srcpath,dstpath,type,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.symlinkSync(srcpath,dstpath,type)};LockedFS.prototype.readlink=function readlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readlink(p,function(err,linkString){this$1._mu.unlock();cb(err,linkString)})})};LockedFS.prototype.readlinkSync=function readlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readlinkSync(p)};var deletionLogPath="/.deletedFiles.log";function makeModeWritable(mode){return 146|mode}function getFlag(f){return FileFlag.getFileFlag(f)}var OverlayFile=function(PreloadFile$$1){function OverlayFile2(fs4,path$$1,flag,stats,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stats,data)}if(PreloadFile$$1)OverlayFile2.__proto__=PreloadFile$$1;OverlayFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);OverlayFile2.prototype.constructor=OverlayFile2;OverlayFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){cb(null);return}this._fs._syncAsync(this,function(err){this$1.resetDirty();cb(err)})};OverlayFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};OverlayFile2.prototype.close=function close(cb){this.sync(cb)};OverlayFile2.prototype.closeSync=function closeSync(){this.syncSync()};return OverlayFile2}(PreloadFile);var UnlockedOverlayFS=function(BaseFileSystem$$1){function UnlockedOverlayFS2(writable,readable){BaseFileSystem$$1.call(this);this._isInitialized=false;this._initializeCallbacks=[];this._deletedFiles={};this._deleteLog="";this._deleteLogUpdatePending=false;this._deleteLogUpdateNeeded=false;this._deleteLogError=null;this._writable=writable;this._readable=readable;if(this._writable.isReadOnly()){throw new ApiError(ErrorCode.EINVAL,"Writable file system must be writable.")}}if(BaseFileSystem$$1)UnlockedOverlayFS2.__proto__=BaseFileSystem$$1;UnlockedOverlayFS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);UnlockedOverlayFS2.prototype.constructor=UnlockedOverlayFS2;UnlockedOverlayFS2.isAvailable=function isAvailable(){return true};UnlockedOverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return{readable:this._readable,writable:this._writable}};UnlockedOverlayFS2.prototype._syncAsync=function _syncAsync(file,cb){var this$1=this;this.createParentDirectoriesAsync(file.getPath(),function(err){if(err){return cb(err)}this$1._writable.writeFile(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode,cb)})};UnlockedOverlayFS2.prototype._syncSync=function _syncSync(file){this.createParentDirectories(file.getPath());this._writable.writeFileSync(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode)};UnlockedOverlayFS2.prototype.getName=function getName(){return OverlayFS.Name};UnlockedOverlayFS2.prototype.initialize=function initialize3(cb){var this$1=this;var callbackArray=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbackArray.forEach(function(cb2){return cb2(e)})};if(this._isInitialized){return cb()}callbackArray.push(cb);if(callbackArray.length!==1){return}this._writable.readFile(deletionLogPath,"utf8",getFlag("r"),function(err,data){if(err){if(err.errno!==ErrorCode.ENOENT){return end(err)}}else{this$1._deleteLog=data}this$1._reparseDeletionLog();end()})};UnlockedOverlayFS2.prototype.isReadOnly=function isReadOnly(){return false};UnlockedOverlayFS2.prototype.supportsSynch=function supportsSynch(){return this._readable.supportsSynch()&&this._writable.supportsSynch()};UnlockedOverlayFS2.prototype.supportsLinks=function supportsLinks(){return false};UnlockedOverlayFS2.prototype.supportsProps=function supportsProps(){return this._readable.supportsProps()&&this._writable.supportsProps()};UnlockedOverlayFS2.prototype.getDeletionLog=function getDeletionLog(){return this._deleteLog};UnlockedOverlayFS2.prototype.restoreDeletionLog=function restoreDeletionLog(log){this._deleteLog=log;this._reparseDeletionLog();this.updateLog("")};UnlockedOverlayFS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(oldPath,cb)||this.checkPathAsync(newPath,cb)){return}if(oldPath===deletionLogPath||newPath===deletionLogPath){return cb(ApiError.EPERM("Cannot rename deletion log."))}if(oldPath===newPath){return cb()}this.stat(oldPath,false,function(oldErr,oldStats){if(oldErr){return cb(oldErr)}return this$1.stat(newPath,false,function(newErr,newStats){var self2=this$1;function copyDirContents(files){var file=files.shift();if(!file){return cb()}var oldFile=path.resolve(oldPath,file);var newFile=path.resolve(newPath,file);self2.rename(oldFile,newFile,function(err){if(err){return cb(err)}copyDirContents(files)})}var mode=511;if(oldStats.isDirectory()){if(newErr){if(newErr.errno!==ErrorCode.ENOENT){return cb(newErr)}return this$1._writable.exists(oldPath,function(exists2){if(exists2){return this$1._writable.rename(oldPath,newPath,cb)}this$1._writable.mkdir(newPath,mode,function(mkdirErr){if(mkdirErr){return cb(mkdirErr)}this$1._readable.readdir(oldPath,function(err,files){if(err){return cb()}copyDirContents(files)})})})}mode=newStats.mode;if(!newStats.isDirectory()){return cb(ApiError.ENOTDIR(newPath))}this$1.readdir(newPath,function(readdirErr,files){if(files&&files.length){return cb(ApiError.ENOTEMPTY(newPath))}this$1._readable.readdir(oldPath,function(err,files2){if(err){return cb()}copyDirContents(files2)})})}if(newStats&&newStats.isDirectory()){return cb(ApiError.EISDIR(newPath))}this$1.readFile(oldPath,null,getFlag("r"),function(err,data){if(err){return cb(err)}return this$1.writeFile(newPath,data,null,getFlag("w"),oldStats.mode,function(err2){if(err2){return cb(err2)}return this$1.unlink(oldPath,cb)})})})})};UnlockedOverlayFS2.prototype.renameSync=function renameSync(oldPath,newPath){var this$1=this;this.checkInitialized();this.checkPath(oldPath);this.checkPath(newPath);if(oldPath===deletionLogPath||newPath===deletionLogPath){throw ApiError.EPERM("Cannot rename deletion log.")}var oldStats=this.statSync(oldPath,false);if(oldStats.isDirectory()){if(oldPath===newPath){return}var mode=511;if(this.existsSync(newPath)){var stats=this.statSync(newPath,false);mode=stats.mode;if(stats.isDirectory()){if(this.readdirSync(newPath).length>0){throw ApiError.ENOTEMPTY(newPath)}}else{throw ApiError.ENOTDIR(newPath)}}if(this._writable.existsSync(oldPath)){this._writable.renameSync(oldPath,newPath)}else if(!this._writable.existsSync(newPath)){this._writable.mkdirSync(newPath,mode)}if(this._readable.existsSync(oldPath)){this._readable.readdirSync(oldPath).forEach(function(name){this$1.renameSync(path.resolve(oldPath,name),path.resolve(newPath,name))})}}else{if(this.existsSync(newPath)&&this.statSync(newPath,false).isDirectory()){throw ApiError.EISDIR(newPath)}this.writeFileSync(newPath,this.readFileSync(oldPath,null,getFlag("r")),null,getFlag("w"),oldStats.mode)}if(oldPath!==newPath&&this.existsSync(oldPath)){this.unlinkSync(oldPath)}};UnlockedOverlayFS2.prototype.stat=function stat(p,isLstat,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this._writable.stat(p,isLstat,function(err,stat2){if(err&&err.errno===ErrorCode.ENOENT){if(this$1._deletedFiles[p]){cb(ApiError.ENOENT(p))}this$1._readable.stat(p,isLstat,function(err2,stat3){if(stat3){stat3=stat3.clone();stat3.mode=makeModeWritable(stat3.mode)}cb(err2,stat3)})}else{cb(err,stat2)}})};UnlockedOverlayFS2.prototype.statSync=function statSync(p,isLstat){this.checkInitialized();try{return this._writable.statSync(p,isLstat)}catch(e){if(this._deletedFiles[p]){throw ApiError.ENOENT(p)}var oldStat=this._readable.statSync(p,isLstat).clone();oldStat.mode=makeModeWritable(oldStat.mode);return oldStat}};UnlockedOverlayFS2.prototype.open=function open(p,flag,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.stat(p,false,function(err,stats){if(stats){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}this$1._writable.open(p,flag,mode,cb)});case ActionType.NOP:return this$1._writable.exists(p,function(exists2){if(exists2){this$1._writable.open(p,flag,mode,cb)}else{stats=stats.clone();stats.mode=mode;this$1._readable.readFile(p,null,getFlag("r"),function(readFileErr,data){if(readFileErr){return cb(readFileErr)}if(stats.size===-1){stats.size=data.length}var f=new OverlayFile(this$1,p,flag,stats,data);cb(null,f)})}});default:return cb(ApiError.EEXIST(p))}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}return this$1._writable.open(p,flag,mode,cb)});default:return cb(ApiError.ENOENT(p))}}})};UnlockedOverlayFS2.prototype.openSync=function openSync(p,flag,mode){this.checkInitialized();this.checkPath(p);if(p===deletionLogPath){throw ApiError.EPERM("Cannot open deletion log.")}if(this.existsSync(p)){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);case ActionType.NOP:if(this._writable.existsSync(p)){return this._writable.openSync(p,flag,mode)}else{var buf=this._readable.readFileSync(p,null,getFlag("r"));var stats=this._readable.statSync(p,false).clone();stats.mode=mode;return new OverlayFile(this,p,flag,stats,buf)}default:throw ApiError.EEXIST(p)}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);default:throw ApiError.ENOENT(p)}}};UnlockedOverlayFS2.prototype.unlink=function unlink(p,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){return this$1._writable.unlink(p,function(err){if(err){return cb(err)}this$1.exists(p,function(readableExists){if(readableExists){this$1.deletePath(p)}cb(null)})})}else{this$1.deletePath(p);cb(null)}})})};UnlockedOverlayFS2.prototype.unlinkSync=function unlinkSync(p){this.checkInitialized();this.checkPath(p);if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.unlinkSync(p)}if(this.existsSync(p)){this.deletePath(p)}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.rmdir=function rmdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}var rmdirLower=function(){this$1.readdir(p,function(err,files){if(err){return cb(err)}if(files.length){return cb(ApiError.ENOTEMPTY(p))}this$1.deletePath(p);cb(null)})};this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){this$1._writable.rmdir(p,function(err){if(err){return cb(err)}this$1._readable.exists(p,function(readableExists){if(readableExists){rmdirLower()}else{cb()}})})}else{rmdirLower()}})})};UnlockedOverlayFS2.prototype.rmdirSync=function rmdirSync(p){this.checkInitialized();if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.rmdirSync(p)}if(this.existsSync(p)){if(this.readdirSync(p).length>0){throw ApiError.ENOTEMPTY(p)}else{this.deletePath(p)}}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.exists(p,function(exists2){if(exists2){return cb(ApiError.EEXIST(p))}this$1.createParentDirectoriesAsync(p,function(err){if(err){return cb(err)}this$1._writable.mkdir(p,mode,cb)})})};UnlockedOverlayFS2.prototype.mkdirSync=function mkdirSync(p,mode){this.checkInitialized();if(this.existsSync(p)){throw ApiError.EEXIST(p)}else{this.createParentDirectories(p);this._writable.mkdirSync(p,mode)}};UnlockedOverlayFS2.prototype.readdir=function readdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.stat(p,false,function(err,dirStats){if(err){return cb(err)}if(!dirStats.isDirectory()){return cb(ApiError.ENOTDIR(p))}this$1._writable.readdir(p,function(err2,wFiles){if(err2&&err2.code!=="ENOENT"){return cb(err2)}else if(err2||!wFiles){wFiles=[]}this$1._readable.readdir(p,function(err3,rFiles){if(err3||!rFiles){rFiles=[]}var seenMap={};var filtered=wFiles.concat(rFiles.filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]})).filter(function(fPath){var result=!seenMap[fPath];seenMap[fPath]=true;return result});cb(null,filtered)})})})};UnlockedOverlayFS2.prototype.readdirSync=function readdirSync(p){var this$1=this;this.checkInitialized();var dirStats=this.statSync(p,false);if(!dirStats.isDirectory()){throw ApiError.ENOTDIR(p)}var contents=[];try{contents=contents.concat(this._writable.readdirSync(p))}catch(e){}try{contents=contents.concat(this._readable.readdirSync(p).filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]}))}catch(e){}var seenMap={};return contents.filter(function(fileP){var result=!seenMap[fileP];seenMap[fileP]=true;return result})};UnlockedOverlayFS2.prototype.exists=function exists2(p,cb){var this$1=this;this.checkInitialized();this._writable.exists(p,function(existsWritable){if(existsWritable){return cb(true)}this$1._readable.exists(p,function(existsReadable){cb(existsReadable&&this$1._deletedFiles[p]!==true)})})};UnlockedOverlayFS2.prototype.existsSync=function existsSync(p){this.checkInitialized();return this._writable.existsSync(p)||this._readable.existsSync(p)&&this._deletedFiles[p]!==true};UnlockedOverlayFS2.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chmod(p,isLchmod,mode,cb)}})};UnlockedOverlayFS2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chmodSync(p,isLchmod,mode)})};UnlockedOverlayFS2.prototype.chown=function chown(p,isLchmod,uid,gid,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chown(p,isLchmod,uid,gid,cb)}})};UnlockedOverlayFS2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chownSync(p,isLchown,uid,gid)})};UnlockedOverlayFS2.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.utimes(p,atime,mtime,cb)}})};UnlockedOverlayFS2.prototype.utimesSync=function utimesSync(p,atime,mtime){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.utimesSync(p,atime,mtime)})};UnlockedOverlayFS2.prototype.deletePath=function deletePath(p){this._deletedFiles[p]=true;this.updateLog("d"+p+"\n")};UnlockedOverlayFS2.prototype.updateLog=function updateLog(addition){var this$1=this;this._deleteLog+=addition;if(this._deleteLogUpdatePending){this._deleteLogUpdateNeeded=true}else{this._deleteLogUpdatePending=true;this._writable.writeFile(deletionLogPath,this._deleteLog,"utf8",FileFlag.getFileFlag("w"),420,function(e){this$1._deleteLogUpdatePending=false;if(e){this$1._deleteLogError=e}else if(this$1._deleteLogUpdateNeeded){this$1._deleteLogUpdateNeeded=false;this$1.updateLog("")}})}};UnlockedOverlayFS2.prototype._reparseDeletionLog=function _reparseDeletionLog(){var this$1=this;this._deletedFiles={};this._deleteLog.split("\n").forEach(function(path$$1){this$1._deletedFiles[path$$1.slice(1)]=path$$1.slice(0,1)==="d"})};UnlockedOverlayFS2.prototype.checkInitialized=function checkInitialized(){if(!this._isInitialized){throw new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;throw e}};UnlockedOverlayFS2.prototype.checkInitAsync=function checkInitAsync(cb){if(!this._isInitialized){cb(new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it."));return false}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;cb(e);return false}return true};UnlockedOverlayFS2.prototype.checkPath=function checkPath(p){if(p===deletionLogPath){throw ApiError.EPERM(p)}};UnlockedOverlayFS2.prototype.checkPathAsync=function checkPathAsync(p,cb){if(p===deletionLogPath){cb(ApiError.EPERM(p));return true}return false};UnlockedOverlayFS2.prototype.createParentDirectoriesAsync=function createParentDirectoriesAsync(p,cb){var parent=path.dirname(p);var toCreate=[];var self2=this;this._writable.stat(parent,false,statDone);function statDone(err,stat){if(err){toCreate.push(parent);parent=path.dirname(parent);self2._writable.stat(parent,false,statDone)}else{createParents()}}function createParents(){if(!toCreate.length){return cb()}var dir=toCreate.pop();self2._readable.stat(dir,false,function(err,stats){if(!stats){return cb()}self2._writable.mkdir(dir,stats.mode,function(err2){if(err2){return cb(err2)}createParents()})})}};UnlockedOverlayFS2.prototype.createParentDirectories=function createParentDirectories(p){var this$1=this;var parent=path.dirname(p),toCreate=[];while(!this._writable.existsSync(parent)){toCreate.push(parent);parent=path.dirname(parent)}toCreate=toCreate.reverse();toCreate.forEach(function(p2){this$1._writable.mkdirSync(p2,this$1.statSync(p2,false).mode)})};UnlockedOverlayFS2.prototype.operateOnWritable=function operateOnWritable(p,f){if(this.existsSync(p)){if(!this._writable.existsSync(p)){this.copyToWritable(p)}f()}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.operateOnWritableAsync=function operateOnWritableAsync(p,cb){var this$1=this;this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(existsWritable){if(existsWritable){cb()}else{return this$1.copyToWritableAsync(p,cb)}})})};UnlockedOverlayFS2.prototype.copyToWritable=function copyToWritable(p){var pStats=this.statSync(p,false);if(pStats.isDirectory()){this._writable.mkdirSync(p,pStats.mode)}else{this.writeFileSync(p,this._readable.readFileSync(p,null,getFlag("r")),null,getFlag("w"),this.statSync(p,false).mode)}};UnlockedOverlayFS2.prototype.copyToWritableAsync=function copyToWritableAsync(p,cb){var this$1=this;this.stat(p,false,function(err,pStats){if(err){return cb(err)}if(pStats.isDirectory()){return this$1._writable.mkdir(p,pStats.mode,cb)}this$1._readable.readFile(p,null,getFlag("r"),function(err2,data){if(err2){return cb(err2)}this$1.writeFile(p,data,null,getFlag("w"),pStats.mode,cb)})})};return UnlockedOverlayFS2}(BaseFileSystem);var OverlayFS=function(LockedFS$$1){function OverlayFS2(writable,readable,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;LockedFS$$1.call(this,new UnlockedOverlayFS(writable,readable));deprecationMessage(deprecateMsg,OverlayFS2.Name,{readable:"readable file system",writable:"writable file system"})}if(LockedFS$$1)OverlayFS2.__proto__=LockedFS$$1;OverlayFS2.prototype=Object.create(LockedFS$$1&&LockedFS$$1.prototype);OverlayFS2.prototype.constructor=OverlayFS2;OverlayFS2.Create=function Create(opts,cb){try{var fs4=new OverlayFS2(opts.writable,opts.readable,false);fs4.initialize(function(e){cb(e,fs4)},false)}catch(e){cb(e)}};OverlayFS2.isAvailable=function isAvailable(){return UnlockedOverlayFS.isAvailable()};OverlayFS2.prototype.initialize=function initialize3(cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.")}LockedFS$$1.prototype.initialize.call(this,cb)};OverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return LockedFS$$1.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()};OverlayFS2.prototype.unwrap=function unwrap(){return LockedFS$$1.prototype.getFSUnlocked.call(this)};return OverlayFS2}(LockedFS);OverlayFS.Name="OverlayFS";OverlayFS.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var SpecialArgType;(function(SpecialArgType2){SpecialArgType2[SpecialArgType2["CB"]=0]="CB";SpecialArgType2[SpecialArgType2["FD"]=1]="FD";SpecialArgType2[SpecialArgType2["API_ERROR"]=2]="API_ERROR";SpecialArgType2[SpecialArgType2["STATS"]=3]="STATS";SpecialArgType2[SpecialArgType2["PROBE"]=4]="PROBE";SpecialArgType2[SpecialArgType2["FILEFLAG"]=5]="FILEFLAG";SpecialArgType2[SpecialArgType2["BUFFER"]=6]="BUFFER";SpecialArgType2[SpecialArgType2["ERROR"]=7]="ERROR"})(SpecialArgType||(SpecialArgType={}));var CallbackArgumentConverter=function CallbackArgumentConverter2(){this._callbacks={};this._nextId=0};CallbackArgumentConverter.prototype.toRemoteArg=function toRemoteArg(cb){var id=this._nextId++;this._callbacks[id]=cb;return{type:SpecialArgType.CB,id}};CallbackArgumentConverter.prototype.toLocalArg=function toLocalArg(id){var cb=this._callbacks[id];delete this._callbacks[id];return cb};var FileDescriptorArgumentConverter=function FileDescriptorArgumentConverter2(){this._fileDescriptors={};this._nextId=0};FileDescriptorArgumentConverter.prototype.toRemoteArg=function toRemoteArg(fd,p,flag,cb){var id=this._nextId++;var data;var stat;this._fileDescriptors[id]=fd;fd.stat(function(err,stats){if(err){cb(err)}else{stat=bufferToTransferrableObject(stats.toBuffer());if(flag.isReadable()){fd.read(Buffer2.alloc(stats.size),0,stats.size,0,function(err2,bytesRead,buff){if(err2){cb(err2)}else{data=bufferToTransferrableObject(buff);cb(null,{type:SpecialArgType.FD,id,data,stat,path:p,flag:flag.getFlagString()})}})}else{cb(null,{type:SpecialArgType.FD,id,data:new ArrayBuffer(0),stat,path:p,flag:flag.getFlagString()})}}})};FileDescriptorArgumentConverter.prototype.applyFdAPIRequest=function applyFdAPIRequest(request,cb){var this$1=this;var fdArg=request.args[0];this._applyFdChanges(fdArg,function(err,fd){if(err){cb(err)}else{fd[request.method](function(e){if(request.method==="close"){delete this$1._fileDescriptors[fdArg.id]}cb(e)})}})};FileDescriptorArgumentConverter.prototype._applyFdChanges=function _applyFdChanges(remoteFd,cb){var fd=this._fileDescriptors[remoteFd.id],data=transferrableObjectToBuffer(remoteFd.data),remoteStats=Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));var flag=FileFlag.getFileFlag(remoteFd.flag);if(flag.isWriteable()){fd.write(data,0,data.length,flag.isAppendable()?fd.getPos():0,function(e){function applyStatChanges(){fd.stat(function(e2,stats){if(e2){cb(e2)}else{if(stats.mode!==remoteStats.mode){fd.chmod(remoteStats.mode,function(e3){cb(e3,fd)})}else{cb(e2,fd)}}})}if(e){cb(e)}else{if(!flag.isAppendable()){fd.truncate(data.length,function(){applyStatChanges()})}else{applyStatChanges()}}})}else{cb(null,fd)}};function apiErrorLocal2Remote(e){return{type:SpecialArgType.API_ERROR,errorData:bufferToTransferrableObject(e.writeToBuffer())}}function apiErrorRemote2Local(e){return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData))}function errorLocal2Remote(e){return{type:SpecialArgType.ERROR,name:e.name,message:e.message,stack:e.stack}}function errorRemote2Local(e){var cnstr=global$1[e.name];if(typeof cnstr!=="function"){cnstr=Error}var err=new cnstr(e.message);err.stack=e.stack;return err}function statsLocal2Remote(stats){return{type:SpecialArgType.STATS,statsData:bufferToTransferrableObject(stats.toBuffer())}}function statsRemote2Local(stats){return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData))}function fileFlagLocal2Remote(flag){return{type:SpecialArgType.FILEFLAG,flagStr:flag.getFlagString()}}function fileFlagRemote2Local(remoteFlag){return FileFlag.getFileFlag(remoteFlag.flagStr)}function bufferToTransferrableObject(buff){return buffer2ArrayBuffer(buff)}function transferrableObjectToBuffer(buff){return arrayBuffer2Buffer(buff)}function bufferLocal2Remote(buff){return{type:SpecialArgType.BUFFER,data:bufferToTransferrableObject(buff)}}function bufferRemote2Local(buffArg){return transferrableObjectToBuffer(buffArg.data)}function isAPIRequest(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}function isAPIResponse(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}var WorkerFile=function(PreloadFile$$1){function WorkerFile2(_fs,_path,_flag,_stat,remoteFdId,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents);this._remoteFdId=remoteFdId}if(PreloadFile$$1)WorkerFile2.__proto__=PreloadFile$$1;WorkerFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);WorkerFile2.prototype.constructor=WorkerFile2;WorkerFile2.prototype.getRemoteFdId=function getRemoteFdId(){return this._remoteFdId};WorkerFile2.prototype.toRemoteArg=function toRemoteArg(){return{type:SpecialArgType.FD,id:this._remoteFdId,data:bufferToTransferrableObject(this.getBuffer()),stat:bufferToTransferrableObject(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}};WorkerFile2.prototype.sync=function sync(cb){this._syncClose("sync",cb)};WorkerFile2.prototype.close=function close(cb){this._syncClose("close",cb)};WorkerFile2.prototype._syncClose=function _syncClose(type,cb){var this$1=this;if(this.isDirty()){this._fs.syncClose(type,this,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};return WorkerFile2}(PreloadFile);var WorkerFS=function(BaseFileSystem$$1){function WorkerFS2(worker,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._callbackConverter=new CallbackArgumentConverter;this._isInitialized=false;this._isReadOnly=false;this._supportLinks=false;this._supportProps=false;this._worker=worker;deprecationMessage(deprecateMsg,WorkerFS2.Name,{worker:"Web Worker instance"});this._worker.addEventListener("message",function(e){var resp=e.data;if(isAPIResponse(resp)){var i2;var args=resp.args;var fixedArgs=new Array(args.length);for(i2=0;i20){countdown=-1;message={browserfsMessage:true,cbId,args:[apiErrorLocal2Remote(err)]};worker.postMessage(message)}}for(i2=0;i20){var inode=void 0;var next=queue.pop();var pwd=next[0];var tree=next[1];var parent=next[2];for(var node in tree){if(tree.hasOwnProperty(node)){var children=tree[node];var name=pwd+"/"+node;if(children){idx._index[name]=inode=new DirInode;queue.push([name,children,inode])}else{inode=new FileInode(new Stats(FileType.FILE,-1,365))}if(parent){parent._ls[node]=inode}}}}return idx};FileIndex.prototype.fileIterator=function fileIterator(cb){var this$1=this;for(var path$$1 in this$1._index){if(this$1._index.hasOwnProperty(path$$1)){var dir=this$1._index[path$$1];var files=dir.getListing();for(var i2=0,list2=files;i20&&prefixUrl.charAt(prefixUrl.length-1)!=="/"){prefixUrl=prefixUrl+"/"}this.prefixUrl=prefixUrl;var listing=null;if(typeof listingUrlOrObj==="string"){listing=this._requestFileSync(listingUrlOrObj,"json");if(!listing){throw new Error("Unable to find listing at URL: ${listingUrlOrObj}")}}else{listing=listingUrlOrObj}deprecationMessage(deprecateMsg,XmlHttpRequest2.Name,{index:typeof listingUrlOrObj==="string"?listingUrlOrObj:"file index as an object",baseUrl:prefixUrl});this._index=FileIndex.fromListing(listing)}if(BaseFileSystem$$1)XmlHttpRequest2.__proto__=BaseFileSystem$$1;XmlHttpRequest2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);XmlHttpRequest2.prototype.constructor=XmlHttpRequest2;XmlHttpRequest2.Create=function Create(opts,cb){if(opts.index===void 0){opts.index="index.json"}if(typeof opts.index==="string"){XmlHttpRequest2.FromURL(opts.index,cb,opts.baseUrl,false)}else{cb(null,new XmlHttpRequest2(opts.index,opts.baseUrl,false))}};XmlHttpRequest2.isAvailable=function isAvailable(){return typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest!==null};XmlHttpRequest2.FromURL=function FromURL(url,cb,baseUrl,deprecateMsg){if(baseUrl===void 0)baseUrl=url.slice(0,url.lastIndexOf("/")+1);if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn(`[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: "`+url+'", baseUrl: "'+baseUrl+`" }, cb)' instead.`)}asyncDownloadFile(url,"json",function(e,data){if(e){cb(e)}else{cb(null,new XmlHttpRequest2(data,baseUrl,false))}})};XmlHttpRequest2.prototype.empty=function empty(){this._index.fileIterator(function(file){file.fileData=null})};XmlHttpRequest2.prototype.getName=function getName(){return XmlHttpRequest2.Name};XmlHttpRequest2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};XmlHttpRequest2.prototype.isReadOnly=function isReadOnly(){return true};XmlHttpRequest2.prototype.supportsLinks=function supportsLinks(){return false};XmlHttpRequest2.prototype.supportsProps=function supportsProps(){return false};XmlHttpRequest2.prototype.supportsSynch=function supportsSynch(){return true};XmlHttpRequest2.prototype.preloadFile=function preloadFile(path$$1,buffer$$1){var inode=this._index.getInode(path$$1);if(isFileInode(inode)){if(inode===null){throw ApiError.ENOENT(path$$1)}var stats=inode.getData();stats.size=buffer$$1.length;stats.fileData=buffer$$1}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.stat=function stat(path$$1,isLstat,cb){var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){this._requestFileSizeAsync(path$$1,function(e,size){if(e){return cb(e)}stats.size=size;cb(null,stats.clone())})}else{cb(null,stats.clone())}}else if(isDirInode(inode)){stats=inode.getStats();cb(null,stats)}else{cb(ApiError.FileError(ErrorCode.EINVAL,path$$1))}};XmlHttpRequest2.prototype.statSync=function statSync(path$$1,isLstat){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){stats.size=this._requestFileSizeSync(path$$1)}}else if(isDirInode(inode)){stats=inode.getStats()}else{throw ApiError.FileError(ErrorCode.EINVAL,path$$1)}return stats};XmlHttpRequest2.prototype.open=function open(path$$1,flags,mode,cb){if(flags.isWriteable()){return cb(new ApiError(ErrorCode.EPERM,path$$1))}var self2=this;var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:return cb(ApiError.EEXIST(path$$1));case ActionType.NOP:if(stats.fileData){return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),stats.fileData))}this._requestFileAsync(path$$1,"buffer",function(err,buffer$$1){if(err){return cb(err)}stats.size=buffer$$1.length;stats.fileData=buffer$$1;return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),buffer$$1))});break;default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileMode object."))}}else{return cb(ApiError.EISDIR(path$$1))}};XmlHttpRequest2.prototype.openSync=function openSync(path$$1,flags,mode){if(flags.isWriteable()){throw new ApiError(ErrorCode.EPERM,path$$1)}var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:throw ApiError.EEXIST(path$$1);case ActionType.NOP:if(stats.fileData){return new NoSyncFile(this,path$$1,flags,stats.clone(),stats.fileData)}var buffer$$1=this._requestFileSync(path$$1,"buffer");stats.size=buffer$$1.length;stats.fileData=buffer$$1;return new NoSyncFile(this,path$$1,flags,stats.clone(),buffer$$1);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileMode object.")}}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.readdir=function readdir(path$$1,cb){try{cb(null,this.readdirSync(path$$1))}catch(e){cb(e)}};XmlHttpRequest2.prototype.readdirSync=function readdirSync(path$$1){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}else if(isDirInode(inode)){return inode.getListing()}else{throw ApiError.ENOTDIR(path$$1)}};XmlHttpRequest2.prototype.readFile=function readFile2(fname,encoding,flag,cb){var oldCb=cb;this.open(fname,flag,420,function(err,fd){if(err){return cb(err)}cb=function(err2,arg){fd.close(function(err22){if(!err2){err2=err22}return oldCb(err2,arg)})};var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){cb(err,copyingSlice(fdBuff))}else{tryToString(fdBuff,encoding,cb)}})};XmlHttpRequest2.prototype.readFileSync=function readFileSync(fname,encoding,flag){var fd=this.openSync(fname,flag,420);try{var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){return copyingSlice(fdBuff)}return fdBuff.toString(encoding)}finally{fd.closeSync()}};XmlHttpRequest2.prototype.getXhrPath=function getXhrPath(filePath){if(filePath.charAt(0)==="/"){filePath=filePath.slice(1)}return this.prefixUrl+filePath};XmlHttpRequest2.prototype._requestFileAsync=function _requestFileAsync(p,type,cb){asyncDownloadFile(this.getXhrPath(p),type,cb)};XmlHttpRequest2.prototype._requestFileSync=function _requestFileSync(p,type){return syncDownloadFile(this.getXhrPath(p),type)};XmlHttpRequest2.prototype._requestFileSizeAsync=function _requestFileSizeAsync(path$$1,cb){getFileSizeAsync(this.getXhrPath(path$$1),cb)};XmlHttpRequest2.prototype._requestFileSizeSync=function _requestFileSizeSync(path$$1){return getFileSizeSync(this.getXhrPath(path$$1))};return XmlHttpRequest2}(BaseFileSystem);XmlHttpRequest.Name="XmlHttpRequest";XmlHttpRequest.Options={index:{type:["string","object"],optional:true,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:true,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."}};var ExtendedASCII=function ExtendedASCII2(){};ExtendedASCII.str2byte=function str2byte(str,buf){var length=str.length>buf.length?buf.length:str.length;for(var i2=0;i2127){var charIdx=ExtendedASCII.extendedChars.indexOf(str.charAt(i2));if(charIdx>-1){charCode=charIdx+128}}buf[charCode]=i2}return length};ExtendedASCII.byte2str=function byte2str(buff){var chars=new Array(buff.length);for(var i2=0;i2127){chars[i2]=ExtendedASCII.extendedChars[charCode-128]}else{chars[i2]=String.fromCharCode(charCode)}}return chars.join("")};ExtendedASCII.byteLength=function byteLength(str){return str.length};ExtendedASCII.extendedChars=["\xC7","\xFC","\xE9","\xE2","\xE4","\xE0","\xE5","\xE7","\xEA","\xEB","\xE8","\xEF","\xEE","\xEC","\xC4","\xC5","\xC9","\xE6","\xC6","\xF4","\xF6","\xF2","\xFB","\xF9","\xFF","\xD6","\xDC","\xF8","\xA3","\xD8","\xD7","\u0192","\xE1","\xED","\xF3","\xFA","\xF1","\xD1","\xAA","\xBA","\xBF","\xAE","\xAC","\xBD","\xBC","\xA1","\xAB","\xBB","_","_","_","\xA6","\xA6","\xC1","\xC2","\xC0","\xA9","\xA6","\xA6","+","+","\xA2","\xA5","+","+","-","-","+","-","+","\xE3","\xC3","+","+","-","-","\xA6","-","+","\xA4","\xF0","\xD0","\xCA","\xCB","\xC8","i","\xCD","\xCE","\xCF","+","+","_","_","\xA6","\xCC","_","\xD3","\xDF","\xD4","\xD2","\xF5","\xD5","\xB5","\xFE","\xDE","\xDA","\xDB","\xD9","\xFD","\xDD","\xAF","\xB4","\xAD","\xB1","_","\xBE","\xB6","\xA7","\xF7","\xB8","\xB0","\xA8","\xB7","\xB9","\xB3","\xB2","_"," "];var inflateRaw=__webpack_require__(31).inflateRaw;var decompressionMethods={};var ExternalFileAttributeType;(function(ExternalFileAttributeType2){ExternalFileAttributeType2[ExternalFileAttributeType2["MSDOS"]=0]="MSDOS";ExternalFileAttributeType2[ExternalFileAttributeType2["AMIGA"]=1]="AMIGA";ExternalFileAttributeType2[ExternalFileAttributeType2["OPENVMS"]=2]="OPENVMS";ExternalFileAttributeType2[ExternalFileAttributeType2["UNIX"]=3]="UNIX";ExternalFileAttributeType2[ExternalFileAttributeType2["VM_CMS"]=4]="VM_CMS";ExternalFileAttributeType2[ExternalFileAttributeType2["ATARI_ST"]=5]="ATARI_ST";ExternalFileAttributeType2[ExternalFileAttributeType2["OS2_HPFS"]=6]="OS2_HPFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MAC"]=7]="MAC";ExternalFileAttributeType2[ExternalFileAttributeType2["Z_SYSTEM"]=8]="Z_SYSTEM";ExternalFileAttributeType2[ExternalFileAttributeType2["CP_M"]=9]="CP_M";ExternalFileAttributeType2[ExternalFileAttributeType2["NTFS"]=10]="NTFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MVS"]=11]="MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["VSE"]=12]="VSE";ExternalFileAttributeType2[ExternalFileAttributeType2["ACORN_RISC"]=13]="ACORN_RISC";ExternalFileAttributeType2[ExternalFileAttributeType2["VFAT"]=14]="VFAT";ExternalFileAttributeType2[ExternalFileAttributeType2["ALT_MVS"]=15]="ALT_MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["BEOS"]=16]="BEOS";ExternalFileAttributeType2[ExternalFileAttributeType2["TANDEM"]=17]="TANDEM";ExternalFileAttributeType2[ExternalFileAttributeType2["OS_400"]=18]="OS_400";ExternalFileAttributeType2[ExternalFileAttributeType2["OSX"]=19]="OSX"})(ExternalFileAttributeType||(ExternalFileAttributeType={}));var CompressionMethod;(function(CompressionMethod2){CompressionMethod2[CompressionMethod2["STORED"]=0]="STORED";CompressionMethod2[CompressionMethod2["SHRUNK"]=1]="SHRUNK";CompressionMethod2[CompressionMethod2["REDUCED_1"]=2]="REDUCED_1";CompressionMethod2[CompressionMethod2["REDUCED_2"]=3]="REDUCED_2";CompressionMethod2[CompressionMethod2["REDUCED_3"]=4]="REDUCED_3";CompressionMethod2[CompressionMethod2["REDUCED_4"]=5]="REDUCED_4";CompressionMethod2[CompressionMethod2["IMPLODE"]=6]="IMPLODE";CompressionMethod2[CompressionMethod2["DEFLATE"]=8]="DEFLATE";CompressionMethod2[CompressionMethod2["DEFLATE64"]=9]="DEFLATE64";CompressionMethod2[CompressionMethod2["TERSE_OLD"]=10]="TERSE_OLD";CompressionMethod2[CompressionMethod2["BZIP2"]=12]="BZIP2";CompressionMethod2[CompressionMethod2["LZMA"]=14]="LZMA";CompressionMethod2[CompressionMethod2["TERSE_NEW"]=18]="TERSE_NEW";CompressionMethod2[CompressionMethod2["LZ77"]=19]="LZ77";CompressionMethod2[CompressionMethod2["WAVPACK"]=97]="WAVPACK";CompressionMethod2[CompressionMethod2["PPMD"]=98]="PPMD"})(CompressionMethod||(CompressionMethod={}));function msdos2date(time,date){var day=date&31;var month=(date>>5&15)-1;var year=(date>>9)+1980;var second=time&31;var minute=time>>5&63;var hour=time>>11;return new Date(year,month,day,hour,minute,second)}function safeToString(buff,useUTF8,start,length){if(length===0){return""}else if(useUTF8){return buff.toString("utf8",start,start+length)}else{return ExtendedASCII.byte2str(buff.slice(start,start+length))}}var FileHeader=function FileHeader2(data){this.data=data;if(data.readUInt32LE(0)!==67324752){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))}};FileHeader.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(4)};FileHeader.prototype.flags=function flags(){return this.data.readUInt16LE(6)};FileHeader.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(8)};FileHeader.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(10),this.data.readUInt16LE(12))};FileHeader.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(10)};FileHeader.prototype.crc32=function crc32(){return this.data.readUInt32LE(14)};FileHeader.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(26)};FileHeader.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(28)};FileHeader.prototype.fileName=function fileName(){return safeToString(this.data,this.useUTF8(),30,this.fileNameLength())};FileHeader.prototype.extraField=function extraField(){var start=30+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};FileHeader.prototype.totalSize=function totalSize(){return 30+this.fileNameLength()+this.extraFieldLength()};FileHeader.prototype.useUTF8=function useUTF8(){return(this.flags()&2048)===2048};var FileData=function FileData2(header,record,data){this.header=header;this.record=record;this.data=data};FileData.prototype.decompress=function decompress(){var compressionMethod=this.header.compressionMethod();var fcn=decompressionMethods[compressionMethod];if(fcn){return fcn(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag())}else{var name=CompressionMethod[compressionMethod];if(!name){name="Unknown: "+compressionMethod}throw new ApiError(ErrorCode.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+name)}};FileData.prototype.getHeader=function getHeader(){return this.header};FileData.prototype.getRecord=function getRecord(){return this.record};FileData.prototype.getRawData=function getRawData(){return this.data};var DataDescriptor=function DataDescriptor2(data){this.data=data};DataDescriptor.prototype.crc32=function crc32(){return this.data.readUInt32LE(0)};DataDescriptor.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(4)};DataDescriptor.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(8)};var ArchiveExtraDataRecord=function ArchiveExtraDataRecord2(data){this.data=data;if(this.data.readUInt32LE(0)!==134630224){throw new ApiError(ErrorCode.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))}};ArchiveExtraDataRecord.prototype.length=function length(){return this.data.readUInt32LE(4)};ArchiveExtraDataRecord.prototype.extraFieldData=function extraFieldData(){return this.data.slice(8,8+this.length())};var DigitalSignature=function DigitalSignature2(data){this.data=data;if(this.data.readUInt32LE(0)!==84233040){throw new ApiError(ErrorCode.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))}};DigitalSignature.prototype.size=function size(){return this.data.readUInt16LE(4)};DigitalSignature.prototype.signatureData=function signatureData(){return this.data.slice(6,6+this.size())};var CentralDirectory=function CentralDirectory2(zipData,data){this.zipData=zipData;this.data=data;if(this.data.readUInt32LE(0)!==33639248){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0))}this._filename=this.produceFilename()};CentralDirectory.prototype.versionMadeBy=function versionMadeBy(){return this.data.readUInt16LE(4)};CentralDirectory.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(6)};CentralDirectory.prototype.flag=function flag(){return this.data.readUInt16LE(8)};CentralDirectory.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(10)};CentralDirectory.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(12),this.data.readUInt16LE(14))};CentralDirectory.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(12)};CentralDirectory.prototype.crc32=function crc32(){return this.data.readUInt32LE(16)};CentralDirectory.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(20)};CentralDirectory.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(24)};CentralDirectory.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(28)};CentralDirectory.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(30)};CentralDirectory.prototype.fileCommentLength=function fileCommentLength(){return this.data.readUInt16LE(32)};CentralDirectory.prototype.diskNumberStart=function diskNumberStart(){return this.data.readUInt16LE(34)};CentralDirectory.prototype.internalAttributes=function internalAttributes(){return this.data.readUInt16LE(36)};CentralDirectory.prototype.externalAttributes=function externalAttributes(){return this.data.readUInt32LE(38)};CentralDirectory.prototype.headerRelativeOffset=function headerRelativeOffset(){return this.data.readUInt32LE(42)};CentralDirectory.prototype.produceFilename=function produceFilename(){var fileName=safeToString(this.data,this.useUTF8(),46,this.fileNameLength());return fileName.replace(/\\/g,"/")};CentralDirectory.prototype.fileName=function fileName(){return this._filename};CentralDirectory.prototype.rawFileName=function rawFileName(){return this.data.slice(46,46+this.fileNameLength())};CentralDirectory.prototype.extraField=function extraField(){var start=44+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};CentralDirectory.prototype.fileComment=function fileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return safeToString(this.data,this.useUTF8(),start,this.fileCommentLength())};CentralDirectory.prototype.rawFileComment=function rawFileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(start,start+this.fileCommentLength())};CentralDirectory.prototype.totalSize=function totalSize(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()};CentralDirectory.prototype.isDirectory=function isDirectory(){var fileName=this.fileName();return(this.externalAttributes()&16?true:false)||fileName.charAt(fileName.length-1)==="/"};CentralDirectory.prototype.isFile=function isFile(){return!this.isDirectory()};CentralDirectory.prototype.useUTF8=function useUTF8(){return(this.flag()&2048)===2048};CentralDirectory.prototype.isEncrypted=function isEncrypted(){return(this.flag()&1)===1};CentralDirectory.prototype.getFileData=function getFileData(){var start=this.headerRelativeOffset();var header=new FileHeader(this.zipData.slice(start));return new FileData(header,this,this.zipData.slice(start+header.totalSize()))};CentralDirectory.prototype.getData=function getData(){return this.getFileData().decompress()};CentralDirectory.prototype.getRawData=function getRawData(){return this.getFileData().getRawData()};CentralDirectory.prototype.getStats=function getStats(){return new Stats(FileType.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var EndOfCentralDirectory=function EndOfCentralDirectory2(data){this.data=data;if(this.data.readUInt32LE(0)!==101010256){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))}};EndOfCentralDirectory.prototype.diskNumber=function diskNumber(){return this.data.readUInt16LE(4)};EndOfCentralDirectory.prototype.cdDiskNumber=function cdDiskNumber(){return this.data.readUInt16LE(6)};EndOfCentralDirectory.prototype.cdDiskEntryCount=function cdDiskEntryCount(){return this.data.readUInt16LE(8)};EndOfCentralDirectory.prototype.cdTotalEntryCount=function cdTotalEntryCount(){return this.data.readUInt16LE(10)};EndOfCentralDirectory.prototype.cdSize=function cdSize(){return this.data.readUInt32LE(12)};EndOfCentralDirectory.prototype.cdOffset=function cdOffset(){return this.data.readUInt32LE(16)};EndOfCentralDirectory.prototype.cdZipCommentLength=function cdZipCommentLength(){return this.data.readUInt16LE(20)};EndOfCentralDirectory.prototype.cdZipComment=function cdZipComment(){return safeToString(this.data,true,22,this.cdZipCommentLength())};EndOfCentralDirectory.prototype.rawCdZipComment=function rawCdZipComment(){return this.data.slice(22,22+this.cdZipCommentLength())};var ZipTOC=function ZipTOC2(index,directoryEntries,eocd,data){this.index=index;this.directoryEntries=directoryEntries;this.eocd=eocd;this.data=data};var ZipFS=function(SynchronousFileSystem$$1){function ZipFS2(input,name,deprecateMsg){if(name===void 0)name="";if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this.name=name;this._index=new FileIndex;this._directoryEntries=[];this._eocd=null;deprecationMessage(deprecateMsg,ZipFS2.Name,{zipData:"zip data as a Buffer",name});if(input instanceof ZipTOC){this._index=input.index;this._directoryEntries=input.directoryEntries;this._eocd=input.eocd;this.data=input.data}else{this.data=input;this.populateIndex()}}if(SynchronousFileSystem$$1)ZipFS2.__proto__=SynchronousFileSystem$$1;ZipFS2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);ZipFS2.prototype.constructor=ZipFS2;ZipFS2.Create=function Create(opts,cb){try{ZipFS2.computeIndex(opts.zipData,function(zipTOC){var fs4=new ZipFS2(zipTOC,opts.name,false);cb(null,fs4)},false)}catch(e){cb(e)}};ZipFS2.isAvailable=function isAvailable(){return true};ZipFS2.RegisterDecompressionMethod=function RegisterDecompressionMethod(m,fcn){decompressionMethods[m]=fcn};ZipFS2.computeIndex=function computeIndex(data,cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.")}var index=new FileIndex;var eocd=ZipFS2.getEOCD(data);if(eocd.diskNumber()!==eocd.cdDiskNumber()){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support spanned zip files.")}var cdPtr=eocd.cdOffset();if(cdPtr===4294967295){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support Zip64.")}var cdEnd=cdPtr+eocd.cdSize();ZipFS2.computeIndexResponsive(data,index,cdPtr,cdEnd,cb,[],eocd)};ZipFS2.getEOCD=function getEOCD(data){var startOffset=22;var endOffset=Math.min(startOffset+65535,data.length-1);for(var i2=startOffset;i2-1};DirectoryRecord.prototype.getRockRidgeOffset=function getRockRidgeOffset(){return this._rockRidgeOffset};DirectoryRecord.prototype.rootCheckForRockRidge=function rootCheckForRockRidge(isoData){var dir=this.getDirectory(isoData);this._rockRidgeOffset=dir.getDotEntry(isoData)._getRockRidgeOffset(isoData);if(this._rockRidgeOffset>-1){this._fileOrDir=null}};DirectoryRecord.prototype.length=function length(){return this._data[0]};DirectoryRecord.prototype.extendedAttributeRecordLength=function extendedAttributeRecordLength(){return this._data[1]};DirectoryRecord.prototype.lba=function lba(){return this._data.readUInt32LE(2)*2048};DirectoryRecord.prototype.dataLength=function dataLength(){return this._data.readUInt32LE(10)};DirectoryRecord.prototype.recordingDate=function recordingDate(){return getShortFormDate(this._data,18)};DirectoryRecord.prototype.fileFlags=function fileFlags(){return this._data[25]};DirectoryRecord.prototype.fileUnitSize=function fileUnitSize(){return this._data[26]};DirectoryRecord.prototype.interleaveGapSize=function interleaveGapSize(){return this._data[27]};DirectoryRecord.prototype.volumeSequenceNumber=function volumeSequenceNumber(){return this._data.readUInt16LE(28)};DirectoryRecord.prototype.identifier=function identifier(){return this._getString(33,this._data[32])};DirectoryRecord.prototype.fileName=function fileName(isoData){if(this.hasRockRidge()){var fn=this._rockRidgeFilename(isoData);if(fn!==null){return fn}}var ident=this.identifier();if(this.isDirectory(isoData)){return ident}var versionSeparator=ident.indexOf(";");if(versionSeparator===-1){return ident}else if(ident[versionSeparator-1]==="."){return ident.slice(0,versionSeparator-1)}else{return ident.slice(0,versionSeparator)}};DirectoryRecord.prototype.isDirectory=function isDirectory(isoData){var rv=!!(this.fileFlags()&2);if(!rv&&this.hasRockRidge()){rv=this.getSUEntries(isoData).filter(function(e){return e instanceof CLEntry}).length>0}return rv};DirectoryRecord.prototype.isSymlink=function isSymlink(isoData){return this.hasRockRidge()&&this.getSUEntries(isoData).filter(function(e){return e instanceof SLEntry}).length>0};DirectoryRecord.prototype.getSymlinkPath=function getSymlinkPath(isoData){var p="";var entries=this.getSUEntries(isoData);var getStr=this._getGetString();for(var i2=0,list2=entries;i21&&p[p.length-1]==="/"){return p.slice(0,p.length-1)}else{return p}};DirectoryRecord.prototype.getFile=function getFile(isoData){if(this.isDirectory(isoData)){throw new Error("Tried to get a File from a directory.")}if(this._fileOrDir===null){this._fileOrDir=isoData.slice(this.lba(),this.lba()+this.dataLength())}return this._fileOrDir};DirectoryRecord.prototype.getDirectory=function getDirectory(isoData){if(!this.isDirectory(isoData)){throw new Error("Tried to get a Directory from a file.")}if(this._fileOrDir===null){this._fileOrDir=this._constructDirectory(isoData)}return this._fileOrDir};DirectoryRecord.prototype.getSUEntries=function getSUEntries(isoData){if(!this._suEntries){this._constructSUEntries(isoData)}return this._suEntries};DirectoryRecord.prototype._rockRidgeFilename=function _rockRidgeFilename(isoData){var nmEntries=this.getSUEntries(isoData).filter(function(e2){return e2 instanceof NMEntry});if(nmEntries.length===0||nmEntries[0].flags()&(2|4)){return null}var str="";var getString=this._getGetString();for(var i2=0,list2=nmEntries;i20){var spEntry=suEntries[0];if(spEntry instanceof SPEntry&&spEntry.checkBytesPass()){for(var i2=1;i2K_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer2.prototype;return buf}function Buffer2(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer2[Symbol.species]===Buffer2){Object.defineProperty(Buffer2,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer2.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer2.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer2.prototype.__proto__=Uint8Array.prototype;Buffer2.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==void 0){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer2.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer2.allocUnsafe=function(size){return allocUnsafe(size)};Buffer2.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer2.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer2.alloc(+length)}Buffer2.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};Buffer2.compare=function compare(a,b){if(!Buffer2.isBuffer(a)||!Buffer2.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer2.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===void 0||start<0){start=0}if(start>this.length){return""}if(end===void 0||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer2.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer2.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer2.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer2.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===void 0){start=0}if(end===void 0){end=target?target.length:0}if(thisStart===void 0){thisStart=0}if(thisEnd===void 0){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer2.from(val,encoding)}if(Buffer2.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==void 0){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i2){if(indexSize===1){return buf[i2]}else{return buf.readUInt16BE(i2*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===void 0)encoding="utf8"}else{encoding=length;length=void 0}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===void 0||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer2.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer2.prototype.readUIntLE=function readUIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){checkOffset(offset,byteLength2,this.length)}var val=this[offset+--byteLength2];var mul=1;while(byteLength2>0&&(mul*=256)){val+=this[offset+--byteLength2]*mul}return val};Buffer2.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer2.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer2.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer2.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer2.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer2.prototype.readIntLE=function readIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readIntBE=function readIntBE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var i=byteLength2;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer2.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer2.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer2.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer2.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer2.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer2.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer2.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer2.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var i=byteLength2-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength2};Buffer2.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer2.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer2.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer2.prototype.writeIntLE=function writeIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeIntBE=function writeIntBE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=byteLength2-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer2.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer2.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer2.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer2.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer2.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer2.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer2.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3){for(i=0;i>>0;end=end===void 0?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function isArrayBufferView(obj){return typeof ArrayBuffer.isView==="function"&&ArrayBuffer.isView(obj)}function numberIsNaN(obj){return obj!==obj}}).call(exports2,__webpack_require__(1))},function(module2,exports2){"use strict";exports2.byteLength=byteLength;exports2.toByteArray=toByteArray;exports2.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len2-2]==="="?2:b64[len2-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i2,j,l,tmp,placeHolders,arr;var len2=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len2*3/4-placeHolders);l=placeHolders>0?len2-4:len2;var L=0;for(i2=0,j=0;i2>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i2=start;i2len22?len22:i2+maxChunkLength))}if(extraBytes===1){tmp=uint8[len2-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len2-2]<<8)+uint8[len2-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},function(module2,exports2){exports2.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports2.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},function(module2,exports2){module2.exports=function(module3){if(!module3.webpackPolyfill){module3.deprecate=function(){};module3.paths=[];module3.children=[];module3.webpackPolyfill=1}return module3}},function(module2,exports2,__webpack_require__){"use strict";var Process=__webpack_require__(7);var process=new Process,processProxy={};function defineKey(key2){if(processProxy[key2]){return}if(typeof process[key2]==="function"){processProxy[key2]=function(){return process[key2].apply(process,arguments)}}else{processProxy[key2]=process[key2]}}for(var key in process){defineKey(key)}processProxy.initializeTTYs=function(){if(process.stdin===null){process.initializeTTYs();processProxy.stdin=process.stdin;processProxy.stdout=process.stdout;processProxy.stderr=process.stderr}};process.nextTick(function(){processProxy.initializeTTYs()});module2.exports=processProxy},function(module2,exports2,__webpack_require__){(function(__dirname){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var events=__webpack_require__(8);var path=null;var Item=function(){function Item2(fun,array){this.fun=fun;this.array=array}Item2.prototype.run=function(){this.fun.apply(null,this.array)};return Item2}();var NextTickQueue=function(){function NextTickQueue2(){this._queue=[];this._draining=false;this._currentQueue=null;this._queueIndex=-1}NextTickQueue2.prototype.push=function(item){var _this=this;if(this._queue.push(item)===1&&!this._draining){setTimeout(function(){return _this._drainQueue()},0)}};NextTickQueue2.prototype._cleanUpNextTick=function(){this._draining=false;if(this._currentQueue&&this._currentQueue.length){this._queue=this._currentQueue.concat(this._queue)}else{this._queueIndex=-1}if(this._queue.length){this._drainQueue()}};NextTickQueue2.prototype._drainQueue=function(){var _this=this;if(this._draining){return}var timeout=setTimeout(function(){return _this._cleanUpNextTick()});this._draining=true;var len=this._queue.length;while(len){this._currentQueue=this._queue;this._queue=[];while(++this._queueIndex0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},function(module2,exports2,__webpack_require__){(function(process){"use strict";var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;function posixSplitPath(filename){var out=splitPathRe.exec(filename);out.shift();return out}var path=function(){function path2(){}path2.normalize=function(p){if(p===""){p="."}var absolute=p.charAt(0)===path2.sep;p=path2._removeDuplicateSeps(p);var components=p.split(path2.sep);var goodComponents=[];for(var idx=0;idx0&&goodComponents[0]!=="..")){goodComponents.pop()}else{goodComponents.push(c)}}if(!absolute&&goodComponents.length<2){switch(goodComponents.length){case 1:if(goodComponents[0]===""){goodComponents.unshift(".")}break;default:goodComponents.push(".")}}p=goodComponents.join(path2.sep);if(absolute&&p.charAt(0)!==path2.sep){p=path2.sep+p}return p};path2.join=function(){var paths=[];for(var _i=0;_i1&&resolved.charAt(resolved.length-1)===path2.sep){return resolved.substr(0,resolved.length-1)}if(resolved.charAt(0)!==path2.sep){if(resolved.charAt(0)==="."&&(resolved.length===1||resolved.charAt(1)===path2.sep)){resolved=resolved.length===1?"":resolved.substr(2)}var cwd=process.cwd();if(resolved!==""){resolved=this.normalize(cwd+(cwd!=="/"?path2.sep:"")+resolved)}else{resolved=cwd}}return resolved};path2.relative=function(from,to){var i;from=path2.resolve(from);to=path2.resolve(to);var fromSegs=from.split(path2.sep);var toSegs=to.split(path2.sep);toSegs.shift();fromSegs.shift();var upCount=0;var downSegs=[];for(i=0;ifromSegs.length){upCount=fromSegs.length}var rv="";for(i=0;i1&&rv.charAt(rv.length-1)===path2.sep){rv=rv.substr(0,rv.length-1)}return rv};path2.dirname=function(p){p=path2._removeDuplicateSeps(p);var absolute=p.charAt(0)===path2.sep;var sections=p.split(path2.sep);if(sections.pop()===""&§ions.length>0){sections.pop()}if(sections.length>1||sections.length===1&&!absolute){return sections.join(path2.sep)}else if(absolute){return path2.sep}else{return"."}};path2.basename=function(p,ext){if(ext===void 0){ext=""}if(p===""){return p}p=path2.normalize(p);var sections=p.split(path2.sep);var lastPart=sections[sections.length-1];if(lastPart===""&§ions.length>1){return sections[sections.length-2]}if(ext.length>0){var lastPartExt=lastPart.substr(lastPart.length-ext.length);if(lastPartExt===ext){return lastPart.substr(0,lastPart.length-ext.length)}}return lastPart};path2.extname=function(p){p=path2.normalize(p);var sections=p.split(path2.sep);p=sections.pop();if(p===""&§ions.length>0){p=sections.pop()}if(p===".."){return""}var i=p.lastIndexOf(".");if(i===-1||i===0){return""}return p.substr(i)};path2.isAbsolute=function(p){return p.length>0&&p.charAt(0)===path2.sep};path2._makeLong=function(p){return p};path2.parse=function(p){var allParts=posixSplitPath(p);return{root:allParts[0],dir:allParts[0]+allParts[1].slice(0,-1),base:allParts[2],ext:allParts[3],name:allParts[2].slice(0,allParts[2].length-allParts[3].length)}};path2.format=function(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof pathObject)}var root=pathObject.root||"";if(typeof root!=="string"){throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof pathObject.root)}var dir=pathObject.dir?pathObject.dir+path2.sep:"";var base=pathObject.base||"";return dir+base};path2._removeDuplicateSeps=function(p){p=p.replace(this._replaceRegex,this.sep);return p};path2.sep="/";path2._replaceRegex=new RegExp("//+","g");path2.delimiter=":";path2.posix=path2;path2.win32=path2;return path2}();var _=path;module2.exports=path}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(Buffer2){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var stream=__webpack_require__(11);var TTY=function(_super){__extends(TTY2,_super);function TTY2(){_super.call(this);this.isRaw=false;this.columns=80;this.rows=120;this.isTTY=true;this._bufferedWrites=[];this._waitingForWrites=false}TTY2.prototype.setRawMode=function(mode){if(this.isRaw!==mode){this.isRaw=mode;this.emit("modeChange")}};TTY2.prototype.changeColumns=function(columns){if(columns!==this.columns){this.columns=columns;this.emit("resize")}};TTY2.prototype.changeRows=function(rows){if(rows!==this.rows){this.rows=rows;this.emit("resize")}};TTY2.isatty=function(fd){return fd&&fd instanceof TTY2};TTY2.prototype._write=function(chunk,encoding,cb){var error;try{var data;if(typeof chunk==="string"){data=new Buffer2(chunk,encoding)}else{data=chunk}this._bufferedWrites.push(data);if(this._waitingForWrites){this._read(1024)}}catch(e){error=e}finally{cb(error)}};TTY2.prototype._read=function(size){if(this._bufferedWrites.length===0){this._waitingForWrites=true}else{while(this._bufferedWrites.length>0){this._waitingForWrites=this.push(this._bufferedWrites.shift());if(!this._waitingForWrites){break}}}};return TTY2}(stream.Duplex);module2.exports=TTY}).call(exports2,__webpack_require__(1))},function(module2,exports2,__webpack_require__){module2.exports=Stream;var EE=__webpack_require__(8).EventEmitter;var inherits=__webpack_require__(12);inherits(Stream,EE);Stream.Readable=__webpack_require__(13);Stream.Writable=__webpack_require__(27);Stream.Duplex=__webpack_require__(28);Stream.Transform=__webpack_require__(29);Stream.PassThrough=__webpack_require__(30);Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},function(module2,exports2){if(typeof Object.create==="function"){module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},function(module2,exports2,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(11)}catch(_){}}();exports2=module2.exports=__webpack_require__(14);exports2.Stream=Stream||exports2;exports2.Readable=exports2;exports2.Writable=__webpack_require__(22);exports2.Duplex=__webpack_require__(21);exports2.Transform=__webpack_require__(25);exports2.PassThrough=__webpack_require__(26);if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module2.exports=Stream}}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(process){"use strict";module2.exports=Readable;var processNextTick=__webpack_require__(15);var isArray=__webpack_require__(16);var Duplex;Readable.ReadableState=ReadableState;var EE=__webpack_require__(8).EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var debugUtil=__webpack_require__(19);var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=__webpack_require__(20);var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=__webpack_require__(24).StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||__webpack_require__(21);if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer2.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;iMAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===void 0){enc=void 0;_fill=0}var buf=new Buffer2(size);if(typeof _fill==="string"){var fillBuf=new Buffer2(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer2(size)};exports2.from=function from(value,encodingOrOffset,length){if(typeof Buffer2.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer2.from)){return Buffer2.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer2(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer2(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer2(value.slice(offset,offset+len))}if(Buffer2.isBuffer(value)){var out=new Buffer2(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer2(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer2(value.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")};exports2.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer2.allocUnsafeSlow==="function"){return Buffer2.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(exports2,function(){return this}())},function(module2,exports2,__webpack_require__){(function(Buffer2){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports2.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports2.isBoolean=isBoolean;function isNull(arg){return arg===null}exports2.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports2.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports2.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports2.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports2.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports2.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports2.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports2.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports2.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports2.isError=isError;function isFunction(arg){return typeof arg==="function"}exports2.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports2.isPrimitive=isPrimitive;exports2.isBuffer=Buffer2.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(exports2,__webpack_require__(1))},function(module2,exports2){},function(module2,exports2,__webpack_require__){"use strict";var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);module2.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},function(module2,exports2,__webpack_require__){"use strict";var objectKeys=Object.keys||function(obj){var keys2=[];for(var key in obj){keys2.push(key)}return keys2};module2.exports=Duplex;var processNextTick=__webpack_require__(15);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var Readable=__webpack_require__(14);var Writable=__webpack_require__(22);util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var internalUtil={deprecate:__webpack_require__(23)};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||__webpack_require__(21);if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer2.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer2.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},function(module2,exports2,__webpack_require__){"use strict";module2.exports=Transform;var Duplex=__webpack_require__(21);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==void 0)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==c.Z_OK){throw new Error(msg[status])}this.header=new GZheader;zlib_inflate.inflateGetHeader(this.strm,this.header)}Inflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_mode;var next_out_utf8,tail,utf8str;var dict;var allowBufError=false;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?c.Z_FINISH:c.Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.binstring2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_inflate.inflate(strm,c.Z_NO_FLUSH);if(status===c.Z_NEED_DICT&&dictionary){if(typeof dictionary==="string"){dict=strings.string2buf(dictionary)}else if(toString.call(dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(dictionary)}else{dict=dictionary}status=zlib_inflate.inflateSetDictionary(this.strm,dict)}if(status===c.Z_BUF_ERROR&&allowBufError===true){status=c.Z_OK;allowBufError=false}if(status!==c.Z_STREAM_END&&status!==c.Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.next_out){if(strm.avail_out===0||status===c.Z_STREAM_END||strm.avail_in===0&&(_mode===c.Z_FINISH||_mode===c.Z_SYNC_FLUSH)){if(this.options.to==="string"){next_out_utf8=strings.utf8border(strm.output,strm.next_out);tail=strm.next_out-next_out_utf8;utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail){utils.arraySet(strm.output,strm.output,next_out_utf8,tail,0)}this.onData(utf8str)}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}if(strm.avail_in===0&&strm.avail_out===0){allowBufError=true}}while((strm.avail_in>0||strm.avail_out===0)&&status!==c.Z_STREAM_END);if(status===c.Z_STREAM_END){_mode=c.Z_FINISH}if(_mode===c.Z_FINISH){status=zlib_inflate.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===c.Z_OK}if(_mode===c.Z_SYNC_FLUSH){this.onEnd(c.Z_OK);strm.avail_out=0;return true}return true};Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate.prototype.onEnd=function(status){if(status===c.Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate(input,options){var inflator=new Inflate(options);inflator.push(input,true);if(inflator.err){throw inflator.msg||msg[inflator.err]}return inflator.result}function inflateRaw(input,options){options=options||{};options.raw=true;return inflate(input,options)}exports2.Inflate=Inflate;exports2.inflate=inflate;exports2.inflateRaw=inflateRaw;exports2.ungzip=inflate},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var adler32=__webpack_require__(34);var crc32=__webpack_require__(35);var inflate_fast=__webpack_require__(36);var inflate_table=__webpack_require__(37);var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&©>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module2.exports=adler32},function(module2,exports2){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255]}return crc^-1}module2.exports=crc32},function(module2,exports2){"use strict";var BAD=30;var TYPE=12;module2.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits>>=op;bits-=op}if(bits<15){hold+=input[_in++]<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bitsdmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3;_in-=len;bits-=len<<3;hold&=(1<=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}for(;;){here_bits=len-drop;if(work[sym]end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var STR_APPLY_OK=true;var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,[0])}catch(__){STR_APPLY_OK=false}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new utils.Buf8(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1}_utf8len[254]=_utf8len[254]=1;exports2.string2buf=function(str){var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos>>6;buf[i++]=128|c&63}else if(c<65536){buf[i++]=224|c>>>12;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}else{buf[i++]=240|c>>>18;buf[i++]=128|c>>>12&63;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}}return buf};function buf2binstring(buf,len){if(len<65537){if(buf.subarray&&STR_APPLY_UIA_OK||!buf.subarray&&STR_APPLY_OK){return String.fromCharCode.apply(null,utils.shrinkBuf(buf,len))}}var result="";for(var i=0;i4){utf16buf[out++]=65533;i+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};exports2.utf8border=function(buf,max){var pos;max=max||buf.length;if(max>buf.length){max=buf.length}pos=max-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max}if(pos===0){return max}return pos+_utf8len[buf[pos]]>max?pos:max}},function(module2,exports2){"use strict";module2.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(module2,exports2){"use strict";module2.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(module2,exports2){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module2.exports=ZStream},function(module2,exports2){"use strict";function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}module2.exports=GZheader}])})}});var CSV=class{constructor(onOpen=this.onOpen,saveButtonId=null,openButtonId=null){this.onOpen=onOpen;this.notes=[];if(saveButtonId!==null){document.getElementById(saveButtonId).addEventListener("click",this.saveCSV)}if(openButtonId!==null){document.getElementById(openButtonId).addEventListener("click",this.openCSV)}}processArraysForCSV(data=["1|2|3","3|2|1"],delimiter="|",header="a,b,c",saveNotes=false){let csvDat=header+"\n";let noteIdx=0;data.forEach((line,i)=>{if(data[i]==="string"&&delimiter!==","){csvDat+=line.split(delimiter).join(",")}else{csvData+=line.join(",")}if(saveNotes===true){if(this.notes[noteIdx].idx===i){line+=this.notes[noteIdx].text;noteIdx++}}if(line.indexOf("\n")<0){csvDat+="\n"}});return csvDat}static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){var hiddenElement=document.createElement("a");hiddenElement.href="data:text/csv;charset=utf-8,"+encodeURI(csvDat);hiddenElement.target="_blank";if(name!==""){hiddenElement.download=name}else{hiddenElement.download=new Date().toISOString()+".csv"}hiddenElement.click()}static openCSV(delimiter=",",onOpen=(csvDat,header,path)=>{return csvDat,header,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;var tempcsvArr=tempcsvData.split("\n");let header=[];var csvDat=[];tempcsvArr.pop();tempcsvArr.forEach((row,i)=>{if(i==0){header=row.split(delimiter)}else{var temp=row.split(delimiter);csvDat.push(temp)}});onOpen(csvDat,header,input.value);input.value="";res({data:csvDat,header,filename:input.value})};reader.readAsText(file)};input.click()})}static openCSVRaw(onOpen=(csvDat,path)=>{return csvDat,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;onOpen(tempcsvData,input.value);input.value="";res({data:tempcsvData,filename:input.value})};reader.readAsText(file)};input.click()})}onOpen(csvDat=[],header=[]){console.log("CSV Opened!",header,csvDat)}};var parseCSVData=(data,filename,head,hasend=true,parser=(lines,filename2,head2)=>{let result={filename:filename2};let header=head2;if(typeof head2==="string")header=head2.split(",");result.header=header;for(let i=0;i{let lines;if(data.includes("\r"))lines=data.split("\r\n");else lines=data.split("\n");if(!head)head=lines[0];lines.shift();if(hasend===false)lines.pop();let result=parser(lines,filename,head);return result};function toISOLocal(d){d=new Date(d);var z=n=>("0"+n).slice(-2);var zz=n=>("00"+n).slice(-3);var off=d.getTimezoneOffset();var sign=off<0?"+":"-";off=Math.abs(off);return d.getFullYear()+"-"+z(d.getMonth()+1)+"-"+z(d.getDate())+"T"+z(d.getHours())+":"+z(d.getMinutes())+":"+z(d.getSeconds())+"."+zz(d.getMilliseconds())+"(UTC"+sign+z(off/60|0)+":00)"}var processDataForCSV=(options={})=>{if(!options.data)return void 0;if(!Array.isArray(options.data))options.data=[options.data];if(options.data&&!options.header)options.header=Object.keys(options.data[0]);let head=[...options.header];if(head.indexOf("timestamp")>-1){head.splice(head.indexOf("timestamp")+1,0,"localized")}let header=head.join(",");let headeridx=0;let lines=[];let foreach=(obj,i)=>{if(Array.isArray(obj)){for(let j=0;j{if(exists2)appendFile(options.filename,joined,options.dir);else appendFile(options.filename,header+joined,options.dir)})}return result};var BrowserFS=__toESM(require_browserfs());var fsInited=false;var fs2=BrowserFS.BFSRequire("fs");var BFSBuffer=BrowserFS.BFSRequire("buffer").Buffer;var initPromise;var initFS=async(dirs=["data"],oninit=(exists2=[])=>{},onerror=e=>{},filesystem="IndexedDB")=>{if(fsInited){if(initPromise){await initPromise}return true}else{fsInited=true;initPromise=new Promise((resolve,reject)=>{BrowserFS.FileSystem[filesystem].Create({},(e,mountableFileSystem)=>{if(e){reject(e);return}if(!mountableFileSystem){onerror(e);reject(new Error(`Error creating BrowserFS`));return}BrowserFS.initialize(mountableFileSystem);let promises=[];dirs.forEach(async dir=>{promises.push(dirExists(fs2,dir))});Promise.all(promises).then(values=>{oninit(values);resolve(true)})})});return await initPromise}};var exists=async(path="")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.exists("/"+path,function(exists2){resolve(exists2)})})};var readFile=async(path="data")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.readFile("/"+path,function(e,output){resolve(output)})})};async function readFileChunk(path="data",begin=0,end=5120,onread=data=>{}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);if(path!=""){return await new Promise(async(resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})}else{console.error("Path name is not defined");return void 0}}var getFilenames=async(directory="data",onload=directory2=>{})=>{if(!fsInited)await initFS([directory]);else await dirExists(fs2,directory);return await new Promise((resolve,reject)=>{fs2.readdir("/"+directory,(e,dir)=>{if(e){reject(e);return}if(dir){onload(dir);resolve(dir)}else resolve(void 0)})})};var writeFile=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.writeFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var appendFile2=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.appendFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var deleteFile=async(path="data",ondelete=()=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{if(path!=""){fs2.unlink("/"+path,e=>{if(e)console.error(e);ondelete();resolve(true)})}else{console.error("Path name is not defined");resolve(false)}})};var readFileAsText=async(path="data",end="end",begin=0,onread=(data,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(async(resolve,reject)=>{let size=await getFileSize(path);if(end==="end"){end=size}else if(typeof end==="number"){if(end>size)end=size}fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})};var listFiles=async(dir="data",onload=directory=>{})=>{if(!fsInited)await initFS([dir]);else await dirExists(fs2,dir);return await new Promise((resolve,reject)=>{fs2.readdir("/"+dir,(e,directory)=>{if(e){reject(e);return}if(directory){onload(directory)}resolve(directory)})})};var getFileSize=async(path="data",onread=size=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;onread(filesize);resolve(filesize)})})};var getCSVHeader=async(path="data",onopen=(header,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,65535,0,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();let lines=data.split("\n");let header=lines[0];fs2.close(fd,()=>{onopen(header,path);resolve(header)})}else resolve(void 0)})})})};var writeToCSVFromDB=async(path="data",fileSizeLimitMb=10)=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{if(path!=""){fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;fs2.open(path,"r",(e2,fd)=>{if(e2){reject(e2);return}let i=0;let maxFileSize=fileSizeLimitMb*1024*1024;let end=maxFileSize;if(filesize{if(e3){reject(e3);return}if(bytesRead!==0)CSV.saveCSV(output.toString(),path.split("/")[1]);fs2.close(fd);resolve(true)})}else{const writeChunkToFile=async()=>{if(ifilesize){end=filesize-i}let chunk=0;fs2.read(fd,end,i,"utf-8",(e3,output,bytesRead)=>{if(e3){reject(e3);return}if(bytesRead!==0){CSV.saveCSV(output.toString(),path.split("/")[1]+"_"+chunk);i+=maxFileSize;chunk++;writeChunkToFile();fs2.close(fd);resolve(true)}})}}}})})}else{console.error("File name is not defined.");resolve(false)}})};async function processCSVChunksFromDB(path="data",onData=(csvdata,start2,end2,size)=>{},maxChunkSize=1e4,start=0,end="end",options={}){let size=await getFileSize(path);let partition=start;return await new Promise((res,rej)=>{let processPartition=()=>{let endChunk=partition+maxChunkSize;if(endChunk>size){endChunk=size}readCSVChunkFromDB(path,partition,endChunk,options).then(async result=>{await onData(result,partition,endChunk,size);partition=endChunk;if(partition!==size){processPartition()}else{res(true)}}).catch(rej)};processPartition()})}async function readCSVChunkFromDB(path="data",start=0,end="end",options={}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);const transpose=options.transpose||false;let head=await getCSVHeader(path);if(head)head=head.split(",");else return void 0;let resultLengths=[];let resultNames=[];let results=transpose?[]:{};head.forEach(v=>{if(v){resultNames.push(v);resultLengths.push(1)}else resultLengths[resultLengths.length-1]++});let size=await getFileSize(path);if(end==="end")end=size;else if(end>size){start=size-(end-start);end=size}let data=(await readFileChunk(path,start,end))?.split("\n").slice(1,-1);let preprocess=value=>{try{value=JSON.parse(value)}catch{}return value};if(data)data.forEach((r,i)=>{let row=r.split(",");if(transpose){const entry={};if(options.json)row.forEach((v,idx)=>{if(options.json)entry[resultNames[idx]]=preprocess(v);else entry[resultNames[idx]]=v});results.push(entry)}else{row.forEach((v,i2)=>{const header=resultNames[i2];if(!results[header])results[header]=[];if(options.json)results[header].push(preprocess(v));else results[header].push(v)})}});return results}var directories={};var dirExists=async(fs3,directory)=>{if(!fsInited)await initFS([directory]);return await new Promise((resolve,reject)=>{if(!directory)reject(false);if(directories[directory]==="exists"||directories[directory]==="created"){resolve()}else{if(directory[0]==="/")directory=directory.substring(1);if(!directory)reject(false);fs3.exists(`/${directory}`,exists2=>{if(exists2){directories[directory]="exists";resolve()}else if(directories[directory]==="creating"){resolve()}else{directories[directory]="creating";fs3.mkdir(`/${directory}`,1,err=>{if(err){reject(err);return}directories[directory]="created";setTimeout(resolve,500)})}})}})};var BFSRoutes={initFS,dirExists,exists,readFile,readFileChunk,getFilenames,writeFile,appendFile:appendFile2,deleteFile,readFileAsText,getFileSize,getCSVHeader,listFiles};var CSV_REFERENCE={};function lerp(v0,v1,t){return(1-t)*v0+t*v1}function interpolerp(v0,v1,fit,floor=true){if(fit<=2)return[v0,v1];let a=1/fit;let result=new Array(fit);result[0]=v0;for(let i=1;i<=fit;i++){result[i]=lerp(v0,v1,a*i);if(floor)result[i]=Math.floor(result[i])}return result}var appendCSV=async(newData,filename,header,options)=>{if(!filename){let keys=Object.keys(CSV_REFERENCE);if(keys.length>0)filename=keys[keys.length-1];else filename=`csv${new Date().toISOString()}`}let csv=CSV_REFERENCE[filename];if(!csv){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);CSV_REFERENCE[filename]={header:header?header:["timestamp","localized",...keys],lastX:void 0,buffer:"",buffered:0,bufferSize:options?.bufferSize?options.bufferSize:0,toFixed:options?.toFixed?options.toFixed:0,xIncrement:options?.xIncrement?options.xIncrement:0};csv=CSV_REFERENCE[filename];const existingHeader=await getCSVHeader(filename).catch(()=>null);const isDifferent=!existingHeader||existingHeader!==csv.header.join(",");if(isDifferent)header=csv.header}if(!csv.header||csv.header?.length===0){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);csv.header=header?header:["timestamp","localized",...keys]}else if(header)csv.header=header;let maxLen=1;for(const key in newData){const value=newData[key];if(csv.header.indexOf(key)>-1&&value&&Array.isArray(value)&&value?.length>maxLen)maxLen=value?.length}let x;if(csv.xIncrement){if(!csv.lastX){if(typeof newData[csv.header[0]]!=="undefined"){x=newData[csv.header[0]]}else if(csv.header[0].toLowerCase().includes("time")||csv.header[0].toLowerCase().includes("unix"))x=Date.now()}else{if(newData[csv.header[2]]){if(Array.isArray(newData[csv.header[2]]))x=csv.lastX+csv.xIncrement*newData[csv.header[2]].length;else x=csv.lastX+csv.xIncrement}else if(newData[csv.header[0]]){if(Array.isArray(newData[csv.header[0]]))x=csv.lastX+csv.xIncrement*newData[csv.header[0]].length;else x=csv.lastX+csv.xIncrement}else x=csv.lastX+csv.xIncrement}}else if(newData[csv.header[0]])x=newData[csv.header[0]];else x=Date.now();if(typeof csv.lastX==="undefined")csv.lastX=Array.isArray(x)?x[0]:x;if(typeof x==="undefined"){if(csv.header[0].includes("time")){let now=Date.now();if(maxLen===1)x=Date.now();else{x=interpolerp(csv.lastX,now,maxLen);x.shift()}}else{let newX=csv.lastX+1;if(maxLen>1){x=new Array(maxLen).fill("");x[maxLen-1]=newX}else x=newX}}else if(maxLen>1&&x?.length!==maxLen){if(!Array.isArray(x)||x.length===1){x=interpolerp(csv.lastX,x,maxLen,true);x.shift()}else{x=interpolerp(x[0],x[x.length-1],maxLen,true);x.shift()}}let toAppend=[];if(Array.isArray(x)){let curIdcs={};for(let i=0;icurIdcs[csv.header[j]]){curIdcs[csv.header[j]]++;toAppend[i][j]=d[curIdcs[csv.header[j]]]}else{toAppend[i][j]=""}}}}else{if(i===x.length-1){toAppend[i][j]=d}else{toAppend[i][j]=""}}if(typeof toAppend[i][j]==="number"&&Math.floor(toAppend[i][j])!==toAppend[i][j])toAppend[i][j]=toAppend[i][j].toFixed(CSV_REFERENCE[filename].toFixed)}}}else{toAppend.push([]);for(let j=0;j{csvProcessed+=(options?.json?arr.map(v=>JSON.stringify(v)):arr).join(",")+"\n";if(csv.bufferSize)csv.buffered++});csv.lastX=toAppend[toAppend.length-1][0];if(csv.bufferSize){csv.buffer+=csvProcessed;if(csv.buffered>csv.bufferSize){let r=new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csv.buffer,written=>{res(written)})}else{appendFile2(filename,csv.buffer,written=>{res(written)})}})});await r;csv.buffer="";csv.buffered=0;return r}else return await Promise.resolve(true)}else{return await new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csvProcessed,written=>{res(written)})}else{appendFile2(filename,csvProcessed,written=>{res(written)})}})})}};var updateCSVHeader=(header,filename)=>{if(CSV_REFERENCE[filename]){CSV_REFERENCE[filename].header=header}};var createCSV=(filename,header,toFixed=5,bufferSize=0,xIncrement)=>{if(!CSV_REFERENCE[filename]){if(header?.indexOf("timestamp")>1){header.splice(header.indexOf("timestamp"),1);header.unshift("timestamp")}if((header?.[0].toLowerCase().includes("time")||header?.[0].toLowerCase().includes("unix"))&&header[1]!=="localized"){header.splice(1,0,"localized")}CSV_REFERENCE[filename]={header,lastX:header[1]==="localized"?Date.now():0,bufferSize,buffer:"",buffered:0,toFixed,xIncrement};return new Promise((res,rej)=>{exists(filename).then(doesExist=>{if(!doesExist){writeFile(filename,CSV_REFERENCE[filename].header?CSV_REFERENCE[filename].header.join(",")+"\n":"",written=>{res(written)}).catch(rej)}})})}};var visualizeDirectory=(dir,parentNode=document.body)=>{return new Promise(async(res,rej)=>{if(parentNode.querySelector("#bfs"+dir))parentNode.querySelector("#bfs"+dir)?.remove();parentNode.insertAdjacentHTML("beforeend",`
`);let div=parentNode.querySelector("#bfs"+dir);await listFiles(dir).then(directory=>{if(directory.length===0)div.innerHTML="No Files!";else directory.forEach(listing=>{div?.insertAdjacentHTML("beforeend",`
- Data: - ${listing} - - ${listing.indexOf(".")>-1?``:""} -
`);if(document.getElementById(`delete${listing}`)){document.getElementById(`delete${listing}`).onclick=()=>{deleteFile(dir+"/"+listing,()=>{visualizeDirectory(dir,parentNode)})}}if(document.getElementById(`download${listing}`)){document.getElementById(`download${listing}`).onclick=()=>{writeToCSVFromDB(dir+"/"+listing,10)}}});res(directory)}).catch(rej)})};var csvRoutes={appendCSV,updateCSVHeader,createCSV,visualizeDirectory,openCSV:CSV.openCSV,saveCSV:CSV.saveCSV,openCSVRaw:CSV.openCSVRaw,parseCSVData,getCSVHeader,writeToCSVFromDB,readCSVChunkFromDB,processCSVChunksFromDB,toISOLocal};})(); -/*! Bundled license information: - -browserfs/dist/browserfs.js: - (*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *) -*/ diff --git a/src/extras/dist/loaders/index.d.ts b/src/extras/dist/loaders/index.d.ts deleted file mode 100644 index 229b9ec7..00000000 --- a/src/extras/dist/loaders/index.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; -/** - * setting nodeA.__node.backward:true propagates operator results to parent - */ -export declare const backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** - * - * Specify a timer loop, will stop when node is popped or nodeA.__node.isLooping is set false - * nodeA.__node.loop = 100 will loop the operator every 100 milliseconds - * - * Or - * nodeA.__node.delay will delay the operator by specified millisecond number and resolve the result as a promise - * nodeA.__node.frame will use requestAnimationFrame to call the function and resolve the result as a promise - * - * Use in combination with: - * nodeA.__node.repeat will repeat the operator the specified number of times - * nodeA.__node.recursive will do the same as repeat but will pass in the previous operator call's results - * - * - */ -export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Animations - * - * nodeA.__node.animate = true; - * then __operator becomes a requestAnimationFrame function - * start with a call the __operator or by setting node.__node.animating = true; - * - * or node.__animation = (...args) => {} - * - */ -export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Branching operations - * - * //runs a function or node if the if-conditions are satisfied, which can be a function that returns a true or false - * nodeA.__branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} - * - * nodeA.__listeners['nodeB.x'] = { - * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } - * } - * - */ -export declare const branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Trigger listeners oncreate with specific arguments - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, oncreate:any } - * - */ -export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Bind listeners to a specific object instead of the node that owns it - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } - * - */ -export declare const bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, transform:(result)=>any } - * - */ -export declare const transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -export declare const substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; -export declare const loaders: { - backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; -}; diff --git a/src/extras/dist/loaders/methodstrings.d.ts b/src/extras/dist/loaders/methodstrings.d.ts deleted file mode 100644 index 978aabc8..00000000 --- a/src/extras/dist/loaders/methodstrings.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function methodstrings(node: any): void; diff --git a/src/extras/dist/services/Service.d.ts b/src/extras/dist/services/Service.d.ts deleted file mode 100644 index a5558998..00000000 --- a/src/extras/dist/services/Service.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Graph, GraphNode, GraphOptions } from "../../src/core/Graph"; -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export type ServiceMessage = { - route?: string; - args?: any; - method?: string; - node?: string | GraphNode; - [key: string]: any; -}; -export type ServiceOptions = GraphOptions & { - services?: { - [key: string]: Service | Function | { - [key: string]: any; - }; - }; - restrict?: { - [key: string]: boolean; - }; -}; -export declare class Service extends Graph { - name: string; - restrict?: { - [key: string]: boolean; - }; - constructor(options?: ServiceOptions); - addServices: (services: { - [key: string]: Function | Graph | Service | { - [key: string]: any; - }; - }) => void; - handleMethod: (route: string, method: string, args?: any) => any; - handleServiceMessage(message: ServiceMessage): any; - handleGraphNodeCall(route: string | GraphNode, args: any): any; - transmit: (...args: any[]) => any | void; - receive: (...args: any[]) => any | void; - pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => number; - pipeOnce: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; - terminate: (...args: any) => void; - isTypedArray: typeof isTypedArray; - recursivelyAssign: (target: any, obj: any) => any; - spliceTypedArray: typeof spliceTypedArray; - ping: () => string; - echo: (...args: any) => any; - log: (...args: any) => boolean; - error: (...args: any) => boolean; -} -export declare function isTypedArray(x: any): boolean; -export declare const recursivelyAssign: (target: any, obj: any) => any; -export declare function spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; diff --git a/src/extras/dist/services/ecs/ECS.service.d.ts b/src/extras/dist/services/ecs/ECS.service.d.ts deleted file mode 100644 index cb3252b8..00000000 --- a/src/extras/dist/services/ecs/ECS.service.d.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { GraphNode, GraphNodeProperties } from '../../core/Graph'; -import { Service, ServiceOptions } from '../Service'; -export type EntityProps = { - components: { - [key: string]: any; - }; -} & (GraphNodeProperties | GraphNode); -export type SystemProps = (GraphNodeProperties & { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; -}) | GraphNode; -export type Entity = { - components: { - [key: string]: any; - }; - [key: string]: any; -} & GraphNode; -export type System = { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - remove?: (entity: Entity, entitities: { - [key: string]: Entity; - }) => Entity; - entities: { - [key: string]: Entity; - }; - entityKeys: string[]; -} & GraphNode; -export type ECSOptions = { - entities: { - [key: string]: EntityProps; - }; - systems: { - [key: string]: SystemProps; - }; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class ECSService extends Service { - entities: { - [key: string]: Entity; - }; - systems: { - [key: string]: System; - }; - entityMap: Map; - entityKeyMap: Map; - order: string[]; - animating: boolean; - entityCt: number; - systemCt: number; - constructor(options?: ECSOptions); - updateEntities: (order?: string[], filter?: boolean, debug?: any) => void; - animateEntities: (filter?: boolean, order?: string[]) => void; - stop: () => void; - start: (filter?: boolean) => void; - addEntities: (prototype: EntityProps, components?: { - [key: string]: any; - }, count?: number) => string[]; - addEntity: (prototype?: EntityProps, components?: { - [key: string]: any; - }) => Entity; - addSystems: (systems?: { - [key: string]: SystemProps; - }, order?: string[]) => { - [key: string]: System; - }; - addSystem: (prototype: SystemProps, setupEntities?: (entities: { - [key: string]: Entity; - }) => any, setupEntity?: (entity: Entity) => any, operator?: (entities: any) => any, remove?: (entities: any) => any, order?: string[]) => System; - setupEntity: (entity: Entity) => void; - removeEntity: (tag: string) => string | GraphNode; - removeEntities(entities: string[] | { - [key: string]: Entity; - }): void; - removeSystem: (tag: string) => string | GraphNode; - filterObject(o: { - [key: string]: any; - }, filter: (string: any, any: any) => boolean | undefined): { - [k: string]: any; - }; - setEntities: (entities: string[] | { - [key: string]: Entity; - }, props: { - [key: string]: any; - }) => boolean; - setEntity: (entity: Entity, props: { - [key: string]: any; - }) => any; - bufferValues: (entities: { - [key: string]: Entity; - }, property: string, keys?: string[] | { - [key: string]: any; - }, buffer?: ArrayBufferLike) => ArrayBufferLike; -} diff --git a/src/extras/dist/services/router/Router.d.ts b/src/extras/dist/services/router/Router.d.ts deleted file mode 100644 index 3d6e0348..00000000 --- a/src/extras/dist/services/router/Router.d.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { Graph, GraphNode } from "../../core/Graph"; -import { Service, ServiceOptions } from "../Service"; -export type User = { - _id: string; - send: (...args: any[]) => any; - request: (...args: any[]) => Promise | Promise[] | undefined; - post: (...args: any[]) => void; - run: (...args: any[]) => Promise | Promise[] | undefined; - subscribe: (...args: any[]) => Promise | Promise[] | undefined; - unsubscribe: (...args: any[]) => Promise | Promise[] | undefined; - sendAll?: (...args: any[]) => any; - requestAll?: (...args: any[]) => Promise | undefined; - postAll?: (...args: any[]) => void; - runAll?: (...args: any[]) => Promise | undefined; - subscribeAll?: (...args: any[]) => Promise | undefined; - unsubscribeAll?: (...args: any[]) => Promise | undefined; - terminate: (...args: any[]) => boolean; - onmessage?: (...args: any[]) => void; - onerror?: (...args: any[]) => void; - onclose?: ((user: User) => void) | ((...args: any[]) => void); - [key: string]: any; -}; -export type ConnectionProps = { - connection: GraphNode | Graph | { - [key: string]: any; - } | string; - service?: string | Graph | Service; - source?: string; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type ConnectionInfo = { - connection: GraphNode | Graph | { - [key: string]: any; - }; - service?: string | Service | Graph; - _id: string; - source: string; - connectionType?: string; - connectionsKey?: string; - send?: (message: any, ...a: any[]) => any; - request?: (message: any, method?: any, ...a: any[]) => Promise | Promise[]; - post?: (route: any, args?: any, method?: string, ...a: any[]) => void; - run?: (route: any, args?: any, method?: string, ...a: any[]) => Promise | Promise[]; - subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | undefined; - unsubscribe?: (route: any, sub: number, ...arrayBuffer: any[]) => Promise | Promise[]; - terminate: (...a: any[]) => boolean; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type RouterOptions = { - graph?: { - [key: string]: Service | Graph | any | { - service: Service | Graph | any; - connections: string[] | { - [key: string]: any; - }; - config?: { - [key: string]: { - _id?: string; - source?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - [key: string]: any; - }; - }; - }; - }; - timeout?: number; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class Router extends Service { - name: string; - connections: { - [key: string]: ConnectionInfo; - }; - sources: { - [key: string]: { - [key: string]: ConnectionInfo; - }; - }; - services: { - [key: string]: Service; - }; - serviceConnections: { - [key: string]: { - [key: string]: { - [key: string]: any; - }; - }; - }; - users: { - [key: string]: User; - }; - userTimeout: number; - order: string[]; - constructor(options?: RouterOptions); - addUser: (info: { - _id: string; - } & { - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; - }, connections?: { - [key: string]: string | ConnectionInfo | ConnectionProps; - }, config?: { - [key: string]: { - [key: string]: any; - service: Service; - _id?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - }; - }, receiving?: boolean) => Promise; - removeUser(profile: string | User | { - _id: string; - [key: string]: any; - }, terminate?: boolean): boolean; - getConnection: (sourceId: string, hasMethod?: string, connectionId?: string) => User | ConnectionInfo | undefined; - getConnections: (sourceId: string, hasMethod?: string, props?: {}) => {}; - runConnection: (userId: string, method: 'run' | 'post' | 'subscribe' | 'unsubscribe' | 'terminate' | 'send' | 'request' | 'runAll' | 'postAll' | 'subscribeAll' | 'unsubscribeAll' | 'sendAll' | 'requestAll', args: any[], connectionId?: string) => Promise; - subscribeThroughConnection: (route: string, remoteRelay: string | ConnectionInfo, remoteEndpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; - addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string, autoRemove?: boolean) => ConnectionInfo; - removeConnection: (connection: string | ConnectionInfo | { - [key: string]: any; - _id: string; - }, terminate?: boolean) => boolean; - routeService: (service: Service, connections?: any, source?: string, order?: string[]) => void; - addServiceConnections: (service: Service | string, connectionsKey: any, source?: string) => {}; - openConnection: (service: string | Service, options: { - [key: string]: any; - }, source?: string, ...args: any[]) => Promise; - terminate: (connection: string | ConnectionInfo) => boolean; - routeConnections: (route: string, transmitter: string | ConnectionInfo, receiver: string | ConnectionInfo, ...args: any[]) => Promise; - setUserData: (user: string | User, data: string | { - [key: string]: any; - }) => boolean; -} -export declare function connectionHasId(connection: { - _id?: string; - [key: string]: any; -}, timeout?: number): Promise; diff --git a/src/extras/dist/services/utils.d.ts b/src/extras/dist/services/utils.d.ts deleted file mode 100644 index 9efee154..00000000 --- a/src/extras/dist/services/utils.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export declare let recursivelyStringifyFunctions: (obj: { - [key: string]: any; -}) => {}; -export declare function getFnParamNames(fn: any): any; -export declare let getFunctionHead: (methodString: any) => any; -export declare function parseFunctionFromText(method?: string): any; -export declare function reconstructObject(json?: string | { - [x: string]: any; -}): any; -export declare const stringifyWithCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyWithFunctionsAndCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyFast: (obj: any, space?: any) => string; diff --git a/src/extras/dist/services/worker/Worker.service.d.ts b/src/extras/dist/services/worker/Worker.service.d.ts deleted file mode 100644 index 9539bb89..00000000 --- a/src/extras/dist/services/worker/Worker.service.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import Worker from 'web-worker'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export type WorkerRoute = { - worker?: WorkerInfo; - workerUrl?: string | URL | Blob; - transferFunctions?: { - [key: string]: Function; - }; - transferClasses?: { - [key: string]: Function; - }; - parentRoute?: string; - portId?: string; - callback?: string; - stopped?: boolean; - blocking?: boolean; - init?: string; - initArgs?: any[]; - initTransfer?: any[]; -} & GraphNodeProperties & WorkerProps; -export type WorkerProps = { - worker?: WorkerInfo; - workerUrl?: string | URL | Blob; - url?: URL | string | Blob; - _id?: string; - port?: MessagePort; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - onclose?: (worker: Worker | MessagePort) => void; -}; -export type WorkerInfo = { - worker: Worker | MessagePort; - send: (message: any, transfer?: any) => void; - request: (message: any, method?: string, transfer?: any) => Promise; - post: (route: any, args?: any, method?: string, transfer?: any) => void; - run: (route: any, args?: any, method?: string, transfer?: any) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; - unsubscribe: (route: any, sub: number) => Promise; - start: (route?: any, portId?: string, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; - stop: (route?: string, portId?: string) => Promise; - workerSubs: { - [key: string]: { - sub: number | false; - route: string; - portId: string; - callback?: ((res: any) => void) | string; - blocking?: boolean; - }; - }; - terminate: () => boolean; - postMessage: (message: any, transfer?: any[]) => void; - graph: WorkerService; - _id: string; -} & WorkerProps & WorkerRoute; -export declare class WorkerService extends Service { - name: string; - workers: { - [key: string]: WorkerInfo; - }; - threadRot: number; - connections: any; - constructor(options?: ServiceOptions); - loadWorkerRoute: (node: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; - workerloader: any; - addDefaultMessageListener: () => void; - postMessage: (message: any, target: string, transfer?: Transferable[]) => void; - addWorker: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - open: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - close: () => void; - toObjectURL: (scriptTemplate: string) => string; - getTransferable(message: any): any; - transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: StructuredSerializeOptions) => any; - terminate: (worker: Worker | MessagePort | string | WorkerInfo) => boolean; - establishMessageChannel: (worker: Worker | string | MessagePort | WorkerInfo, worker2?: Worker | string | MessagePort | WorkerInfo) => string | false; - request: (message: ServiceMessage | any, workerId: string, transfer?: any, method?: string) => Promise; - runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number, getTransferable?: boolean) => any; - subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => number; - subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; - triggerSubscription: (route: string, workerId: string, result: any) => Promise; - pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, args?: any[], key?: any, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; - unpipeWorkers: (sourceRoute: string, sourceWorker: WorkerInfo | string, sub?: number) => Promise; -} diff --git a/src/extras/dist/src/core/EventHandler.d.ts b/src/extras/dist/src/core/EventHandler.d.ts deleted file mode 100644 index 2f00b243..00000000 --- a/src/extras/dist/src/core/EventHandler.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -export declare class EventHandler { - data: { - [key: string]: any; - }; - triggers: { - [key: string]: { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - }; - ctr: number; - constructor(data?: { - [key: string]: any; - }); - setState: (updateObj: { - [key: string]: any; - }) => { - [key: string]: any; - }; - setValue: (key: any, value: any) => void; - triggerEvent: (key: any, value: any) => void; - subscribeState: (onchange: (res: any) => void) => number; - unsubscribeState: (sub: number) => boolean; - subscribeEvent: (key: string, onchange: (res: any) => void, refObject?: { - [key: string]: any; - }, refKey?: string) => number; - unsubscribeEvent: (key: string, sub?: number) => boolean; - subscribeEventOnce: (key: string, onchange: (res: any) => void) => any; - getEvent: (key: any, sub?: any) => { - [key: string]: any; - sub: number; - onchange: Function; - } | { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - getSnapshot: () => void; - onRemoved: (trigger: { - sub: number; - onchange: Function; - }) => void; -} diff --git a/src/extras/dist/src/core/Graph.d.ts b/src/extras/dist/src/core/Graph.d.ts deleted file mode 100644 index f77b09bd..00000000 --- a/src/extras/dist/src/core/Graph.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { EventHandler } from "./EventHandler"; -export declare const state: EventHandler; -export type GraphNodeProperties = { - __props?: Function | { - [key: string]: any; - } | GraphNodeProperties | GraphNode; - __operator?: ((...args: any[]) => any) | string; - __children?: { - [key: string]: any; - }; - __listeners?: { - [key: string]: true | string | ((result: any) => void) | { - __callback: string | ((result: any) => void) | true; - subInput?: boolean; - [key: string]: any; - }; - } | { - [key: string]: ((result: any) => void) | true | string; - }; - __onconnected?: ((node: any) => void | ((node: any) => void)[]); - __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); - __node?: { - tag?: string; - state?: EventHandler; - [key: string]: any; - }; - __args?: any[]; - __callable?: boolean; - [key: string]: any; -}; -export type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; -export type Roots = { - [key: string]: any; -}; -export type GraphOptions = { - roots?: Roots; - loaders?: { - [key: string]: Loader | { - init?: Loader; - connected?: (node: any) => void; - disconnected?: (node: any) => void; - }; - }; - state?: EventHandler; - mapGraphs?: false; - [key: string]: any; -}; -export type argObject = { - __input?: string | ((...args: any[]) => any); - __callback: string | ((...args: any[]) => any); - __args?: any[]; - __output?: string | argObject | ((...args: any[]) => any); -}; -export type Listener = { - __callback?: string; - __args?: (argObject | Function | string)[]; - sub: number; - node: GraphNode; - graph: Graph; - source?: string; - key?: string; - target?: string; - tkey?: string; - arguments?: Function[]; - subInput?: boolean; - onchange: Function; -}; -export declare class Callable extends Function { - __bound: Callable; - __call: ((...args: any[]) => any); - [key: string]: any; - constructor(); -} -export declare class GraphNode { - __node: { - tag: string; - unique: string; - state: EventHandler; - [key: string]: any; - }; - __children?: { - [key: string]: GraphNode; - }; - __parent?: Graph | GraphNode; - __operator?: any; - __listeners?: any; - __props?: any; - __args: any[]; - [key: string]: any; - constructor(properties: GraphNodeProperties, parent?: { - [key: string]: any; - }, graph?: Graph); - get __graph(): any; - set __graph(graph: any); - __setProperties: (properties: any, parent: any, graph: any) => void; - __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, target?: string, tkey?: string, args?: any[], callbackStr?: string) => any; - __unsubscribe: (sub?: number, key?: string, unsubInput?: boolean) => boolean; - __setOperator: (fn: (...args: any[]) => any) => any; - __addLocalState: (props?: { - [key: string]: any; - }, key?: string) => void; - __proxyObject: (obj: any) => void; - __addOnconnected(callback: (node: any) => void): void; - __addOndisconnected(callback: (node: any) => void): void; - __callConnected(node?: this): void; - __callDisconnected(node?: this): void; -} -export declare class Graph { - [key: string]: any; - __node: { - tag: string; - unique: string; - state: EventHandler; - nodes: Map; - roots: { - [key: string]: any; - }; - mapGraphs?: boolean; - [key: string]: any; - }; - constructor(options?: GraphOptions); - init: (options?: GraphOptions) => void; - load: (roots: { - [key: string]: any; - }, overwrite?: boolean) => { - [key: string]: any; - }; - setLoaders: (loaders: { - [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, props: any, key: string) => void; - }, replace?: boolean) => any; - runLoaders: (node: any, parent: any, properties: any, key: any) => void; - add: (properties: any, parent?: GraphNode | string, overwrite?: boolean) => GraphNode; - recursiveSet: (originCpy: any, parent: any, listeners: any, origin: any, overwrite?: boolean) => any; - remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; - run: (node: string | GraphNode, ...args: any[]) => any; - /** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners: (listeners: { - [key: string]: { - [key: string]: any; - }; - }) => void; - clearListeners: (node: GraphNode | string, listener?: string) => void; - get: (tag: string) => any; - getByUnique: (unique: string) => any; - set: (tag: string, node: GraphNode) => Map; - delete: (tag: string) => boolean; - list: () => string[]; - getListener: (nodeTag: string, key?: string, sub?: number) => Listener; - getProps: (node: GraphNode | string, getInitial?: boolean) => void; - subscribe: (nodeEvent: GraphNode | string, onEvent: string | GraphNode | ((...res: any) => void), args?: any[], key?: string | undefined, subInput?: boolean, target?: string | GraphNode, tkey?: string) => number; - unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; - setState: (update: { - [key: string]: any; - }) => void; -} -export declare function getAllProperties(obj: any): any[]; -export declare function instanceObject(obj: any): any; -export declare function isNativeClass(thing: any): boolean; -export declare function isFunction(x: any): "function" | "class" | "async" | "arrow" | ""; -export declare let getCallbackFromString: (a: any, graph: any) => (...inp: any[]) => any; -export declare const wrapArgs: (callback: any, argOrder: any, graph: any) => { - __callback: any; - __args: any[]; -}; diff --git a/src/extras/dist/src/extras/algorithms/accel_gyro.d.ts b/src/extras/dist/src/extras/algorithms/accel_gyro.d.ts deleted file mode 100644 index c98cb706..00000000 --- a/src/extras/dist/src/extras/algorithms/accel_gyro.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const accel_gyro: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/beat_detect.d.ts b/src/extras/dist/src/extras/algorithms/beat_detect.d.ts deleted file mode 100644 index bc3fb33d..00000000 --- a/src/extras/dist/src/extras/algorithms/beat_detect.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const beat_detect: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/blink.d.ts b/src/extras/dist/src/extras/algorithms/blink.d.ts deleted file mode 100644 index 4743de8d..00000000 --- a/src/extras/dist/src/extras/algorithms/blink.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const blink_detect: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/buffering.d.ts b/src/extras/dist/src/extras/algorithms/buffering.d.ts deleted file mode 100644 index 71e1efac..00000000 --- a/src/extras/dist/src/extras/algorithms/buffering.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const circularBuffer2d: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/coherence.d.ts b/src/extras/dist/src/extras/algorithms/coherence.d.ts deleted file mode 100644 index 0b35b736..00000000 --- a/src/extras/dist/src/extras/algorithms/coherence.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const coherence: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/dft.d.ts b/src/extras/dist/src/extras/algorithms/dft.d.ts deleted file mode 100644 index ccd239c3..00000000 --- a/src/extras/dist/src/extras/algorithms/dft.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const dft: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/index.d.ts b/src/extras/dist/src/extras/algorithms/index.d.ts deleted file mode 100644 index c3ec990e..00000000 --- a/src/extras/dist/src/extras/algorithms/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -declare const algorithms: { - [key: string]: GraphNodeProperties; -}; -export { algorithms }; diff --git a/src/extras/dist/src/extras/algorithms/index.gpu.d.ts b/src/extras/dist/src/extras/algorithms/index.gpu.d.ts deleted file mode 100644 index fcfc3ef0..00000000 --- a/src/extras/dist/src/extras/algorithms/index.gpu.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare const gpualgorithms: { - dft: import("../../core/Graph").GraphNodeProperties; - coherence: import("../../core/Graph").GraphNodeProperties; -}; diff --git a/src/extras/dist/src/extras/algorithms/rms.d.ts b/src/extras/dist/src/extras/algorithms/rms.d.ts deleted file mode 100644 index 39ad84d0..00000000 --- a/src/extras/dist/src/extras/algorithms/rms.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -export declare const rms: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/util/ArrayManip.d.ts b/src/extras/dist/src/extras/algorithms/util/ArrayManip.d.ts deleted file mode 100644 index b6d5e3ad..00000000 --- a/src/extras/dist/src/extras/algorithms/util/ArrayManip.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export declare class ArrayManip { - static autoscale(array: any, lineIdx?: number, nLines?: number, centerZero?: boolean, ymin?: number, ymax?: number, clamp?: boolean): any; - static genTimestamps(ct: any, sps: any): any[]; - static absmax(array: any): number; - static downsample(array: any, fitCount: any, scalar?: number): any; - static upsample(array: any, fitCount: any, scalar?: number): any[]; - static interpolate(array: number[], fitCount: number, scalar?: number): any; - static HSLToRGB(h: any, s: any, l: any, scalar?: number): [number, number, number]; - static circularBuffer(arr: any[], newEntries: any[]): any[]; - static reformatData(data: { - [key: string]: number[] | number | { - values: number[] | number; - [key: string]: any; - }; - } | string | ((number | number[])[]) | number, key?: string): string | number | { - [key: string]: number | number[] | { - [key: string]: any; - values: number[] | number; - }; - } | (number | number[])[]; - static padTime(data: number[], //new data, assumed to be sequential between a gap - lastValue: number, //the last data point before the gap - time: number, //interval that's passed to determine slope between samples - targetFit: number): number[]; - static interpolateForTime(data: number[], //new data, assumed to be evenly spread over a time interval - time: number, //the time interval passed (s) - targetSPS: number): any; - static bufferValues: (objects: { - [key: string]: { - [key: string]: any; - }; - }, property: string, keys?: string[] | { - [key: string]: any; - }, buffer?: ArrayBufferLike) => ArrayBufferLike; - isTypedArray(x: any): boolean; - recursivelyAssign: (target: any, obj: any) => any; - spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; -} diff --git a/src/extras/dist/src/extras/algorithms/util/BiquadFilters.d.ts b/src/extras/dist/src/extras/algorithms/util/BiquadFilters.d.ts deleted file mode 100644 index fd1d4fc9..00000000 --- a/src/extras/dist/src/extras/algorithms/util/BiquadFilters.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -export type FilterSettings = { - sps: number; - useSMA4?: boolean; - useNotch50?: boolean; - useNotch60?: boolean; - useLowpass?: boolean; - lowpassHz?: number; - useBandpass?: boolean; - bandpassLower?: number; - bandpassUpper?: number; - useDCBlock?: boolean; - DCBresonance?: number; - useScaling?: boolean; - scalar?: number; - trimOutliers?: boolean; - outlierTolerance?: number; -}; -export declare class BiquadChannelFilterer { - idx: number; - sps: number; - bandpassLower?: number; - bandpassUpper?: number; - useSMA4?: boolean; - last4?: number[]; - filtered: number; - trimOutliers?: boolean; - outlierTolerance?: number; - useNotch50?: boolean; - useNotch60?: boolean; - useLowpass?: boolean; - lowpassHz?: number; - useBandpass?: boolean; - useDCBlock?: boolean; - DCBresonance?: number; - useScaling?: boolean; - scalar?: number; - notch50?: any; - notch60?: any; - lp1?: any; - bp1?: any; - dcb?: any; - constructor(options?: FilterSettings); - reset(sps?: number): void; - setBandpass(bandpassLower?: number, bandpassUpper?: number, sps?: number): void; - apply(latestData?: number): number; -} -export declare class Biquad { - type: string; - freq: number; - sps: number; - Q: number; - dbGain: number; - a0: number; - a1: number; - a2: number; - b0: number; - b1: number; - b2: number; - x1: number; - x2: number; - y1: number; - y2: number; - constructor(type: 'lowpass' | 'highpass' | 'bandpass' | 'notch' | 'peak' | 'lowshelf' | 'highshelf', freq: number, sps: number, Q?: number, dbGain?: number); - lowpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - highpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - bandpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - notch(A: any, sn: any, cs: any, alpha: any, beta: any): void; - peak(A: any, sn: any, cs: any, alpha: any, beta: any): void; - lowshelf(A: any, sn: any, cs: any, alpha: any, beta: any): void; - highshelf(A: any, sn: any, cs: any, alpha: any, beta: any): void; - applyFilter(signal_step: any): number; - zResult(freq: any): number; - static calcCenterFrequency(freqStart: any, freqEnd: any): number; - static calcBandwidth(freqStart: any, freqEnd: any): number; - static calcBandpassQ(frequency: any, bandwidth: any, resonance?: number): number; - static calcNotchQ(frequency: any, bandwidth: any, resonance?: number): number; -} -export declare class DCBlocker { - r: number; - x1: number; - x2: number; - y1: number; - y2: number; - constructor(r?: number); - applyFilter(signal_step: any): number; -} -export declare const makeNotchFilter: (frequency: any, sps: any, bandwidth: any) => Biquad; -export declare const makeBandpassFilter: (freqStart: any, freqEnd: any, sps: any, resonance?: number) => Biquad; diff --git a/src/extras/dist/src/extras/algorithms/util/ByteParser.d.ts b/src/extras/dist/src/extras/algorithms/util/ByteParser.d.ts deleted file mode 100644 index 178a7329..00000000 --- a/src/extras/dist/src/extras/algorithms/util/ByteParser.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { ArrayManip } from "./ArrayManip"; -export declare class ByteParser extends ArrayManip { - static codes: { - '\\n': number; - '\\r': number; - '\\t': number; - '\\s': number; - '\\b': number; - '\\f': number; - '\\': number; - }; - static toDataView(value: string | number | ArrayBufferLike | DataView | number[]): DataView; - static searchBuffer(buffer: number[] | ArrayBuffer, searchString: Uint8Array, limit?: number): any[]; - static bytesToInt16(x0: number, x1: number): number; - static bytesToUInt16(x0: number, x1: number): number; - static Uint16ToBytes(y: number): number[]; - static bytesToInt24(x0: number, x1: number, x2: number): number; - static bytesToUInt24(x0: number, x1: number, x2: number): number; - static Uint24ToBytes(y: number): number[]; - static bytesToInt32(x0: number, x1: number, x2: number, x3: number): number; - static bytesToUInt32(x0: number, x1: number, x2: number, x3: number): number; - static Uint32ToBytes(y: number): number[]; - static get2sCompliment(val: number, nbits: number): number; - static getSignedInt(...args: number[]): number; - static asUint8Array(input: any): Uint8Array; - static boyerMoore(patternBuffer: any): any; - static struct(format: string): Readonly<{ - unpack: (arrb: any) => any[]; - pack: (...values: any[]) => ArrayBuffer; - unpack_from: (arrb: any, offs: any) => any[]; - pack_into: (arrb: any, offs: any, ...values: any[]) => void; - iter_unpack: (arrb: any) => Generator; - format: string; - size: number; - }>; -} diff --git a/src/extras/dist/src/extras/ecs/ECS.systems.d.ts b/src/extras/dist/src/extras/ecs/ECS.systems.d.ts deleted file mode 100644 index 34de4406..00000000 --- a/src/extras/dist/src/extras/ecs/ECS.systems.d.ts +++ /dev/null @@ -1,383 +0,0 @@ -import { Entity } from "../../services/ecs/ECS.service"; -export declare const Systems: { - collision: { - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __node: { - tag: string; - }; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - collisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionEnabled?: boolean; - collisionType: 'sphere' | 'box' | 'point'; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionEnabled?: boolean; - collisionType: 'sphere' | 'box' | 'point'; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => number | false; - sphereCollisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - boxCollisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => boolean; - sphereBoxCollisionCheck: (sphere: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, box: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - isPointInsideSphere: (point: { - x: number; - y: number; - z: number; - }, sphere: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - isPointInsideBox: (point: { - x: number; - y: number; - z: number; - }, box: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => boolean; - closestPointOnLine: (point: { - x: number; - y: number; - z: number; - }, lineStart: { - x: number; - y: number; - z: number; - }, lineEnd: { - x: number; - y: number; - z: number; - }) => { - x: number; - y: number; - z: number; - }; - closestPointOnPolygon: (point: { - x: number; - y: number; - z: number; - }, t0: { - x: number; - y: number; - z: number; - }, t1: { - x: number; - y: number; - z: number; - }, t2: { - x: number; - y: number; - z: number; - }) => { - [key: string]: number; - }; - calcNormal: (t0: { - x: number; - y: number; - z: number; - }, t1: { - x: number; - y: number; - z: number; - }, t2: { - x: number; - y: number; - z: number; - }, positive?: boolean) => {}; - dot: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; - makeVec(p1: { - x: number; - y: number; - z: number; - }, p2: { - x: number; - y: number; - z: number; - }): { - x: number; - y: number; - z: number; - }; - vecadd: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecsub: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecmul: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecdiv: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecscale: (v1: { - [key: string]: number; - }, scalar: number) => { - [key: string]: number; - }; - distance: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; - magnitude: (v: { - [key: string]: number; - }) => number; - normalize: (v: { - [key: string]: number; - }) => {}; - distance3D(v1: { - x: number; - y: number; - z: number; - }, v2: { - x: number; - y: number; - z: number; - }): number; - cross3D(v1: { - x: number; - y: number; - z: number; - }, v2: { - x: number; - y: number; - z: number; - }): { - x: number; - y: number; - z: number; - }; - nearestNeighborSearch(entities: { - [key: string]: Entity; - }, isWithinRadius?: number): {}; - generateBoundingVolumeTree(entities: { - [key: string]: Entity; - }, mode?: 'octree' | 'aabb', withinRadius?: number, minEntities?: number): any; - }; - collider: { - lastTime: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - checkBoundingBox: (entity: any) => void; - resolveBoxCollision: (body1: Entity, box: Entity, negate?: boolean) => void; - resolveSphereCollisions: (entity1: Entity, entity2: Entity, dist?: number) => void; - }; - nbody: { - lastTime: number; - G: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - attract: (body1: any, body2: any, dist?: number, G?: any, vecn?: { - x: number; - y: number; - z: number; - }) => void; - }; - boid: { - lastTime: number; - defaultAnchor: { - x: number; - y: number; - z: number; - mul: number; - }; - setupEntities: (entities: any) => any; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - }; - movement: { - __node: { - tag: string; - }; - lastTime: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => void; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - }; -}; diff --git a/src/extras/dist/src/extras/gpu/GPU.service.d.ts b/src/extras/dist/src/extras/gpu/GPU.service.d.ts deleted file mode 100644 index 547ea325..00000000 --- a/src/extras/dist/src/extras/gpu/GPU.service.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Service } from "../../services/Service"; -import { gpuUtils } from 'gpujsutils'; -export declare class GPUService extends Service { - gpu: gpuUtils; - constructor(options?: any); - addFunc: (fn: string | Function) => void; - addKernel: (name: string, fn: string | Function, options?: any) => void; - combineKernels: (name: string, fs: (string | Function)[], ckrnl?: () => void) => void; - callKernel: (name: string, ...args: any[]) => void; - dft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; - multidft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; - multidftbandpass: (buffered: number[][], nSeconds: number, freqStart: number, freqEnd: number, scalar?: number) => any; - coherence: (buffered: number[][], nSeconds: number, freqStart: number, freqEnd: number) => any[]; -} diff --git a/src/extras/dist/src/extras/index.gpu.services.d.ts b/src/extras/dist/src/extras/index.gpu.services.d.ts deleted file mode 100644 index a1d3d930..00000000 --- a/src/extras/dist/src/extras/index.gpu.services.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './gpu/GPU.service'; -export { gpualgorithms } from './algorithms/index.gpu'; diff --git a/src/extras/dist/src/extras/index.services.d.ts b/src/extras/dist/src/extras/index.services.d.ts deleted file mode 100644 index 4c38107e..00000000 --- a/src/extras/dist/src/extras/index.services.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './struct/Struct.frontend'; -export * from './struct/Struct.backend'; -export * from './struct/genTimestamps'; -export * from './ecs/ECS.systems'; -export * from './webgl-plot/webglplot.routes'; -export { algorithms } from './algorithms/index'; diff --git a/src/extras/dist/src/extras/struct/Struct.backend.d.ts b/src/extras/dist/src/extras/struct/Struct.backend.d.ts deleted file mode 100644 index 278d1ebe..00000000 --- a/src/extras/dist/src/extras/struct/Struct.backend.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { ObjectId } from "./datastructures/bson.cjs"; -import { AuthorizationStruct, GroupStruct, ProfileStruct } from "./datastructures/types"; -import { TimeSpecifier } from './genTimestamps'; -import { Service } from "../../services/Service"; -import { User } from '../../services/router/Router'; -export declare const toObjectId: (str: any) => any; -export declare const getStringId: (mongoid: string | ObjectId) => any; -type CollectionsType = { - [x: string]: CollectionType; -}; -type CollectionType = any | { - instance?: any; - reference: { - [key: string]: any; - }; -}; -export declare class StructBackend extends Service { - name: string; - debug: boolean; - db: any; - users: { - [key: string]: User; - }; - collections: CollectionsType; - mode: 'local' | 'mongo' | string; - useAuths: boolean; - useAccessTokens: boolean; - useRefreshTokens: boolean; - accessTokens: Map; - refreshTokens: Map; - constructor(options?: any, dboptions?: { - users?: { - [key: string]: User; - }; - mode?: 'local' | 'mongo' | string; - db?: any; - collections?: CollectionsType; - useAuths?: boolean; - debug?: boolean; - useAccessTokens?: boolean; - useRefreshTokens?: boolean; - }); - initDB: (dboptions: any) => void; - query: (requestingUserId: string, collection?: any, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - getUser: (requestingUserId: string, lookupId: string, basicInfo?: boolean, token?: string) => Promise; - setUser: (requestingUserId: string, struct: Partial, token: string) => Promise; - getUsersByIds: (requestingUserId: string, userIds: string[], basicInfo?: boolean) => Promise; - getUsersByRole: (requestingUserId: string, role: string) => Promise; - deleteUser: (requestingUserId: string, userId: string, deleteData?: boolean, token?: string) => Promise; - setData: (requestingUserId: string, structs: any[], notify?: boolean, token?: string) => Promise; - getData: (requestingUserId: string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number, token?: string) => Promise; - getDataByIds: (requestingUserId: string, structIds: string[], ownerId?: string, collection?: string, token?: string) => Promise; - getAllData: (requestingUserId: string, ownerId: string, excludedCollections?: string[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - deleteData: (requestingUserId: string, structIds: string[], token?: string) => Promise; - getUserGroups: (requestingUserId: string, userId?: string, groupId?: string) => Promise; - deleteGroup: (requestingUserId: string, groupId: string, token?: string) => Promise; - getAuthorizations: (requestingUserId: string, ownerId?: string, authId?: string, token?: string) => Promise; - deleteAuthorization: (requestingUserId: string, authId: string, token?: string) => Promise; - getToken: (user: Partial) => string; - notificationStruct: (parentStruct?: any) => { - structType: string; - timestamp: number; - _id: string; - note: string; - alert: boolean; - ownerId: string; - parentUserId: string; - parent: { - structType: any; - _id: any; - }; - }; - checkToNotify: (user: Partial, structs?: any[], mode?: string) => Promise; - queryMongo: (user: Partial, collection: string, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - setMongoData: (user: Partial, structs?: any[], notify?: boolean, token?: string) => Promise; - setMongoUser: (user: Partial, struct: Partial, token?: string) => Promise; - setGroup: (user: Partial, struct: any, mode?: string, token?: string) => Promise; - getMongoUser: (user: Partial, info?: string, requireAuth?: boolean, basicInfo?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - queryUsers: (user: Partial, info?: string, limit?: number, skip?: number, requireAuth?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - getMongoUsersByIds: (user: Partial, userIds?: any[], basicInfo?: boolean) => Promise; - getMongoUsersByRole: (user: Partial, role: string) => Promise; - getMongoDataByIds: (user: Partial, structIds: string[], ownerId: string | undefined, collection: string | undefined, token?: string) => Promise; - getMongoData: (user: Partial, collection: string | undefined, ownerId: string | undefined, dict?: any | undefined, limit?: number, skip?: number, token?: string) => Promise; - getAllUserMongoData: (user: Partial, ownerId: any, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - getMongoDataByRefs: (user: Partial, structRefs?: any[], token?: string) => Promise; - getMongoAuthorizations: (user: Partial, ownerId?: any, authId?: string, token?: string) => Promise; - getMongoGroups: (user: Partial, userId?: any, groupId?: string) => Promise; - deleteMongoData: (user: Partial, structRefs?: any[], token?: string) => Promise; - deleteMongoUser: (user: Partial, userId: any, deleteData?: boolean, token?: string) => Promise; - deleteMongoGroup: (user: Partial, groupId: any, token?: string) => Promise; - deleteMongoAuthorization: (user: Partial, authId: any, token?: string) => Promise; - setAuthorization: (user: Partial, authStruct: any, token?: string) => Promise; - checkAuthorization: (user: string | Partial | { - _id: string; - }, struct: any, request?: string, token?: string) => Promise; - wipeDB: () => Promise; - overwriteLocalData: (structs: any) => void; - setLocalData: (structs: any) => void; - getLocalData: (collection: any, query?: any) => any; - deleteLocalData: (struct: any) => boolean; -} -export {}; diff --git a/src/extras/dist/src/extras/struct/Struct.frontend.d.ts b/src/extras/dist/src/extras/struct/Struct.frontend.d.ts deleted file mode 100644 index 3b0ef8dc..00000000 --- a/src/extras/dist/src/extras/struct/Struct.frontend.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { DataTablet } from './datastructures/index'; -import { Data, ProfileStruct, AuthorizationStruct, GroupStruct, DataStruct, EventStruct, ChatroomStruct, CommentStruct, Struct } from './datastructures/types'; -import { TimeSpecifier } from './genTimestamps'; -import { Service } from '../../services/Service'; -import { User } from '../../services/router/Router'; -import { GraphNodeProperties } from '../../core/Graph'; -export declare const randomId: (prefix?: any) => string; -export declare const pseudoObjectId: (m?: Math, d?: DateConstructor, h?: number, s?: (s: any) => string) => string; -export type StructFrontendProps = { - useAccessTokens?: boolean; - useRefreshTokens?: boolean; -} & GraphNodeProperties; -export declare class StructFrontend extends Service { - name: string; - currentUser: User; - tablet: DataTablet; - collections: Map; - id: string; - useAccessTokens: boolean; - useRefreshTokens: boolean; - constructor(options?: any, user?: Partial); - getToken(user: Partial): string; - setupUser: (userinfo: Partial, callback?: (currentUser: any) => void) => Promise; - baseServerCallback: (data: any) => void; - structNotification: () => void; - structDeleted: (struct: { - _id: string; - structType: string; - }) => void; - onResult: (data: any) => void; - randomId(tag?: string): string; - /** - let struct = { - _id: randomId(structType+'defaultId'), //random id associated for unique identification, used for lookup and indexing - structType: structType, //this is how you will look it up by type in the server - ownerId: parentUser?._id, //owner user - timestamp: Date.now(), //date of creation - parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) - } - */ - addStruct: (structType?: string, props?: any, parentUser?: { - [key: string]: any; - }, parentStruct?: { - [key: string]: any; - }, updateServer?: boolean) => Promise; - getUser: (info?: string | number, basicInfo?: boolean, callback?: (data: any) => void) => Promise<{ - user: ProfileStruct; - groups: GroupStruct[]; - authorizations: AuthorizationStruct[]; - }>; - queryUsers: (info: string, skip?: number, limit?: number, callback?: (data: any) => void) => Promise; - getUsers: (ids?: (string | number)[], basicInfo?: boolean, callback?: (data: any) => void) => Promise; - getUsersByRole: (userRole: string, callback?: (data: any) => void) => Promise; - getAllUserData: (ownerId: string | number, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], callback?: (data: any) => void) => Promise; - query: (collection: string, mongoQuery?: {}, findOne?: boolean, skip?: number, callback?: (data: any) => void) => Promise; - getDataByTimeRange(collection: any, timeRange?: [number | TimeSpecifier, number | TimeSpecifier], ownerId?: string | number | undefined, limit?: number, skip?: number, key?: string): Promise; - getData: (collection: string, ownerId?: string | number | undefined, searchDict?: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - getDataByIds: (structIds?: any[], ownerId?: string | number | undefined, collection?: string | undefined, callback?: (data: any) => void) => Promise; - getStructParentData: (struct: Struct, callback?: (data: any) => void) => Promise; - setUser: (userStruct: ProfileStruct, callback?: (data: any) => void) => Promise; - checkUserToken: (usertoken: any, user?: User, callback?: (data: any) => void) => Promise; - setData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; - updateServerData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; - deleteData: (structs?: any[], callback?: (data: any) => void) => Promise; - deleteUser: (userId?: string, deleteData?: boolean, callback?: (data: any) => void) => Promise; - setGroup: (groupStruct: GroupStruct, callback?: (data: any) => void) => Promise; - getUserGroups: (userId?: string, groupId?: string, callback?: (data: any) => void) => Promise; - deleteGroup: (groupId: any, callback?: (data: any) => void) => Promise; - setAuthorization: (authorizationStruct: AuthorizationStruct, callback?: (data: any) => void) => Promise; - getAuthorizations: (userId?: string, authorizationId?: string, callback?: (data: any) => void) => Promise; - deleteAuthorization: (authorizationId: any, callback?: (data: any) => void) => Promise; - checkForNotifications: (userId?: string) => Promise; - resolveNotifications: (notifications?: any[], pull?: boolean, user?: Partial) => Promise; - setAuthorizationsByGroup: (user?: User) => Promise; - deleteRoom: (roomStruct: any) => Promise; - deleteComment: (commentStruct: any) => Promise; - getUserDataByAuthorization: (authorizationStruct: any, collection: any, searchDict: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - getUserDataByAuthorizationGroup: (groupId: string, collection: any, searchDict: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - overwriteLocalData(structs: any): void; - setLocalData(structs: any): void; - getLocalData(collection: any, query?: any): any; - getLocalUserPeerIds: (user?: User) => any; - getLocalReplies(struct: any): any; - hasLocalAuthorization(otherUserId: any, ownerId?: string): any; - deleteLocalData(structs: Struct[]): boolean; - deleteStruct(struct: Struct): boolean; - stripStruct(struct: Struct): Struct; - createStruct(structType: string, props: { - [key: string]: any; - }, parentUser?: User, parentStruct?: Struct): any; - userStruct(props?: Partial, currentUser?: boolean): ProfileStruct; - authorizeUser: (parentUser: Partial, authorizerUserId?: string, authorizerUserName?: string, authorizedUserId?: string, authorizedUserName?: string, authorizations?: {}, structs?: {}, excluded?: {}, groups?: {}, expires?: boolean) => Promise; - addGroup: (parentUser: Partial, name?: string, details?: string, admins?: {}, peers?: {}, clients?: {}, updateServer?: boolean) => Promise; - dataObject(data?: any, type?: string, timestamp?: string | number): { - type: string; - data: any; - timestamp: string | number; - }; - addData: (parentUser: Partial, author?: string, title?: string, type?: string, data?: string | Data[], expires?: boolean, updateServer?: boolean) => Promise; - addEvent: (parentUser: Partial, author?: string, event?: string | number, notes?: string, startTime?: string | number, endTime?: string | number, grade?: string | number, value?: any, units?: string, location?: any, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; - addChatroom: (parentUser: Partial, authorId?: string, message?: string, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; - addComment: (parentUser: Partial, roomStruct?: { - _id: string; - users: any[]; - comments: any[]; - }, replyTo?: { - _id: string; - replies: any[]; - }, authorId?: string, message?: string, attachments?: string | Data[], updateServer?: boolean) => Promise; -} diff --git a/src/extras/dist/src/extras/struct/datastructures/DataStructures.d.ts b/src/extras/dist/src/extras/struct/datastructures/DataStructures.d.ts deleted file mode 100644 index 3da6e206..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/DataStructures.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -import * as types from './types'; -export declare function Struct(structType?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.Struct; -export declare const eegCoordinates: { - [x: string]: number[]; -}; -export declare function setCoordinate(channelDict: any, assignTo?: {}): any; -export declare function EEGCoordinates(channelDicts?: [], genCoherenceMap?: boolean): types.EEGStruct[]; -export declare function FrequencyBandsStruct(additionalBands?: types.FrequencyBandNames[], //add whatever tags -assignTo?: {}): types.FrequencyBandsStruct; -export declare function EEGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EEGStruct; -export declare function CoherenceStruct(coords?: { - 0: types.EEGStruct; - 1: types.EEGStruct; -}, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.CoherenceStruct; -export declare function CoherenceMap(opts?: { - channelDicts: any[]; - taggedOnly?: boolean; -}, _?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.CoherenceStruct[]; -export declare function FNIRSStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.FNIRSStruct; -export declare function IMUStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.IMUStruct; -export declare function EyeTrackerStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EyeTrackerStruct; -export declare function ECGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ECGStruct; -export declare function EDAStruct(_?: string, __?: {}, ___?: { - _id: string; -}, ____?: { - structType: string; - _id: string; -}): void; -export declare function PPGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.FNIRSStruct; -export declare function HRVStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ECGStruct; -export declare function EMGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EEGStruct; -export declare function ProfileStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ProfileStruct; -export declare function AuthorizationStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.AuthorizationStruct; -export declare function GroupStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.GroupStruct; -export declare function Data(type: string, data: any): { - type: string; - data: any; - timestamp: number; -}; -export declare function DataStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.DataStruct; -export declare function EventStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.EventStruct; -export declare function ChatroomStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.ChatroomStruct; -export declare function CommentStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.CommentStruct; -export declare function NotificationStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.NotificationStruct; -export declare function ScheduleStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.ScheduleStruct; -export declare function DateStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.DateStruct; -export declare const structRegistry: { - Struct: typeof Struct; - EEGStruct: typeof EEGStruct; - FNIRSStruct: typeof FNIRSStruct; - CoherenceStruct: typeof CoherenceStruct; - CoherenceMap: typeof CoherenceMap; - FrequencyBandsStruct: typeof FrequencyBandsStruct; - IMUStruct: typeof IMUStruct; - EyeTrackerStruct: typeof EyeTrackerStruct; - ECGStruct: typeof ECGStruct; - EDAStruct: typeof EDAStruct; - PPGStruct: typeof PPGStruct; - HRVStruct: typeof HRVStruct; - EMGStruct: typeof EMGStruct; - ProfileStruct: typeof ProfileStruct; - AuthorizationStruct: typeof AuthorizationStruct; - GroupStruct: typeof GroupStruct; - DataStruct: typeof DataStruct; - EventStruct: typeof EventStruct; - ChatroomStruct: typeof ChatroomStruct; - CommentStruct: typeof CommentStruct; - NotificationStruct: typeof NotificationStruct; - ScheduleStruct: typeof ScheduleStruct; - DateStruct: typeof DateStruct; -}; diff --git a/src/extras/dist/src/extras/struct/datastructures/DataTablet.d.ts b/src/extras/dist/src/extras/struct/datastructures/DataTablet.d.ts deleted file mode 100644 index 967adeae..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/DataTablet.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { ArbitraryObject, Struct } from './types'; -export declare class DataTablet { - workerId: any; - id: any; - threaded: boolean; - workers: any; - DS: any; - collections: Map; - data: any; - rolloverLimit: number; - dataSorts: Map; - watches: any; - constructor(props?: {}); - randomId(tag?: string): string; - setLocalData(structs: (Partial)[] | (Partial)): void; - getLocalData(collection: string, query: any): any; - onCollectionSet: (type: any, collection: any) => void; - runSort(key: string, dataObj?: {}, newdata?: any[], tablet?: this): any; - /** - * Unsorted data structs come in with a minimum 'structType' and 'timestamp' set of values. - * - * If a sort key matches the structType or dataType (from a data struct.data array), - * it can return a modified struct or push to the newdata array with a set of newly made structs. - * Return undefined to process the input data by default structType/dataType and timestamp into the tablet, so you can do this - * plus split up additional structs or processed structs into each other. This is intentionally vague until we refine this idea into clearer hooks. - * The newdata array accumulates all of the data structs supplied on a sort pass which gets sent to this.onSorted() at the end of the sorting pass. - */ - setSort(key: string | string[], response?: (data: any, newdata?: any[], tablet?: this) => void): void; - getSort(key: string): any; - checkWatches(sorted?: ArbitraryObject): void; - /** - * - pass the sorted structure to the accumulator object which is just an empty object you can do whatever with - * - ondata checks the data if it's relevant and keeps a record via the accumulator - * - if the accumlator condition is satisfied, return true which triggers ontrigger(accum), else return a falsey value - * - ontrigger function then is passed the accumulator object to do whatever with, - * e.g. supply it to an 'alert' struct, set alert:true, and data:accum, and update the server to notify any connected peers. - */ - setWatch(name: string, ownerId: string | undefined, ondata?: (sorted: any, accum: any, ownerId: string) => boolean, ontrigger?: (accum: any) => void): void; - getWatch(name: string): any; - sortStructsIntoTable(datastructs?: Struct[]): Promise; - onUpdate(_: any, __: any, ___?: any): void; - onSorted(_?: any[]): void; - getDataByTimestamp(timestamp: number, ownerId: string): any; - getDataByTimeRange(begin: number, end: number, type: string, ownerId: string): ArbitraryObject; - getDataByType(type: string, timestamp: number, ownerId: string): any; - filterSleepResults(unfiltered?: ArbitraryObject): ArbitraryObject; - sortObjectByPropName(object: ArbitraryObject): ArbitraryObject; - checkRollover(collection: string, limit?: number): boolean; -} diff --git a/src/extras/dist/src/extras/struct/datastructures/bson.d.cts b/src/extras/dist/src/extras/struct/datastructures/bson.d.cts deleted file mode 100644 index 2efd64df..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/bson.d.cts +++ /dev/null @@ -1,419 +0,0 @@ -declare var bson: Readonly<{ - __proto__: any; - Code: typeof Code; - BSONSymbol: typeof BSONSymbol; - DBRef: typeof DBRef; - Binary: typeof Binary; - ObjectId: typeof ObjectId; - UUID: typeof UUID; - Long: typeof Long; - Timestamp: typeof Timestamp; - Double: typeof Double; - Int32: typeof Int32; - MinKey: typeof MinKey; - MaxKey: typeof MaxKey; - BSONRegExp: typeof BSONRegExp; - Decimal128: typeof Decimal128; - setInternalBufferSize: typeof setInternalBufferSize; - serialize: typeof serialize; - serializeWithBufferAndIndex: typeof serializeWithBufferAndIndex; - deserialize: typeof deserialize; - calculateObjectSize: typeof calculateObjectSize; - deserializeStream: typeof deserializeStream; - BSONValue: typeof BSONValue; - BSONError: typeof BSONError; - BSONVersionError: typeof BSONVersionError; - BSONRuntimeError: typeof BSONRuntimeError; - BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; - }>; - EJSON: any; -}>; -export class BSONError extends Error { - static isBSONError(value: any): boolean; - constructor(message: any); - get bsonError(): boolean; - get name(): string; -} -export class BSONRegExp extends BSONValue { - static parseOptions(options: any): any; - static fromExtendedJSON(doc: any): any; - constructor(pattern: any, options: any); - get _bsontype(): string; - pattern: any; - options: any; - toExtendedJSON(options: any): { - $regex: any; - $options: any; - $regularExpression?: undefined; - } | { - $regularExpression: { - pattern: any; - options: any; - }; - $regex?: undefined; - $options?: undefined; - }; - inspect(): string; -} -export class BSONRuntimeError extends BSONError { -} -export class BSONSymbol extends BSONValue { - static fromExtendedJSON(doc: any): BSONSymbol; - constructor(value: any); - get _bsontype(): string; - value: any; - valueOf(): any; - toString(): any; - inspect(): string; - toJSON(): any; - toExtendedJSON(): { - $symbol: any; - }; -} -export const BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; -}>; -export class BSONValue { -} -export class BSONVersionError extends BSONError { - constructor(); -} -export class Binary extends BSONValue { - static fromExtendedJSON(doc: any, options: any): Binary; - constructor(buffer: any, subType: any); - get _bsontype(): string; - sub_type: any; - buffer: any; - position: any; - put(byteValue: any): void; - write(sequence: any, offset: any): void; - read(position: any, length: any): any; - value(asRaw: any): any; - length(): any; - toJSON(): any; - toString(encoding: any): any; - toExtendedJSON(options: any): { - $binary: any; - $type: string; - } | { - $binary: { - base64: any; - subType: string; - }; - $type?: undefined; - }; - toUUID(): UUID; - inspect(): string; -} -export namespace Binary { - let BSON_BINARY_SUBTYPE_DEFAULT: number; - let BUFFER_SIZE: number; - let SUBTYPE_DEFAULT: number; - let SUBTYPE_FUNCTION: number; - let SUBTYPE_BYTE_ARRAY: number; - let SUBTYPE_UUID_OLD: number; - let SUBTYPE_UUID: number; - let SUBTYPE_MD5: number; - let SUBTYPE_ENCRYPTED: number; - let SUBTYPE_COLUMN: number; - let SUBTYPE_USER_DEFINED: number; -} -export class Code extends BSONValue { - static fromExtendedJSON(doc: any): Code; - constructor(code: any, scope: any); - get _bsontype(): string; - code: any; - scope: any; - toJSON(): { - code: any; - scope: any; - } | { - code: any; - scope?: undefined; - }; - toExtendedJSON(): { - $code: any; - $scope: any; - } | { - $code: any; - $scope?: undefined; - }; - inspect(): string; -} -export class DBRef extends BSONValue { - static fromExtendedJSON(doc: any): DBRef; - constructor(collection: any, oid: any, db: any, fields: any); - get _bsontype(): string; - collection: any; - oid: any; - db: any; - fields: any; - set namespace(value: any); - get namespace(): any; - toJSON(): any; - toExtendedJSON(options: any): { - $ref: any; - $id: any; - }; - inspect(): string; -} -export class Decimal128 extends BSONValue { - static fromString(representation: any): Decimal128; - static fromExtendedJSON(doc: any): Decimal128; - constructor(bytes: any); - get _bsontype(): string; - bytes: any; - toJSON(): { - $numberDecimal: string; - }; - toExtendedJSON(): { - $numberDecimal: string; - }; - inspect(): string; -} -export class Double extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Double; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toJSON(): number; - toString(radix: any): string; - toExtendedJSON(options: any): number | { - $numberDouble: string; - }; - inspect(): string; -} -export const EJSON: any; -export class Int32 extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Int32; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toString(radix: any): string; - toJSON(): number; - toExtendedJSON(options: any): number | { - $numberInt: string; - }; - inspect(): string; -} -export class Long extends BSONValue { - static fromBits(lowBits: any, highBits: any, unsigned: any): Long; - static fromInt(value: any, unsigned: any): any; - static fromNumber(value: any, unsigned: any): any; - static fromBigInt(value: any, unsigned: any): any; - static fromString(str: any, unsigned: any, radix: any): any; - static fromBytes(bytes: any, unsigned: any, le: any): Long; - static fromBytesLE(bytes: any, unsigned: any): Long; - static fromBytesBE(bytes: any, unsigned: any): Long; - static isLong(value: any): boolean; - static fromValue(val: any, unsigned: any): any; - static fromExtendedJSON(doc: any, options: any): any; - constructor(low: number, high: any, unsigned: any); - get _bsontype(): string; - get __isLong__(): boolean; - low: number; - high: number; - unsigned: boolean; - add(addend: any): Long; - and(other: any): Long; - compare(other: any): 0 | 1 | -1; - comp(other: any): 0 | 1 | -1; - divide(divisor: any): any; - div(divisor: any): any; - equals(other: any): boolean; - eq(other: any): boolean; - getHighBits(): number; - getHighBitsUnsigned(): number; - getLowBits(): number; - getLowBitsUnsigned(): number; - getNumBitsAbs(): any; - greaterThan(other: any): boolean; - gt(other: any): boolean; - greaterThanOrEqual(other: any): boolean; - gte(other: any): boolean; - ge(other: any): boolean; - isEven(): boolean; - isNegative(): boolean; - isOdd(): boolean; - isPositive(): boolean; - isZero(): boolean; - lessThan(other: any): boolean; - lt(other: any): boolean; - lessThanOrEqual(other: any): boolean; - lte(other: any): boolean; - modulo(divisor: any): Long; - mod(divisor: any): Long; - rem(divisor: any): Long; - multiply(multiplier: any): any; - mul(multiplier: any): any; - negate(): Long; - neg(): Long; - not(): Long; - notEquals(other: any): boolean; - neq(other: any): boolean; - ne(other: any): boolean; - or(other: any): Long; - shiftLeft(numBits: any): Long; - shl(numBits: any): Long; - shiftRight(numBits: any): Long; - shr(numBits: any): Long; - shiftRightUnsigned(numBits: any): Long; - shr_u(numBits: any): Long; - shru(numBits: any): Long; - subtract(subtrahend: any): Long; - sub(subtrahend: any): Long; - toInt(): number; - toNumber(): number; - toBigInt(): bigint; - toBytes(le: any): number[]; - toBytesLE(): number[]; - toBytesBE(): number[]; - toSigned(): Long; - toString(radix: any): any; - toUnsigned(): Long; - xor(other: any): Long; - eqz(): boolean; - le(other: any): boolean; - toExtendedJSON(options: any): number | { - $numberLong: any; - }; - inspect(): string; -} -export namespace Long { - let TWO_PWR_24: any; - let MAX_UNSIGNED_VALUE: Long; - let ZERO: any; - let UZERO: any; - let ONE: any; - let UONE: any; - let NEG_ONE: any; - let MAX_VALUE: Long; - let MIN_VALUE: Long; -} -export class MaxKey extends BSONValue { - static fromExtendedJSON(): MaxKey; - get _bsontype(): string; - toExtendedJSON(): { - $maxKey: number; - }; - inspect(): string; -} -export class MinKey extends BSONValue { - static fromExtendedJSON(): MinKey; - get _bsontype(): string; - toExtendedJSON(): { - $minKey: number; - }; - inspect(): string; -} -export class ObjectId extends BSONValue { - static getInc(): number; - static generate(time: any): any; - static createPk(): ObjectId; - static createFromTime(time: any): ObjectId; - static createFromHexString(hexString: any): ObjectId; - static isValid(id: any): boolean; - static fromExtendedJSON(doc: any): ObjectId; - constructor(inputId: any); - get _bsontype(): string; - __id: any; - set id(value: any); - get id(): any; - toHexString(): any; - toString(encoding: any): any; - toJSON(): any; - equals(otherId: any): any; - getTimestamp(): Date; - toExtendedJSON(): { - $oid: any; - }; - inspect(): string; - [kId]: any; -} -export namespace ObjectId { - let index: number; -} -export class Timestamp extends Long { - static fromInt(value: any): Timestamp; - static fromNumber(value: any): Timestamp; - static fromBits(lowBits: any, highBits: any): Timestamp; - static fromString(str: any, optRadix: any): Timestamp; - static fromExtendedJSON(doc: any): Timestamp; - constructor(low: any); - toJSON(): { - $timestamp: any; - }; - toExtendedJSON(): { - $timestamp: { - t: number; - i: number; - }; - }; -} -export namespace Timestamp { - import MAX_VALUE_1 = Long.MAX_UNSIGNED_VALUE; - export { MAX_VALUE_1 as MAX_VALUE }; -} -export class UUID extends Binary { - static generate(): any; - static isValid(input: any): boolean; - static createFromHexString(hexString: any): UUID; - constructor(input: any); - __id: any; - set id(value: any); - get id(): any; - toHexString(includeDashes?: boolean): any; - equals(otherId: any): any; - toBinary(): Binary; -} -export function calculateObjectSize(object: any, options?: {}): number; -export function deserialize(buffer: any, options?: {}): {}; -export function deserializeStream(data: any, startIndex: any, numberOfDocuments: any, documents: any, docStartIndex: any, options: any): any; -export function serialize(object: any, options?: {}): any; -export function serializeWithBufferAndIndex(object: any, finalBuffer: any, options?: {}): number; -export function setInternalBufferSize(size: any): void; -declare const kId: unique symbol; -export { bson as BSON }; diff --git a/src/extras/dist/src/extras/struct/datastructures/index.d.ts b/src/extras/dist/src/extras/struct/datastructures/index.d.ts deleted file mode 100644 index 07efe2c4..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './DataStructures'; -export * from './DataTablet'; -export * as DS from './DataStructures'; diff --git a/src/extras/dist/src/extras/struct/datastructures/types.d.ts b/src/extras/dist/src/extras/struct/datastructures/types.d.ts deleted file mode 100644 index ddb01f54..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/types.d.ts +++ /dev/null @@ -1,243 +0,0 @@ -export type ArbitraryObject = { - [x: string | number]: any; -}; -export type Struct = { - _id: string; - structType?: string | number; - timestamp?: string | number; - ownerId?: string | number; - parent?: { - structType: string; - _id: string | number; - }; - [key: string]: any; -}; -export type DataTypes = 'byTime' | 'notes' | 'events' | 'sleep' | 'food' | 'rx' | 'hr' | 'ppg' | 'hrv' | 'ecg' | 'emg' | 'eeg' | 'fnirs' | string | number | undefined; -export type StructTypes = LooseStructTypes | DataTypes | 'data' | 'struct' | string | number | undefined; -export type LooseStructTypes = 'coherence' | 'imu' | 'eyetracker' | 'profile' | 'authorization' | 'group' | 'event' | 'chatroom' | 'comment' | 'notification' | 'schedule' | 'date' | string | number | undefined; -export type Data = { - type: string; - data: any; - timestamp?: string | number; -}; -export type DataStruct = { - title?: string; - author?: string; - expires: boolean | number | string; - type: string; - data: Data[]; - tag?: string | number; -} & Struct; -export type EventStruct = { - event: string; - author: string; - startTime: string; - endTime?: string; - grade?: string | number; - value?: any; - units?: string; - notes?: string; - location?: any; - attachments?: Data | string | number[]; - users?: { - [key: string]: true; - }; - tag?: string | number; -} & Struct; -export type ChatroomStruct = { - message: string; - topic: string; - author: string; - attachments: Data | string | number[]; - comments: string[]; - replies: string[]; - users: { - [key: string]: true; - }; - audioChatActive: boolean; - videoChatActive: boolean; - tag?: string | number; -} & Struct; -export type CommentStruct = { - author: string; - replyTo: string; - attachments: Data | string | number[]; - replies: string[]; - users: { - [key: string]: true; - }; - tag?: string | number; -} & Struct; -export type NotificationStruct = { - note: string; - parentUserId: string; - tag?: string | number; -} & Struct; -export type ScheduleStruct = { - title: string; - author: string; - attachments: Data | string | number[]; - dates: string[]; - tag?: string | number; -} & Struct; -export type DateStruct = { - timeSet: string | number; - notes: string; - recurs: number | string | boolean; - attachments: Data | string | number[]; - tag?: string | number; -} & Struct; -export type ProfileStruct = { - username?: string; - name?: string; - firstName?: string; - lastName?: string; - fullName?: string; - email?: string; - phone?: string; - sex?: string; - birthday?: string; - userRoles?: {}; - socials?: {}; - data?: {}; - type?: string; - hidden?: boolean; - pictureUrl: string; - accessToken?: string; - refreshToken?: string; - tag?: string | number; -} & Struct; -export type AuthorizationStruct = { - authorizedId: string; - authorizedName: string; - authorizerId: string; - authorizerName: string; - authorizations: {}; - structs: {}; - excluded: {}; - groups: {}; - status: "PENDING" | "OKAY"; - expires: string | boolean; - associatedAuthId: string | number; - tag?: string | number; -} & Struct; -export type GroupStruct = { - name: string; - details: string; - admins: {}; - peers: {}; - clients: {}; - users: {}; - tag?: string | number; -} & Struct; -type FreqBand = [number[], number[]]; -export type FrequencyBandNames = 'scp' | 'delta' | 'theta' | 'alpha1' | 'alpha2' | 'beta' | 'lowgamma' | 'highgamma'; -export type FrequencyBandsStruct = { - scp: FreqBand | []; - delta: FreqBand | []; - theta: FreqBand | []; - alpha1: FreqBand | []; - alpha2: FreqBand | []; - beta: FreqBand | []; - lowgamma: FreqBand | []; - highgamma: FreqBand | []; -}; -export type EEGStruct = { - position: { - x: number; - y: number; - z: number; - }; - count: number; - times: number[]; - raw: number[]; - filtered: number[]; - fftCount: number; - fftTimes: number[]; - ffts: [][]; - slices: FrequencyBandsStruct; - means: FrequencyBandsStruct; - startTime: number | string; - tag?: string | number; -} & Struct; -export type CoherenceStruct = { - x0: number; - y0: number; - z0: number; - x1: number; - y1: number; - z1: number; - fftCount: number; - fftTimes: number[]; - ffts: [][]; - slices: FrequencyBandsStruct; - means: FrequencyBandsStruct; - startTime: number | string; - tag?: string | number; -} & Struct; -export type FNIRSStruct = { - position: { - x: number; - y: number; - z: number; - }; - count: number; - times: number[]; - red: number[]; - ir: number[]; - ir2: number[]; - ambient: number[]; - ratio: number[]; - temp: number[]; - beat_detect: { - beats: any[]; - breaths: any[]; - rir: any[]; - rir2: any[]; - drir_dt: any[]; - localmins: any[]; - localmaxs: any[]; - val_dists: any[]; - peak_dists: any[]; - localmins2: any[]; - localmaxs2: any[]; - val_dists2: any[]; - peak_dists2: any[]; - }; - startTime: number | string; - tag?: string | number; -} & Struct; -export type IMUStruct = { - Ax: number[]; - Ay: number[]; - Az: number[]; - Gx: number[]; - Gy: number[]; - Gz: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type EyeTrackerStruct = { - count: number; - times: number[]; - x: number[]; - y: number[]; - smax: number[]; - smay: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type ECGStruct = { - count: number; - times: number[]; - raw: number[]; - filtered: number[]; - bpm: number[]; - hrv: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type PPGStruct = FNIRSStruct; -export type HRVStruct = ECGStruct; -export type EMGStruct = EEGStruct; -export {}; diff --git a/src/extras/dist/src/extras/struct/genTimestamps.d.ts b/src/extras/dist/src/extras/struct/genTimestamps.d.ts deleted file mode 100644 index 69253e3d..00000000 --- a/src/extras/dist/src/extras/struct/genTimestamps.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type TimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' | 'decade' | 'century' | 'millennium' | 'microsecond' | 'nanosecond'; -type Plural = `${T}s`; -export type TimeSpecifier = `now` | `last ${string} ${Plural}` | `last ${TimeUnit}`; -export declare let defaultSpecifiers: (TimeUnit | "now")[]; -export declare function genTimeSpecifiers(specifiers?: (TimeUnit | "now")[]): string[]; -export declare function genTimestampFromString(specifier: TimeSpecifier): number; -export {}; diff --git a/src/extras/dist/src/extras/webgl-plot/webglplot.routes.d.ts b/src/extras/dist/src/extras/webgl-plot/webglplot.routes.d.ts deleted file mode 100644 index 26ef2e6b..00000000 --- a/src/extras/dist/src/extras/webgl-plot/webglplot.routes.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { WorkerInfo } from '../../services/worker/Worker.service'; -import { WebglLinePlotInfo, WebglLinePlotProps, WebglLinePlotUtil, WebglLineProps } from "webgl-plot-utils"; -import { FilterSettings } from "../algorithms/util/BiquadFilters"; -export { WebglLinePlotUtil, WebglLineProps, WebglLinePlotProps, WebglLinePlotInfo }; -export declare const webglPlotRoutes: { - setupChart: (settings: WebglLinePlotProps) => any; - updateChartData: (plot: WebglLinePlotInfo | string, lines?: { - [key: string]: number[] | WebglLineProps | { - [key: string]: any; - values: number[]; - }; - }, draw?: boolean) => boolean; - clearChart: (plot: WebglLinePlotInfo | string) => boolean; - resetChart: (plot: WebglLinePlotInfo | string, settings: WebglLinePlotProps) => any; - getChartSettings: (plotId: any) => any; -}; -export declare function setSignalControls(controlsDiv: HTMLElement, plotId: string, streamworker: WorkerInfo, chartworker: WorkerInfo, chartSettings: Partial, filterSettings: FilterSettings): Promise; diff --git a/src/extras/dist/src/loaders/index.d.ts b/src/extras/dist/src/loaders/index.d.ts deleted file mode 100644 index 229b9ec7..00000000 --- a/src/extras/dist/src/loaders/index.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; -/** - * setting nodeA.__node.backward:true propagates operator results to parent - */ -export declare const backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** - * - * Specify a timer loop, will stop when node is popped or nodeA.__node.isLooping is set false - * nodeA.__node.loop = 100 will loop the operator every 100 milliseconds - * - * Or - * nodeA.__node.delay will delay the operator by specified millisecond number and resolve the result as a promise - * nodeA.__node.frame will use requestAnimationFrame to call the function and resolve the result as a promise - * - * Use in combination with: - * nodeA.__node.repeat will repeat the operator the specified number of times - * nodeA.__node.recursive will do the same as repeat but will pass in the previous operator call's results - * - * - */ -export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Animations - * - * nodeA.__node.animate = true; - * then __operator becomes a requestAnimationFrame function - * start with a call the __operator or by setting node.__node.animating = true; - * - * or node.__animation = (...args) => {} - * - */ -export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Branching operations - * - * //runs a function or node if the if-conditions are satisfied, which can be a function that returns a true or false - * nodeA.__branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} - * - * nodeA.__listeners['nodeB.x'] = { - * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } - * } - * - */ -export declare const branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Trigger listeners oncreate with specific arguments - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, oncreate:any } - * - */ -export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Bind listeners to a specific object instead of the node that owns it - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } - * - */ -export declare const bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** - * - * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, transform:(result)=>any } - * - */ -export declare const transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -export declare const substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; -export declare const loaders: { - backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; - substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; -}; diff --git a/src/extras/dist/src/loaders/methodstrings.d.ts b/src/extras/dist/src/loaders/methodstrings.d.ts deleted file mode 100644 index 978aabc8..00000000 --- a/src/extras/dist/src/loaders/methodstrings.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function methodstrings(node: any): void; diff --git a/src/extras/dist/src/services/Service.d.ts b/src/extras/dist/src/services/Service.d.ts deleted file mode 100644 index a5558998..00000000 --- a/src/extras/dist/src/services/Service.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Graph, GraphNode, GraphOptions } from "../../src/core/Graph"; -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export type ServiceMessage = { - route?: string; - args?: any; - method?: string; - node?: string | GraphNode; - [key: string]: any; -}; -export type ServiceOptions = GraphOptions & { - services?: { - [key: string]: Service | Function | { - [key: string]: any; - }; - }; - restrict?: { - [key: string]: boolean; - }; -}; -export declare class Service extends Graph { - name: string; - restrict?: { - [key: string]: boolean; - }; - constructor(options?: ServiceOptions); - addServices: (services: { - [key: string]: Function | Graph | Service | { - [key: string]: any; - }; - }) => void; - handleMethod: (route: string, method: string, args?: any) => any; - handleServiceMessage(message: ServiceMessage): any; - handleGraphNodeCall(route: string | GraphNode, args: any): any; - transmit: (...args: any[]) => any | void; - receive: (...args: any[]) => any | void; - pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => number; - pipeOnce: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; - terminate: (...args: any) => void; - isTypedArray: typeof isTypedArray; - recursivelyAssign: (target: any, obj: any) => any; - spliceTypedArray: typeof spliceTypedArray; - ping: () => string; - echo: (...args: any) => any; - log: (...args: any) => boolean; - error: (...args: any) => boolean; -} -export declare function isTypedArray(x: any): boolean; -export declare const recursivelyAssign: (target: any, obj: any) => any; -export declare function spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; diff --git a/src/extras/dist/src/services/ecs/ECS.service.d.ts b/src/extras/dist/src/services/ecs/ECS.service.d.ts deleted file mode 100644 index cb3252b8..00000000 --- a/src/extras/dist/src/services/ecs/ECS.service.d.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { GraphNode, GraphNodeProperties } from '../../core/Graph'; -import { Service, ServiceOptions } from '../Service'; -export type EntityProps = { - components: { - [key: string]: any; - }; -} & (GraphNodeProperties | GraphNode); -export type SystemProps = (GraphNodeProperties & { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; -}) | GraphNode; -export type Entity = { - components: { - [key: string]: any; - }; - [key: string]: any; -} & GraphNode; -export type System = { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - remove?: (entity: Entity, entitities: { - [key: string]: Entity; - }) => Entity; - entities: { - [key: string]: Entity; - }; - entityKeys: string[]; -} & GraphNode; -export type ECSOptions = { - entities: { - [key: string]: EntityProps; - }; - systems: { - [key: string]: SystemProps; - }; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class ECSService extends Service { - entities: { - [key: string]: Entity; - }; - systems: { - [key: string]: System; - }; - entityMap: Map; - entityKeyMap: Map; - order: string[]; - animating: boolean; - entityCt: number; - systemCt: number; - constructor(options?: ECSOptions); - updateEntities: (order?: string[], filter?: boolean, debug?: any) => void; - animateEntities: (filter?: boolean, order?: string[]) => void; - stop: () => void; - start: (filter?: boolean) => void; - addEntities: (prototype: EntityProps, components?: { - [key: string]: any; - }, count?: number) => string[]; - addEntity: (prototype?: EntityProps, components?: { - [key: string]: any; - }) => Entity; - addSystems: (systems?: { - [key: string]: SystemProps; - }, order?: string[]) => { - [key: string]: System; - }; - addSystem: (prototype: SystemProps, setupEntities?: (entities: { - [key: string]: Entity; - }) => any, setupEntity?: (entity: Entity) => any, operator?: (entities: any) => any, remove?: (entities: any) => any, order?: string[]) => System; - setupEntity: (entity: Entity) => void; - removeEntity: (tag: string) => string | GraphNode; - removeEntities(entities: string[] | { - [key: string]: Entity; - }): void; - removeSystem: (tag: string) => string | GraphNode; - filterObject(o: { - [key: string]: any; - }, filter: (string: any, any: any) => boolean | undefined): { - [k: string]: any; - }; - setEntities: (entities: string[] | { - [key: string]: Entity; - }, props: { - [key: string]: any; - }) => boolean; - setEntity: (entity: Entity, props: { - [key: string]: any; - }) => any; - bufferValues: (entities: { - [key: string]: Entity; - }, property: string, keys?: string[] | { - [key: string]: any; - }, buffer?: ArrayBufferLike) => ArrayBufferLike; -} diff --git a/src/extras/dist/src/services/router/Router.d.ts b/src/extras/dist/src/services/router/Router.d.ts deleted file mode 100644 index 3d6e0348..00000000 --- a/src/extras/dist/src/services/router/Router.d.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { Graph, GraphNode } from "../../core/Graph"; -import { Service, ServiceOptions } from "../Service"; -export type User = { - _id: string; - send: (...args: any[]) => any; - request: (...args: any[]) => Promise | Promise[] | undefined; - post: (...args: any[]) => void; - run: (...args: any[]) => Promise | Promise[] | undefined; - subscribe: (...args: any[]) => Promise | Promise[] | undefined; - unsubscribe: (...args: any[]) => Promise | Promise[] | undefined; - sendAll?: (...args: any[]) => any; - requestAll?: (...args: any[]) => Promise | undefined; - postAll?: (...args: any[]) => void; - runAll?: (...args: any[]) => Promise | undefined; - subscribeAll?: (...args: any[]) => Promise | undefined; - unsubscribeAll?: (...args: any[]) => Promise | undefined; - terminate: (...args: any[]) => boolean; - onmessage?: (...args: any[]) => void; - onerror?: (...args: any[]) => void; - onclose?: ((user: User) => void) | ((...args: any[]) => void); - [key: string]: any; -}; -export type ConnectionProps = { - connection: GraphNode | Graph | { - [key: string]: any; - } | string; - service?: string | Graph | Service; - source?: string; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type ConnectionInfo = { - connection: GraphNode | Graph | { - [key: string]: any; - }; - service?: string | Service | Graph; - _id: string; - source: string; - connectionType?: string; - connectionsKey?: string; - send?: (message: any, ...a: any[]) => any; - request?: (message: any, method?: any, ...a: any[]) => Promise | Promise[]; - post?: (route: any, args?: any, method?: string, ...a: any[]) => void; - run?: (route: any, args?: any, method?: string, ...a: any[]) => Promise | Promise[]; - subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | undefined; - unsubscribe?: (route: any, sub: number, ...arrayBuffer: any[]) => Promise | Promise[]; - terminate: (...a: any[]) => boolean; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type RouterOptions = { - graph?: { - [key: string]: Service | Graph | any | { - service: Service | Graph | any; - connections: string[] | { - [key: string]: any; - }; - config?: { - [key: string]: { - _id?: string; - source?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - [key: string]: any; - }; - }; - }; - }; - timeout?: number; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class Router extends Service { - name: string; - connections: { - [key: string]: ConnectionInfo; - }; - sources: { - [key: string]: { - [key: string]: ConnectionInfo; - }; - }; - services: { - [key: string]: Service; - }; - serviceConnections: { - [key: string]: { - [key: string]: { - [key: string]: any; - }; - }; - }; - users: { - [key: string]: User; - }; - userTimeout: number; - order: string[]; - constructor(options?: RouterOptions); - addUser: (info: { - _id: string; - } & { - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; - }, connections?: { - [key: string]: string | ConnectionInfo | ConnectionProps; - }, config?: { - [key: string]: { - [key: string]: any; - service: Service; - _id?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - }; - }, receiving?: boolean) => Promise; - removeUser(profile: string | User | { - _id: string; - [key: string]: any; - }, terminate?: boolean): boolean; - getConnection: (sourceId: string, hasMethod?: string, connectionId?: string) => User | ConnectionInfo | undefined; - getConnections: (sourceId: string, hasMethod?: string, props?: {}) => {}; - runConnection: (userId: string, method: 'run' | 'post' | 'subscribe' | 'unsubscribe' | 'terminate' | 'send' | 'request' | 'runAll' | 'postAll' | 'subscribeAll' | 'unsubscribeAll' | 'sendAll' | 'requestAll', args: any[], connectionId?: string) => Promise; - subscribeThroughConnection: (route: string, remoteRelay: string | ConnectionInfo, remoteEndpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; - addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string, autoRemove?: boolean) => ConnectionInfo; - removeConnection: (connection: string | ConnectionInfo | { - [key: string]: any; - _id: string; - }, terminate?: boolean) => boolean; - routeService: (service: Service, connections?: any, source?: string, order?: string[]) => void; - addServiceConnections: (service: Service | string, connectionsKey: any, source?: string) => {}; - openConnection: (service: string | Service, options: { - [key: string]: any; - }, source?: string, ...args: any[]) => Promise; - terminate: (connection: string | ConnectionInfo) => boolean; - routeConnections: (route: string, transmitter: string | ConnectionInfo, receiver: string | ConnectionInfo, ...args: any[]) => Promise; - setUserData: (user: string | User, data: string | { - [key: string]: any; - }) => boolean; -} -export declare function connectionHasId(connection: { - _id?: string; - [key: string]: any; -}, timeout?: number): Promise; diff --git a/src/extras/dist/src/services/utils.d.ts b/src/extras/dist/src/services/utils.d.ts deleted file mode 100644 index 9efee154..00000000 --- a/src/extras/dist/src/services/utils.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export declare let recursivelyStringifyFunctions: (obj: { - [key: string]: any; -}) => {}; -export declare function getFnParamNames(fn: any): any; -export declare let getFunctionHead: (methodString: any) => any; -export declare function parseFunctionFromText(method?: string): any; -export declare function reconstructObject(json?: string | { - [x: string]: any; -}): any; -export declare const stringifyWithCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyWithFunctionsAndCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyFast: (obj: any, space?: any) => string; diff --git a/src/extras/dist/src/services/worker/Worker.service.d.ts b/src/extras/dist/src/services/worker/Worker.service.d.ts deleted file mode 100644 index 730d0214..00000000 --- a/src/extras/dist/src/services/worker/Worker.service.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import Worker from 'web-worker'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export type WorkerRoute = { - worker?: WorkerInfo; - workerUrl?: string | URL | Blob; - transferFunctions?: { - [key: string]: Function; - }; - transferClasses?: { - [key: string]: Function; - }; - parentRoute?: string; - portId?: string; - callback?: string; - stopped?: boolean; - blocking?: boolean; - init?: string; - initArgs?: any[]; - initTransfer?: any[]; -} & GraphNodeProperties & WorkerProps; -export type WorkerProps = { - worker?: WorkerInfo; - workerUrl?: string | URL | Blob; - url?: URL | string | Blob; - _id?: string; - port?: MessagePort; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - onclose?: (worker: Worker | MessagePort) => void; -}; -export type WorkerInfo = { - worker: Worker | MessagePort; - send: (message: any, transfer?: any) => void; - request: (message: any, method?: string, transfer?: any) => Promise; - post: (route: any, args?: any, method?: string, transfer?: any) => void; - run: (route: any, args?: any, method?: string, transfer?: any) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; - unsubscribe: (route: any, sub: number) => Promise; - start: (route?: any, portId?: string, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; - stop: (route?: string, portId?: string) => Promise; - workerSubs: { - [key: string]: { - sub: number | false; - route: string; - portId: string; - callback?: ((res: any) => void) | string; - blocking?: boolean; - }; - }; - terminate: () => boolean; - postMessage: (message: any, transfer?: any[]) => void; - graph: WorkerService; - _id: string; -} & WorkerProps & WorkerRoute; -export declare class WorkerService extends Service { - name: string; - workers: { - [key: string]: WorkerInfo; - }; - threadRot: number; - connections: any; - constructor(options?: ServiceOptions); - loadWorkerRoute: (node: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; - workerloader: any; - addDefaultMessageListener: () => void; - postMessage: (message: any, target: string, transfer?: Transferable[]) => void; - addWorker: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - open: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - close: () => void; - toObjectURL: (scriptTemplate: string) => string; - getTransferable(message: any): any; - transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: StructuredSerializeOptions) => any; - terminate: (worker: Worker | MessagePort | string | WorkerInfo) => boolean; - establishMessageChannel: (worker: Worker | string | MessagePort | WorkerInfo, worker2?: Worker | string | MessagePort | WorkerInfo) => string | false; - request: (message: ServiceMessage | any, workerId: string, transfer?: any, method?: string) => Promise; - runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number) => any; - subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => number; - subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; - triggerSubscription: (route: string, workerId: string, result: any) => Promise; - pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, args?: any[], key?: any, subInput?: boolean, blocking?: boolean) => Promise; - unpipeWorkers: (sourceRoute: string, sourceWorker: WorkerInfo | string, sub?: number) => Promise; -} diff --git a/src/extras/dist/src/storage/BFSUtils.d.ts b/src/extras/dist/src/storage/BFSUtils.d.ts deleted file mode 100644 index be89548b..00000000 --- a/src/extras/dist/src/storage/BFSUtils.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -export function readFileChunk(path?: string, begin?: number, end?: number, onread?: (data: any) => void): Promise; -export function processCSVChunksFromDB(path?: string, onData?: (csvdata: any, start: any, end: any, size: any) => void, maxChunkSize?: number, start?: number, end?: string, options?: {}): Promise; -export function readCSVChunkFromDB(path?: string, start?: number, end?: string, options?: {}): Promise<{}>; -export let fsInited: boolean; -export const fs: import("browserfs/dist/node/core/FS.js").FSModule; -export function initFS(dirs?: string[], oninit?: (exists?: any[]) => void, onerror?: (e: any) => void, filesystem?: string): Promise; -export function exists(path?: string): Promise; -export function readFile(path?: string): Promise; -export function getFilenames(directory?: string, onload?: (directory: any) => void): Promise; -export function writeFile(path: any, data: any, onwrite?: (data: any) => void): Promise; -export function appendFile(path: any, data: any, onwrite?: (data: any) => void): Promise; -export function deleteFile(path?: string, ondelete?: () => void): Promise; -export function readFileAsText(path?: string, end?: string, begin?: number, onread?: (data: any, filename: any) => void): Promise; -export function listFiles(dir?: string, onload?: (directory: any) => void): Promise; -export function getFileSize(path?: string, onread?: (size: any) => void): Promise; -export function getCSVHeader(path?: string, onopen?: (header: any, filename: any) => void): Promise; -export function writeToCSVFromDB(path?: string, fileSizeLimitMb?: number): Promise; -export function dirExists(fs: any, directory: any): Promise; -export namespace BFSRoutes { - export { initFS }; - export { dirExists }; - export { exists }; - export { readFile }; - export { readFileChunk }; - export { getFilenames }; - export { writeFile }; - export { appendFile }; - export { deleteFile }; - export { readFileAsText }; - export { getFileSize }; - export { getCSVHeader }; - export { listFiles }; -} diff --git a/src/extras/dist/src/storage/BFS_CSV.d.ts b/src/extras/dist/src/storage/BFS_CSV.d.ts deleted file mode 100644 index d18aaee3..00000000 --- a/src/extras/dist/src/storage/BFS_CSV.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { processCSVChunksFromDB, readCSVChunkFromDB } from './BFSUtils'; -import { CSV, toISOLocal } from './csv'; -export declare const appendCSV: (newData: { - [key: string]: number | number[]; -}, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; -}) => Promise; -export declare const updateCSVHeader: (header: any[], filename: string) => void; -export declare const createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; -export declare const visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; -export declare const csvRoutes: { - appendCSV: (newData: { - [key: string]: number | number[]; - }, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; - }) => Promise; - updateCSVHeader: (header: any[], filename: string) => void; - createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; - visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; - openCSV: typeof CSV.openCSV; - saveCSV: typeof CSV.saveCSV; - openCSVRaw: typeof CSV.openCSVRaw; - parseCSVData: (data: any, filename: any, head: any, hasend?: boolean, parser?: (lines: any, filename: any, head: any) => { - filename: any; - }) => { - filename: any; - }; - getCSVHeader: (path?: string, onopen?: (header: any, filename: any) => void) => Promise; - writeToCSVFromDB: (path?: string, fileSizeLimitMb?: number) => Promise; - readCSVChunkFromDB: typeof readCSVChunkFromDB; - processCSVChunksFromDB: typeof processCSVChunksFromDB; - toISOLocal: typeof toISOLocal; -}; diff --git a/src/extras/dist/src/storage/csv.d.ts b/src/extras/dist/src/storage/csv.d.ts deleted file mode 100644 index 030f67f5..00000000 --- a/src/extras/dist/src/storage/csv.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -export function toISOLocal(d: any): string; -export class CSV { - static saveCSV(csvDat?: string, name?: string): void; - static openCSV(delimiter?: string, onOpen?: (csvDat: any, header: any, path: any) => any): Promise; - static openCSVRaw(onOpen?: (csvDat: any, path: any) => any): Promise; - constructor(onOpen?: (csvDat?: any[], header?: any[]) => void, saveButtonId?: any, openButtonId?: any); - onOpen(csvDat?: any[], header?: any[]): void; - notes: any[]; - processArraysForCSV(data?: string[], delimiter?: string, header?: string, saveNotes?: boolean): string; -} -export function parseCSVData(data: any, filename: any, head: any, hasend?: boolean, parser?: (lines: any, filename: any, head: any) => { - filename: any; -}): { - filename: any; -}; -export function processDataForCSV(options?: {}): { - filename: any; - header: string; - body: string; -}; diff --git a/src/extras/dist/storage/BFSUtils.d.ts b/src/extras/dist/storage/BFSUtils.d.ts deleted file mode 100644 index be89548b..00000000 --- a/src/extras/dist/storage/BFSUtils.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -export function readFileChunk(path?: string, begin?: number, end?: number, onread?: (data: any) => void): Promise; -export function processCSVChunksFromDB(path?: string, onData?: (csvdata: any, start: any, end: any, size: any) => void, maxChunkSize?: number, start?: number, end?: string, options?: {}): Promise; -export function readCSVChunkFromDB(path?: string, start?: number, end?: string, options?: {}): Promise<{}>; -export let fsInited: boolean; -export const fs: import("browserfs/dist/node/core/FS.js").FSModule; -export function initFS(dirs?: string[], oninit?: (exists?: any[]) => void, onerror?: (e: any) => void, filesystem?: string): Promise; -export function exists(path?: string): Promise; -export function readFile(path?: string): Promise; -export function getFilenames(directory?: string, onload?: (directory: any) => void): Promise; -export function writeFile(path: any, data: any, onwrite?: (data: any) => void): Promise; -export function appendFile(path: any, data: any, onwrite?: (data: any) => void): Promise; -export function deleteFile(path?: string, ondelete?: () => void): Promise; -export function readFileAsText(path?: string, end?: string, begin?: number, onread?: (data: any, filename: any) => void): Promise; -export function listFiles(dir?: string, onload?: (directory: any) => void): Promise; -export function getFileSize(path?: string, onread?: (size: any) => void): Promise; -export function getCSVHeader(path?: string, onopen?: (header: any, filename: any) => void): Promise; -export function writeToCSVFromDB(path?: string, fileSizeLimitMb?: number): Promise; -export function dirExists(fs: any, directory: any): Promise; -export namespace BFSRoutes { - export { initFS }; - export { dirExists }; - export { exists }; - export { readFile }; - export { readFileChunk }; - export { getFilenames }; - export { writeFile }; - export { appendFile }; - export { deleteFile }; - export { readFileAsText }; - export { getFileSize }; - export { getCSVHeader }; - export { listFiles }; -} diff --git a/src/extras/dist/storage/BFS_CSV.d.ts b/src/extras/dist/storage/BFS_CSV.d.ts deleted file mode 100644 index d18aaee3..00000000 --- a/src/extras/dist/storage/BFS_CSV.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { processCSVChunksFromDB, readCSVChunkFromDB } from './BFSUtils'; -import { CSV, toISOLocal } from './csv'; -export declare const appendCSV: (newData: { - [key: string]: number | number[]; -}, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; -}) => Promise; -export declare const updateCSVHeader: (header: any[], filename: string) => void; -export declare const createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; -export declare const visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; -export declare const csvRoutes: { - appendCSV: (newData: { - [key: string]: number | number[]; - }, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; - }) => Promise; - updateCSVHeader: (header: any[], filename: string) => void; - createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; - visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; - openCSV: typeof CSV.openCSV; - saveCSV: typeof CSV.saveCSV; - openCSVRaw: typeof CSV.openCSVRaw; - parseCSVData: (data: any, filename: any, head: any, hasend?: boolean, parser?: (lines: any, filename: any, head: any) => { - filename: any; - }) => { - filename: any; - }; - getCSVHeader: (path?: string, onopen?: (header: any, filename: any) => void) => Promise; - writeToCSVFromDB: (path?: string, fileSizeLimitMb?: number) => Promise; - readCSVChunkFromDB: typeof readCSVChunkFromDB; - processCSVChunksFromDB: typeof processCSVChunksFromDB; - toISOLocal: typeof toISOLocal; -}; diff --git a/src/extras/dist/storage/csv.d.ts b/src/extras/dist/storage/csv.d.ts deleted file mode 100644 index 030f67f5..00000000 --- a/src/extras/dist/storage/csv.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -export function toISOLocal(d: any): string; -export class CSV { - static saveCSV(csvDat?: string, name?: string): void; - static openCSV(delimiter?: string, onOpen?: (csvDat: any, header: any, path: any) => any): Promise; - static openCSVRaw(onOpen?: (csvDat: any, path: any) => any): Promise; - constructor(onOpen?: (csvDat?: any[], header?: any[]) => void, saveButtonId?: any, openButtonId?: any); - onOpen(csvDat?: any[], header?: any[]): void; - notes: any[]; - processArraysForCSV(data?: string[], delimiter?: string, header?: string, saveNotes?: boolean): string; -} -export function parseCSVData(data: any, filename: any, head: any, hasend?: boolean, parser?: (lines: any, filename: any, head: any) => { - filename: any; -}): { - filename: any; -}; -export function processDataForCSV(options?: {}): { - filename: any; - header: string; - body: string; -}; diff --git a/src/extras/ecs/ECS.systems.ts b/src/extras/ecs/ECS.systems.ts index db53156e..8be51471 100644 --- a/src/extras/ecs/ECS.systems.ts +++ b/src/extras/ecs/ECS.systems.ts @@ -32,6 +32,7 @@ export const Systems = { __operator:function( entities:{[key:string]:Entity}){ let keys = this.entityKeys; + for(let i = 0; i < keys.length; i++) { const entity1 = entities[keys[i]]; @@ -106,7 +107,7 @@ export const Systems = { } return false }, - sphereCollisionCheck:( //simplest collisions + sphereCollisionCheck:( body1:{ position:{x:number,y:number,z:number}, collisionRadius:number, @@ -125,7 +126,7 @@ export const Systems = { return (dist as number) < (body1.collisionRadius + body2.collisionRadius); }, - boxCollisionCheck:( //also simple but corners are a problem + boxCollisionCheck:( body1:{ position:{x:number,y:number,z:number}, collisionRadius:number, @@ -311,8 +312,8 @@ export const Systems = { } }, dot:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ let dot = 0; for(const key in v1) { @@ -331,8 +332,8 @@ export const Systems = { }; }, vecadd:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1+v2 let result = Object.assign({},v1); for(const key in result) { @@ -341,8 +342,8 @@ export const Systems = { return result; }, vecsub:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1-v2, e.g. a point is v2 - v1 let result = Object.assign({},v1); for(const key in result) { @@ -351,8 +352,8 @@ export const Systems = { return result; }, vecmul:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1*v2 let result = Object.assign({},v1); for(const key in result) { @@ -361,8 +362,8 @@ export const Systems = { return result; }, vecdiv:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1/v2 let result = Object.assign({},v1); for(const key in result) { @@ -371,7 +372,7 @@ export const Systems = { return result; }, vecscale:( - v1:{[key:string]:number}, + v1:any, scalar:number )=>{ //v1*v2 let result = Object.assign({},v1); @@ -381,8 +382,8 @@ export const Systems = { return result; }, distance:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ let distance = 0; for(const key in v1) { @@ -391,7 +392,7 @@ export const Systems = { return Math.sqrt(distance); }, magnitude:( - v:{[key:string]:number} + v:any ) => { let magnitude = 0; for(const key in v) { @@ -400,11 +401,11 @@ export const Systems = { return Math.sqrt(magnitude); }, normalize:( - v:{[key:string]:number} + v:any ) => { let magnitude = Systems.collision.magnitude(v); let _mag = magnitude ? 1/magnitude : 0; - let vn = {}; + let vn = Object.assign({},v); for(const key in v) { vn[key] = v[key]*_mag; } @@ -754,6 +755,7 @@ export const Systems = { __operator: function (entities:{[key:string]:Entity}) { let keys = this.entityKeys; + for(let i = 0; i < keys.length; i++) { const entity1 = entities[keys[i]]; @@ -994,6 +996,7 @@ export const Systems = { __operator:function(entities:{[key:string]:Entity}){ let keys = this.entityKeys; + for(let i = 0; i < keys.length; i++) { const entity = entities[keys[i]]; @@ -1140,6 +1143,7 @@ export const Systems = { this.lastTime = now; let keys = this.entityKeys; + let length = keys.length; let _timeStep = 1/timeStep; @@ -1364,6 +1368,7 @@ export const Systems = { this.lastTime = now; let keys = this.entityKeys; + for(let i = 0; i < keys.length; i++) { const entity = entities[keys[i]]; diff --git a/src/extras/gpu/GPU.service.ts b/src/extras/gpu/GPU.service.ts index 431da7f4..8e9265e8 100644 --- a/src/extras/gpu/GPU.service.ts +++ b/src/extras/gpu/GPU.service.ts @@ -26,15 +26,8 @@ export class GPUService extends Service { if(typeof fn === 'string') fn = parseFunctionFromText(fn); if(typeof fn === 'function') this.gpu.addKernel(name,fn as any,options); } - combineKernels=(name:string,fs:(string|Function)[], ckrnl?:()=>void)=>{ - for(let i = 0; i < fs.length; i++) { - if(typeof fs[i] === 'string') fs[i] = parseFunctionFromText(fs[i] as string); - } - if(typeof ckrnl === 'string') ckrnl = parseFunctionFromText(ckrnl); - this.gpu.combineKernels(name, fs, ckrnl); - } callKernel=(name:string,...args:any[])=>{ - this.gpu.callKernel(name,args); + this.gpu.callKernel(name,...args); } dft=(signalBuffer: number[], nSeconds: any, scalar?: number)=>{ if (scalar == undefined) scalar = 1; diff --git a/src/extras/index.gpu.services.ts b/src/extras/index.gpu.services.ts deleted file mode 100644 index 6ab447b6..00000000 --- a/src/extras/index.gpu.services.ts +++ /dev/null @@ -1,4 +0,0 @@ -//for all the extra services we want to export but are too bulky for the core - -export * from './gpu/GPU.service' //~500kb -export { gpualgorithms } from './algorithms/index.gpu'; //modified algorithms object with presets \ No newline at end of file diff --git a/src/extras/index.services.ts b/src/extras/index.services.ts deleted file mode 100644 index 25e64c89..00000000 --- a/src/extras/index.services.ts +++ /dev/null @@ -1,17 +0,0 @@ -//for all the extra services we want to export but are too bulky for the core - -//e.g. babylonjs service, threejs service - -export * from './struct/Struct.frontend' -export * from './struct/Struct.backend' -export * from './struct/genTimestamps' - -export * from './ecs/ECS.systems' - -export * from './webgl-plot/webglplot.routes' - -//import gsworker from '../services/worker/Worker' //compiles the worker in the dist - -export { algorithms } from './algorithms/index'; //modified algorithms object with presets - -//export { gsworker } //available as a dataurl \ No newline at end of file diff --git a/src/extras/index.storage.services.ts b/src/extras/index.storage.services.ts deleted file mode 100644 index 9b76b24c..00000000 --- a/src/extras/index.storage.services.ts +++ /dev/null @@ -1,5 +0,0 @@ -//for all the extra services we want to export but are too bulky for the core - -export * from './storage/csv' -export * from './storage/BFSUtils' -export * from './storage/BFS_CSV' diff --git a/src/extras/package.json b/src/extras/package.json index 8b72994b..92ae0242 100644 --- a/src/extras/package.json +++ b/src/extras/package.json @@ -1,44 +1,15 @@ { - "name": "graphscript-services", - "version": "0.3.2", + "name": "graphscript-extras", + "version": "0.2.27", "description": "Extra services for graphscript.", - "main": "dist/index.services.js", - "module": "dist/index.services.esm.js", - "types": "dist/src/extras/index.services.d.ts", + "private": true, "scripts": { - "start": "tinybuild path=tinybuild.config.js && tinybuild path=tinybuild.gpu.config.js && tinybuild path=tinybuild.storage.config.js", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \"npm run python\" \"npm start\"", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" + "start": "npm run build", + "build": "cd build && cd gpu && tinybuild && cd ../storage && tinybuild && cd ../services && tinybuild" }, "keywords": [ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", - "dependencies": { - "brainsatplay-math": "~0.1.0", - "browserfs": "~1.4.3", - "gpujsutils": "~1.0.15", - "web-worker": "~1.3.0", - "webgl-plot-utils": "~0.4.2" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - }, - "devDependencies": { - "@types/node": "~18.7.15" - } + "license": "AGPL-3.0-or-later" } diff --git a/src/extras/storage/BFSUtils.js b/src/extras/storage/BFSUtils.js index 2281dddd..b6337e41 100644 --- a/src/extras/storage/BFSUtils.js +++ b/src/extras/storage/BFSUtils.js @@ -1,6 +1,6 @@ import {CSV} from './csv.js' -export let fsInited = false; +export let fsInited = false import * as BrowserFS from 'browserfs' export const fs = BrowserFS.BFSRequire('fs'); const BFSBuffer = BrowserFS.BFSRequire('buffer').Buffer; @@ -10,7 +10,6 @@ const BFSBuffer = BrowserFS.BFSRequire('buffer').Buffer; //Generic reimplementation of reading/writing buffered objects from/to CSVs and IndexedDB -let initPromise; // ----------------------------- Generic Functions for BrowserFS ----------------------------- export const initFS = async ( dirs = ['data'], @@ -18,26 +17,16 @@ export const initFS = async ( onerror=(e)=>{}, filesystem='IndexedDB' //default is IndexedDB //https://github.com/jvilk/BrowserFS see all ) => { - if (fsInited) { - if(initPromise) { - await initPromise; - } - return true; - } + if (fsInited) return true else { fsInited = true; - initPromise = new Promise ((resolve, reject) => { - //let oldmfs = fs.getRootFS(); + return new Promise (resolve => { + let oldmfs = fs.getRootFS(); BrowserFS.FileSystem[filesystem].Create({}, (e, mountableFileSystem) => { - if (e) { - reject(e); - return - } + if (e) throw e; if (!mountableFileSystem) { onerror(e); - - reject( new Error(`Error creating BrowserFS`) ); - return + throw new Error(`Error creating BrowserFS`); } BrowserFS.initialize(mountableFileSystem); //fs now usable with imports after this //console.log(mountableFileSystem,filesystem); @@ -50,11 +39,11 @@ export const initFS = async ( Promise.all(promises).then((values) => { oninit(values); + fsInited = true resolve(true) - }); - }); - }); - return await initPromise; + }) + }) + }) } } @@ -62,7 +51,7 @@ export const exists = async (path='') => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(resolve => { + return new Promise(resolve => { fs.exists('/'+path, function (exists) { resolve(exists); }); @@ -74,7 +63,7 @@ export const readFile = async (path='data') => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(resolve => { + return new Promise(resolve => { fs.readFile('/'+path, function(e, output) { resolve(output) }); @@ -88,18 +77,12 @@ export async function readFileChunk (path='data', begin = 0, end = 5120, onread= else await dirExists(fs,path.split('/')[0]); if (path != ''){ - return await new Promise(async (resolve, reject) => { + return new Promise(async resolve => { fs.open('/'+path, 'r', (e, fd) => { - if (e) { - reject(e); - return - } + if (e) throw e; fs.read(fd, end, begin, 'utf-8', (er, output, bytesRead) => { - if (er) { - reject(er); - return - } + if (er) throw er; if (bytesRead !== 0) { let data = output.toString(); //Now parse the data back into the buffers. @@ -122,12 +105,9 @@ export const getFilenames = async (directory = 'data', onload=(directory)=>{}) = if(!fsInited) await initFS([directory]); else await dirExists(fs,directory); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.readdir('/'+directory, (e, dir) => { - if (e){ - reject(e); - return - } + if (e) throw e; if (dir) { //console.log("files", dir); onload(dir); @@ -142,12 +122,9 @@ export const writeFile = async (path, data, onwrite=(data)=>{}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.writeFile('/'+path, data, (err) => { - if (err) { - reject(err); - return - } + if (err) throw err; onwrite(data); resolve(true); }); @@ -158,12 +135,9 @@ export const appendFile = async (path, data, onwrite=(data)=>{}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.appendFile('/'+path, data, (err) => { - if (err) { - reject(err); - return - } + if (err) throw err; onwrite(data); resolve(true); }); @@ -174,7 +148,7 @@ export const deleteFile = async (path='data', ondelete=()=>{}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(resolve => { + return new Promise(resolve => { if (path != ''){ fs.unlink('/'+path, (e) => { if (e) console.error(e); @@ -199,9 +173,9 @@ export const readFileAsText = async ( if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(async (resolve, reject) => { + return new Promise(async resolve => { - let size = await getFileSize(path); + let size = await getFileSize(path,dir) if(end === 'end') { end = size; @@ -210,15 +184,9 @@ export const readFileAsText = async ( } fs.open('/'+path, 'r', (e, fd) => { - if (e) { - reject(e); - return - } + if (e) throw e; fs.read(fd, end, begin, 'utf-8', (er, output, bytesRead) => { - if (er) { - reject(er); - return - } + if (er) throw er; if (bytesRead !== 0) { let data = output.toString(); //Now parse the data back into the buffers. @@ -241,12 +209,9 @@ export const listFiles = async (dir='data', onload=(directory)=>{}) => { if(!fsInited) await initFS([dir]); else await dirExists(fs,dir); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.readdir('/'+dir, (e, directory) => { - if (e) { - reject(e); - return - } + if (e) throw e; if (directory) { onload(directory); // if(fs_html_id){ @@ -277,17 +242,13 @@ export const listFiles = async (dir='data', onload=(directory)=>{}) => { -export const getFileSize = async (path='data',onread=(size)=>{}) => { - +export const getFileSize = async (path='data',onread=(size)=>{console.log(size);}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.stat('/'+path,(e,stats) => { - if(e) { - reject(e) - return - } + if(e) throw e; let filesize = stats.size; onread(filesize); resolve(filesize); @@ -296,22 +257,16 @@ export const getFileSize = async (path='data',onread=(size)=>{}) => { } -export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) => { +export const getCSVHeader = async (path='data', onopen=(header, filename)=>{console.log(header,filename);}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.open('/'+path,'r',(e,fd) => { - if(e) { - reject(e) - return - } + if(e) throw e; fs.read(fd,65535,0,'utf-8',(er,output,bytesRead) => { //could be a really long header for all we know - if (er) { - reject(er) - return; - } + if (er) throw er; if(bytesRead !== 0) { let data = output.toString(); let lines = data.split('\n'); @@ -332,30 +287,22 @@ export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) = if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { if (path != ''){ fs.stat('/' + path, (e, stats) => { - if (e) { - reject(e); - return - } + if (e) throw e; let filesize = stats.size; + console.log(filesize) fs.open(path, 'r', (e, fd) => { - if (e) { - reject(e); - return - } + if (e) throw e; let i = 0; let maxFileSize = fileSizeLimitMb * 1024 * 1024; let end = maxFileSize; if (filesize < maxFileSize) { end = filesize; fs.read(fd, end, 0, 'utf-8', (e, output, bytesRead) => { - if (e) { - reject(e); - return - } - if (bytesRead !== 0) CSV.saveCSV(output.toString(), path.split('/')[1]); + if (e) throw e; + if (bytesRead !== 0) CSV.saveCSV(output.toString(), path); fs.close(fd); resolve(true); }); @@ -366,12 +313,9 @@ export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) = if (i + end > filesize) { end = filesize - i; } let chunk = 0; fs.read(fd, end, i, 'utf-8', (e, output, bytesRead) => { - if (e) { - reject(e); - return - } + if (e) throw e; if (bytesRead !== 0) { - CSV.saveCSV(output.toString(), path.split('/')[1] + "_" + chunk); + CSV.saveCSV(output.toString(), path + "_" + chunk); i += maxFileSize; chunk++; writeChunkToFile(); @@ -393,42 +337,12 @@ export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) = }); } -//iterate asynchronously over a file (or a specific range of a file) and run a function on the data -export async function processCSVChunksFromDB(path='data', onData=(csvdata,start,end,size)=>{}, maxChunkSize=10000, start=0, end='end', options={}) { - - let size = await getFileSize(path); - - let partition = start; - - return await new Promise((res,rej) => { - let processPartition = () => { - let endChunk = partition+maxChunkSize; - if(endChunk > size) { - endChunk = size; - } - readCSVChunkFromDB(path,partition,endChunk,options).then(async (result) => { - await onData(result,partition,endChunk,size); - //console.log(partition,endChunk,size); - partition = endChunk; - if(partition !== size) { - processPartition(); - } else { - res(true); - } - }).catch(rej); - - } - - processPartition(); - }); -} //returns an object with the headers and correctly sized outputs (e.g. single values or arrays pushed in columns) -export async function readCSVChunkFromDB(path='data', start=0, end='end', options={}) { +export async function readCSVChunkFromDB(path='data', start=0, end='end') { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - const transpose = options.transpose || false; let head = await getCSVHeader(path); @@ -437,7 +351,7 @@ export async function readCSVChunkFromDB(path='data', start=0, end='end', option let resultLengths = []; let resultNames = []; - let results = (transpose) ? [] : {} + let results = {}; head.forEach((v) => { if(v) { @@ -454,62 +368,53 @@ export async function readCSVChunkFromDB(path='data', start=0, end='end', option end = size; } + let data = await readFileChunk(path,start,end); - let data = (await readFileChunk(path,start,end))?.split('\n').slice(1, -1) // exclude header and last pseudoline - - let preprocess = (value) => { - try { value = JSON.parse(value) } catch {} - return value; - } - - if(data) data.forEach((r,i) => { + let headeridx = 0; + let lastIdx = 0; + data.forEach((r,i) => { let row = r.split(','); - if (transpose) { - const entry = {} - if(options.json) row.forEach((v, idx) => {if(options.json) entry[resultNames[idx]] = preprocess(v); else entry[resultNames[idx]] = v;}) - results.push(entry) - } else { - row.forEach((v,i) => { - const header = resultNames[i] - if (!results[header]) results[header] = []; - if(options.json) results[header].push(preprocess(v)) - else results[header].push(v); - }) - } + while(lastIdx < row.length-1) { + let l = resultLengths[headeridx]; + if(l === 1) { + results[resultNames[headeridx]].push(row[lastIdx]); + lastIdx++; + } + else { + results[resultNames[headeridx]].push(row[lastIdx].slice(lastIdx,l)); + lastIdx+=l; + } + } }); - return results; + } + let directories = {}; export const dirExists = async (fs, directory) => { - if(!fsInited) await initFS([directory]); - return await new Promise((resolve, reject) => { - if(!directory) reject(false); + return new Promise((resolve, reject) => { if (directories[directory] === 'exists' || directories[directory] === 'created'){ resolve() } else { - if(directory[0] === '/') directory = directory.substring(1); - if(!directory) reject(false); fs.exists(`/${directory}`, (exists) => { if (exists) { directories[directory] = 'exists' - //console.log(`/${directory} exists!`) + console.log(`/${directory} exists!`) resolve(); } else if (directories[directory] === 'creating'){ - //console.log(directory + ' is still being created.') + console.log(directory + ' is still being created.') resolve(); } else { - //console.log('creating ' + `/${directory}`, fs); + console.log('creating ' + `/${directory}`, fs); directories[directory] = 'creating'; fs.mkdir(`/${directory}`, 1, (err) => { if (err) { - reject(err); - return + throw err; } directories[directory] = 'created' setTimeout(resolve, 500) @@ -521,19 +426,19 @@ export const dirExists = async (fs, directory) => { }); } -//redundant declaration prevents minification of names for the routes + export const BFSRoutes = { - initFS:initFS, - dirExists:dirExists, - exists:exists, - readFile:readFile, - readFileChunk:readFileChunk, - getFilenames:getFilenames, - writeFile:writeFile, - appendFile:appendFile, - deleteFile:deleteFile, - readFileAsText:readFileAsText, - getFileSize:getFileSize, - getCSVHeader:getCSVHeader, - listFiles:listFiles + initFS, + dirExists, + exists, + readFile, + readFileChunk, + getFilenames, + writeFile, + appendFile, + deleteFile, + readFileAsText, + getFileSize, + getCSVHeader, + listFiles }; \ No newline at end of file diff --git a/src/extras/storage/BFS_CSV.ts b/src/extras/storage/BFS_CSV.ts index 29df8331..63c01657 100644 --- a/src/extras/storage/BFS_CSV.ts +++ b/src/extras/storage/BFS_CSV.ts @@ -1,4 +1,4 @@ -import { appendFile, deleteFile, exists, getCSVHeader, listFiles, processCSVChunksFromDB, readCSVChunkFromDB, writeFile, writeToCSVFromDB } from './BFSUtils'; +import { appendFile, deleteFile, exists, getCSVHeader, listFiles, readCSVChunkFromDB, writeFile, writeToCSVFromDB } from './BFSUtils'; import { CSV, parseCSVData, toISOLocal } from './csv'; //We have object formats coming in like {x,y,z}, tied to devices with USB data or BLE data with specifiers @@ -11,7 +11,6 @@ const CSV_REFERENCE:{ lastX:number, //latest line, unjoined buffer:string, //appended strings waiting to be written to browserfs buffered:number, - toFixed:number, bufferSize:number|undefined, xIncrement?:number|undefined } @@ -39,16 +38,9 @@ export const appendCSV = async ( newData:{[key:string]:number|number[]}, //assume uniformly sized data is passed in, so pass separate timestamp intervals separately filename:string, header?:string[], - options?: { - json?:boolean, - toFixed?:number, - bufferSize?:number, - xIncrement?:number - } + toFixed:number=5 ) => { - //console.log(newData); - //console.log('append',filename); if(!filename) { let keys = Object.keys(CSV_REFERENCE); @@ -66,15 +58,11 @@ export const appendCSV = async ( lastX:undefined as any, buffer:'', buffered:0, //buffer numbers to be appended? - bufferSize:options?.bufferSize ? options.bufferSize : 0, - toFixed:options?.toFixed ? options.toFixed : 0, - xIncrement:options?.xIncrement ? options.xIncrement : 0 + bufferSize:0, + xIncrement:undefined }; csv = CSV_REFERENCE[filename]; - - const existingHeader = await getCSVHeader(filename).catch(() => null); - const isDifferent = (!existingHeader || existingHeader !== csv.header.join(',')) - if (isDifferent) header = csv.header; // Only push header if it's different + header = csv.header; } if (!csv.header || csv.header?.length === 0) { let keys = Array.from(Object.keys(newData)); if (keys.indexOf('timestamp') > -1) keys.splice(keys.indexOf('timestamp'), 1); @@ -85,10 +73,12 @@ export const appendCSV = async ( let maxLen = 1; //max length of new arrays being appended, if any for(const key in newData) { - const value = newData[key] - if(csv.header.indexOf(key) > -1 && value && Array.isArray(value) && value?.length > maxLen) maxLen = value?.length; + if(csv.header.indexOf(key) > -1 && (newData[key] as any)?.length > maxLen) { + maxLen = (newData[key] as any)?.length; + } } + let x; if(csv.xIncrement) { @@ -111,9 +101,8 @@ export const appendCSV = async ( } } - else if(newData[csv.header[0]]) x = newData[csv.header[0]]; //first csv value treated as x for reference for growing the csv, mainly to generate timestamps if being used but not defined - else x = Date.now(); - + else x = newData[csv.header[0]]; //first csv value treated as x for reference for growing the csv, mainly to generate timestamps if being used but not defined + if(typeof csv.lastX === 'undefined') csv.lastX = Array.isArray(x) ? x[0] : x; if(typeof x === 'undefined') { if(csv.header[0].includes('time')) { @@ -133,10 +122,10 @@ export const appendCSV = async ( } } else if (maxLen > 1 && (x as any)?.length !== maxLen) { if(!Array.isArray(x) || x.length === 1) { - x = interpolerp(csv.lastX,x,maxLen,true); //we are gonna upsample x to the maximum size array that's been passed in + x = interpolerp(csv.lastX,x,maxLen); //we are gonna upsample x to the maximum size array that's been passed in x.shift(); } else { - x = interpolerp(x[0],x[x.length-1],maxLen,true); //upsample using new timestamps + x = interpolerp(x[0],x[x.length-1],maxLen); //upsample using new timestamps x.shift(); } } @@ -184,8 +173,7 @@ export const appendCSV = async ( } if(typeof toAppend[i][j] === 'number' && Math.floor(toAppend[i][j]) !== toAppend[i][j]) - toAppend[i][j] = toAppend[i][j].toFixed(CSV_REFERENCE[filename].toFixed) - + toAppend[i][j] = toAppend[i][j].toFixed(toFixed) } } } else { @@ -203,8 +191,7 @@ export const appendCSV = async ( if(typeof toAppend[0][j] === 'number' && Math.floor(toAppend[0][j]) !== toAppend[0][j]) - toAppend[0][j] = toAppend[0][j].toFixed(CSV_REFERENCE[filename].toFixed); - + toAppend[0][j] = toAppend[0][j].toFixed(toFixed) } } @@ -214,15 +201,13 @@ export const appendCSV = async ( if(header) csvProcessed += header.join(',') + '\n'; //append new headers when they show up toAppend.forEach((arr) => { - csvProcessed += ((options?.json) ? arr.map(v => JSON.stringify(v)) : arr).join(',') + '\n'; - // csvProcessed += arr.join(',') + '\n'; + csvProcessed += arr.join(',') + '\n'; if(csv.bufferSize) csv.buffered++; }); csv.lastX = toAppend[toAppend.length-1][0]; //reference the last array written as the latest data for if we don't pass timestamps //okay we are ready to append arrays to the file - if(csv.bufferSize) { csv.buffer += csvProcessed; if(csv.buffered > csv.bufferSize) { @@ -255,10 +240,10 @@ export const appendCSV = async ( return r; } - else return await Promise.resolve(true); + else return Promise.resolve(true); } else { - return await new Promise((res,rej) => { + return new Promise((res,rej) => { exists(filename).then((fileExists) => { if(!fileExists) { writeFile( @@ -278,7 +263,7 @@ export const appendCSV = async ( ); } }); - }) as any as Promise + }) as Promise } //e.g. generalize this for other data types } @@ -293,42 +278,35 @@ export const updateCSVHeader = (header:any[],filename:string) => { export const createCSV = ( filename:string, header:string[], - toFixed:number=5, //limit decimals (saves a ton of memory), set to 0 for integers bufferSize:number=0, //accumulate a certain number of lines before writing to BFS? (necessary for > 100 updates/sec fyi) xIncrement?:number //fixed time increment for newlines? ) => { - if(!CSV_REFERENCE[filename]) { - if(header?.indexOf('timestamp') > 1) {header.splice(header.indexOf('timestamp'),1); header.unshift('timestamp')} - if((header?.[0].toLowerCase().includes('time') || header?.[0].toLowerCase().includes('unix')) && header[1] !== 'localized') { - header.splice(1,0,'localized') //toISOLocal - } - - CSV_REFERENCE[filename] = { - header, - lastX:header[1] === 'localized' ? Date.now() : 0, - bufferSize, - buffer:'', - buffered:0, - toFixed, - xIncrement - }; - - //overwrite existing files - return new Promise((res,rej) => { - exists(filename).then((doesExist) => { - if(!doesExist) { //try not to overwrite - writeFile( - filename, - CSV_REFERENCE[filename].header? CSV_REFERENCE[filename].header.join(',')+'\n' : '', - (written:boolean) => { - res(written); - } - ).catch(rej); - } - }); - }); + if(header?.indexOf('timestamp') > 1) {header.splice(header.indexOf('timestamp'),1); header.unshift('timestamp')} + if((header?.[0].toLowerCase().includes('time') || header?.[0].toLowerCase().includes('unix')) && header[1] !== 'localized') { + header.splice(1,0,'localized') //toISOLocal } + + CSV_REFERENCE[filename] = { + header, + lastX:header[1] === 'localized' ? Date.now() : 0, + bufferSize, + buffer:'', + buffered:0, + xIncrement + }; + + //overwrite existing files + return new Promise((res,rej) => { + writeFile( + filename, + CSV_REFERENCE[filename].header? CSV_REFERENCE[filename].header.join(',')+'\n' : '', + (written:boolean) => { + res(written); + } + ).catch(rej); + }); + } @@ -373,17 +351,16 @@ export const visualizeDirectory = (dir:string, parentNode=document.body) => { } export const csvRoutes = { - appendCSV:appendCSV, - updateCSVHeader:updateCSVHeader, - createCSV:createCSV, - visualizeDirectory:visualizeDirectory, + appendCSV, + updateCSVHeader, + createCSV, + visualizeDirectory, openCSV:CSV.openCSV, saveCSV:CSV.saveCSV, openCSVRaw:CSV.openCSVRaw, - parseCSVData:parseCSVData, - getCSVHeader:getCSVHeader, - writeToCSVFromDB:writeToCSVFromDB, - readCSVChunkFromDB:readCSVChunkFromDB, - processCSVChunksFromDB:processCSVChunksFromDB, - toISOLocal:toISOLocal + parseCSVData, + getCSVHeader, + writeToCSVFromDB, + readCSVChunkFromDB, + toISOLocal } \ No newline at end of file diff --git a/src/extras/storage/BFS_GDrive.ts b/src/extras/storage/BFS_GDrive.ts deleted file mode 100644 index ab9dcfdb..00000000 --- a/src/extras/storage/BFS_GDrive.ts +++ /dev/null @@ -1,669 +0,0 @@ - -import { fs, fsInited, initFS } from "./BFSUtils"; - -declare var window; - - - -export class GDrive { - //------------------------ - //-GOOGLE DRIVE FUNCTIONS- - //------------------------ - - google = (window as any).google; - gapi = (window as any).gapi; - tokenClient = (window as any).tokenClient; - gapiInited = this.gapi !== undefined; - gsiInited = this.google !== undefined; - isLoggedIn = false; - previousPageTokens = [] as any[]; - nextPageToken: any; previousPageToken:any; currentFolderId; - container:any; - - directory = "Graphscript" - fs = fs; - - constructor(apiKey?, googleClientId?) { - if(apiKey && googleClientId) - this.initGapi(apiKey, googleClientId); - } - - //this is deprecated now?: https://developers.google.com/identity/gsi/web/guides/overview - initGapi = async ( - apiKey:string, - googleClientID:string - ) => { - - return new Promise(async (resolve,rej) => { - - //console.log('initializing gapi'); - - const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'; - const SCOPES = 'https://www.googleapis.com/auth/drive'; - this.gapiInited = false; - this.gsiInited = false; - - - await Promise.all( - [new Promise((res) => { - const initializeGapiClient = async () => { - await this.gapi.client.init({ - apiKey: apiKey, - discoveryDocs: [DISCOVERY_DOC], - }); - this.gapiInited = true; - //console.log('gapi', window.gapi); - } - - const gapiLoaded = () => { - this.gapi = window.gapi; - this.gapi.load('client', initializeGapiClient); - } - - const script1 = document.createElement('script'); - script1.type = "text/javascript"; - script1.src = "https://apis.google.com/js/api.js"; - script1.async = true; - script1.defer = true; - script1.onload = gapiLoaded; - document.head.appendChild(script1); - - }), - new Promise((res) => { - - const gsiLoaded =() => { - this.google = window.google; - this.tokenClient = this.google.accounts.oauth2.initTokenClient({ - client_id: googleClientID, - scope: SCOPES, - callback: '', // defined later - }); - this.gsiInited = true; - //console.log('google', window.google) - res(true); - } - - const script2 = document.createElement('script'); - script2.type = "text/javascript"; - script2.src = "https://accounts.google.com/gsi/client"; - script2.async = true; - script2.defer = true; - script2.onload = gsiLoaded; - document.head.appendChild(script2); - - }) - ]); - - resolve(true); - - // function updateSigninStatus(isSignedIn) { - // if (isSignedIn) { - // console.log("Signed in with Google.") - // } else { - // console.log("Signed out of Google") - // } - // } - - }) - - } - - handleUserSignIn = () => { - return new Promise(async (res,rej) => { - if(!this.tokenClient) { - console.error('Google API not found'); - return; - } - - this.tokenClient.callback = async (resp) => { - if (resp.error !== undefined) { - rej(resp); - } - this.isLoggedIn = true; - res(resp); - }; - - if (this.gapi.client.getToken() === null) { - // Prompt the user to select a Google Account and ask for consent to share their data - // when establishing a new session. - this.tokenClient.requestAccessToken({prompt: 'consent'}); - } else { - // Skip display of account chooser and consent dialog for an existing session. - this.tokenClient.requestAccessToken({prompt: ''}); - } - }); - } - - checkFolder = ( - name=this.directory, - onResponse=(result)=>{} - ) => { - return new Promise((res,rej) => { - - this.gapi.client.drive.files.list({ - q:"name='"+name+"' and mimeType='application/vnd.google-apps.folder'", - }).then((response) => { - if(response.result.files.length === 0) { - this.createDriveFolder(); - if(onResponse) onResponse(response.result); - res(response.result as any); - } - else if(onResponse) onResponse(response.result); - res(response.result as any); - }); - }) - } - - createDriveFolder = ( - name=this.directory - ) => { - return new Promise((res,rej) => { - if(this.isLoggedIn) { - let data = new Object() as any; - data.name = name; - data.mimeType = "application/vnd.google-apps.folder"; - this.gapi.client.drive.files.create({'resource': data}).then((response)=>{ - console.log("Created Folder:",response.result); - res(response.result as any); - }); - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - res(await this.createDriveFolder(name)); //rerun - } - }); - } - }); - } - - async listFolders(directory = this.directory, parent='parents') { - try { - const response = await this.gapi.client.drive.files.list({ - q: `'${directory}' in ${parent} and mimeType='application/vnd.google-apps.folder'`, - fields: 'nextPageToken, files(id, name, mimeType)' - }); - return response.result.files || []; - } catch (error) { - console.error('Error listing folders:', error); - throw error; - } - } - - - async getFileMetadata(fileId) { - try { - const response = await this.gapi.client.drive.files.get({ - fileId, - fields: 'id, name, mimeType, parents', - }); - return response.result; - } catch (error) { - console.error('Error getting file metadata:', error); - throw error; - } - } - - async getFolderId(folderName, parentFolder = 'root') { - try { - const query = `mimeType='application/vnd.google-apps.folder' and name='${folderName}' ${parentFolder ? `and '${parentFolder}' ` : ``}in parents and trashed=false`; - const response = await this.gapi.client.drive.files.list({ - q: query, - fields: 'files(id, name)', - pageSize: 1 - }); - - const folder = response.result.files && response.result.files[0]; - if (folder) { - return folder.id; - } else { - console.error('Folder not found'); - return null; - } - } catch (error) { - console.error('Error getting folder ID:', error); - throw error; - } - } - - async downloadFile(fileId, mimeType) { - try { - const response = await this.gapi.client.drive.files.get({ - fileId, - alt: 'media' - }, { responseType: 'blob' }); - - const blob = new Blob([response.body], { type: mimeType }); - const link = document.createElement('a'); - link.href = URL.createObjectURL(blob); - link.download = 'downloaded_file'; - //document.body.appendChild(link); - link.click(); - //document.body.removeChild(link); - } catch (error) { - console.error('Error downloading file:', error); - throw error; - } - } - - async uploadFileToGoogleDrive( - data:Blob|string='a,b,c,1,2,3\nd,e,f,4,5,6\n', - fileName=`${new Date().toISOString()}.csv`, - mimeType='application/vnd.google-apps.spreadsheet', - directory=this.directory, - onProgress:((this: XMLHttpRequest, ev: ProgressEvent) => any) | null - ) { - - if (typeof data === 'string') { - const type = fileName.endsWith('.csv') ? 'text/csv' : 'text/plain'; - data = new Blob([data], { type }); - } - - const metadata = { - 'name': fileName, - 'mimeType': mimeType, - 'parents': [directory], // upload to the current directory - }; - - const form = new FormData(); - form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); - form.append('file', data); - - const xhr = new XMLHttpRequest(); - xhr.open('POST', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'); - - const token = this.gapi.auth.getToken().access_token; - xhr.setRequestHeader('Authorization', 'Bearer ' + token); - - xhr.upload.onprogress = onProgress; - - return new Promise((resolve, reject) => { - xhr.onload = () => { - if (xhr.status === 200) { - resolve(JSON.parse(xhr.responseText)); - } else { - reject(xhr.responseText); - } - }; - xhr.onerror = () => reject(xhr.statusText); - xhr.send(form); - }); - } - - // Add this method to your GDrive class - async uploadFiles( - files:{name:string,mimeType:string,data:Blob|string}[], - directory=this.directory, - uploadProgress:HTMLProgressElement|string, - defaultBrowser=false - ) { - if(typeof uploadProgress === 'string') uploadProgress = document.getElementById('upload-progress') as HTMLProgressElement; - if(uploadProgress) uploadProgress.style.display = 'block'; - - for (let i = 0; i < files.length; i++) { - const file = files[i]; - try { - await this.uploadFileToGoogleDrive( - file.data, - file.name, - file.mimeType, - directory, - (progressEvent) => { - const progress = (progressEvent.loaded / progressEvent.total) * 100; - (uploadProgress as HTMLProgressElement).value = progress; - } - ); - if(uploadProgress) uploadProgress.value = 0; // Reset the progress bar after each file is uploaded - } catch (error) { - console.error('Error uploading file:', (file as any).name, error); - } - } - - if(uploadProgress) uploadProgress.style.display = 'none'; // Hide the progress bar after all files are uploaded - if(defaultBrowser) this.updateFileList(directory, this.nextPageToken, undefined, this.container); // Refresh the file list to show the newly uploaded files - } - - - async listDriveFiles( - folderId = this.directory, - pageSize = 100, - onload?:(files)=>{}, - pageToken = null, - parentFolder?:string - ) { - - if(this.isLoggedIn) { - try { - const response = await this.gapi.client.drive.files.list({ - q: `'${folderId}' ${parentFolder ? `and '${parentFolder}' ` : ``}in parents and trashed=false`, - pageSize, - fields: 'nextPageToken, files(id, name, mimeType)', - pageToken, - }); - - if (response.result?.files && response.result.files.length > 0) { - if(onload) onload(response.result.files); - } - - return { - files: response.result.files, - nextPageToken: response.result.nextPageToken, - }; - - } catch (error) { - console.error('Error listing Drive files:', error); - throw error; - } - - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - return await this.listDriveFiles( - folderId, - pageSize, - onload, //rerun - pageToken, - parentFolder - ) - } - }); - } - } - - createFileBrowser( - container, - folderId=this.directory, - nextPageToken=this.nextPageToken, - parentFolder - ) { - if (typeof container === 'string') { - container = document.getElementById(container); - } - - if (!container) { - console.error('Container element not found'); - return; - } - this.container = container; - container.innerHTML = `
-
- - -
-
Drop files here to upload
- -
-
- - -
`; - - this.updateFileList(folderId, nextPageToken, parentFolder, container); // Initially load the root directory - this.setupDragAndDrop(folderId, nextPageToken, parentFolder, container); - this.setupUploadButton(folderId, nextPageToken, parentFolder, container); - this.setupPaginationButtons(folderId, parentFolder, container); - } - - setupUploadButton(folderId, nextPageToken, parentFolder, container) { - const uploadButton = container.querySelector('#upload-button') as HTMLButtonElement; - const fileInput = container.querySelector('#file-input') as HTMLInputElement; - - if (!uploadButton || !fileInput) { - console.error('Upload button or file input not found'); - return; - } - - uploadButton.addEventListener('click', () => { - fileInput.click(); - }); - - fileInput.addEventListener('change', async () => { - const files = fileInput.files as any; - if (files.length > 0) { - const uploadFiles = Array.from(files).map((file:any) => ({ - name: file.name, - mimeType: file.type, - data: file, - })); - - const uploadProgress = container.querySelector('#upload-progress') as HTMLProgressElement; - await this.uploadFiles(uploadFiles, this.directory, uploadProgress); - this.updateFileList(folderId, nextPageToken, parentFolder, container); - fileInput.value = ''; // Clear the file input - } - }); - } - - setupDragAndDrop(currentFolderId:string, nextPageToken, parentFolder, container:HTMLElement) { - const dropZone = container.querySelector('#drop-zone'); - if (!dropZone) { - console.error('Drop zone element not found'); - return; - } - - dropZone.addEventListener('dragover', (e) => { - e.preventDefault(); - e.stopPropagation(); - dropZone.classList.add('highlight'); - }); - - dropZone.addEventListener('dragleave', (e) => { - e.preventDefault(); - e.stopPropagation(); - dropZone.classList.remove('highlight'); - }); - - dropZone.addEventListener('drop', async (e:any) => { - e.preventDefault(); - e.stopPropagation(); - dropZone.classList.remove('highlight'); - - const files = e.dataTransfer.files; - if (files.length > 0) { - const uploadFiles = Array.from(files).map((file:any) => ({ - name: file.name, - mimeType: file.type, - data: file, - })); - - const uploadProgress = container.querySelector('#upload-progress') as HTMLProgressElement; - await this.uploadFiles(uploadFiles, this.directory, uploadProgress); - this.updateFileList(currentFolderId, nextPageToken, parentFolder, container); - } - }); - } - - async updateFileList(currentFolderId = this.directory, pageToken = null, parentFolder, container:HTMLElement) { - try { - const { files, nextPageToken } = await this.listDriveFiles(currentFolderId, 100, undefined, pageToken, parentFolder) as any; - this.renderFileList(files, currentFolderId, parentFolder, container); - - // Update the previous page token when navigating forward. - if (pageToken !== null) { - this.previousPageToken = pageToken; - } - // Update the next page token. - this.nextPageToken = nextPageToken; - // Update the visibility of the pagination buttons. - (container.querySelector('#previous-page') as any).style.display = this.previousPageToken ? 'block' : 'none'; - (container.querySelector('#next-page') as any).style.display = this.nextPageToken ? 'block' : 'none'; - } catch (error) { - console.error('Error updating file list:', error); - } - } - - - renderFileList(files, currentFolderId = this.directory, parentFolder, container:HTMLElement) { - const fileListContainer = container.querySelector('#file-list'); - const folderPathContainer = container.querySelector('#folder-path'); - - if (!fileListContainer || !folderPathContainer) { - console.error('File browser elements not found'); - return; - } - - let html = ''; - files.forEach(file => { - html += `
- ${file.name} -
`; - }); - fileListContainer.innerHTML = html; - - this.setupFileItemClick(parentFolder, container); - - if (currentFolderId !== this.directory) { - folderPathContainer.innerHTML = ``; - (container.querySelector('#parent-folder') as any).addEventListener('click', () => { - this.goBackToParentFolder(container); - }); - } else { - folderPathContainer.innerHTML = ''; - } - } - - async goBackToParentFolder(container) { - try { - const currentFolderMetadata = await this.getFileMetadata(this.currentFolderId); - if (currentFolderMetadata && currentFolderMetadata.parents && currentFolderMetadata.parents.length > 0) { - const parentFolderId = currentFolderMetadata.parents[0]; - this.updateFileList(parentFolderId, null, 'parents', container); - this.currentFolderId = parentFolderId; // Update currentFolderId - } else { - console.error('This folder does not have a parent.'); - } - } catch (error) { - console.error('Error going back to parent folder:', error); - } - } - - setupFileItemClick(parentFolder, container) { - const fileItems = container.querySelectorAll('.file-item'); - fileItems.forEach(item => { - item.addEventListener('click', async () => { - const fileId = item.getAttribute('data-id'); - const mimeType = item.getAttribute('data-mime-type'); - const fileName = item.getAttribute('data-name'); - - if (mimeType === 'application/vnd.google-apps.folder') { - this.updateFileList(fileId, null, parentFolder, container); // Updated to navigate into the folder - this.currentFolderId = fileId; // Update currentFolderId - } else { - const downloadedFile = await this.downloadFile(fileId, mimeType); - console.log('Downloaded file:', fileName, downloadedFile); - } - }); - }); - } - - - setupPaginationButtons(folderId, parentFolder, container) { - (container.querySelector('#previous-page') as any).addEventListener('click', () => { - if (this.previousPageToken !== null) { - this.updateFileList(folderId, this.previousPageToken, parentFolder, container); - // Clear the previous page token since we've navigated back. - this.previousPageToken = null; - } - }); - - (container.querySelector('#next-page') as any).addEventListener('click', () => { - if (this.nextPageToken) { - this.updateFileList(folderId, this.nextPageToken, parentFolder, container); - } - }); - } - - - //backup BFS file to drive by name (requires gapi authorization) - backupBFSToDrive = ( - bfsPath:string, - bfsDir='data', - mimeType='application/vnd.google-apps.spreadsheet' - ) => { - return new Promise(async (res,rej) => { - if(!fsInited) await initFS(['data']); - if(this.isLoggedIn){ - fs.readFile(bfsDir+'/'+bfsPath, (e,output)=>{ - if(e) throw e; if(!output) return; - let file = new Blob([output.toString()],{type:'text/csv'}); - this.checkFolder(this.directory, (result)=>{ - console.log(result); - let metadata = { - 'name':bfsPath, - 'mimeType':mimeType, - 'parents':[result.files[0].id] - } - let token = this.gapi.auth.getToken().access_token; - var form = new FormData(); - form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'})); - form.append('file', file); - - var xhr = new XMLHttpRequest(); - xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'); - xhr.setRequestHeader('Authorization', 'Bearer ' + token); - xhr.responseType = 'json'; - xhr.onload = () => { - console.log("Uploaded file id: ",xhr.response.id); // Retrieve uploaded file ID. - //this.listDriveFiles(); - res(true); - }; - xhr.send(form); - }); - }); - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - res(await this.backupBFSToDrive(bfsPath)); //rerun - } - }); - - } - }); - - } - - - //pass a queried drive folder (i.e. from listDriveFiles) - driveToBFS = ( - file:{id:string, name:string, [key:string]:any}, //you need the file id from gdrive - bfsDir='data', - ondownload=(body)=>{}, - mimeType='text/csv' - ) => { - return new Promise((res,rej) => { - if(this.isLoggedIn) { - var request = this.gapi.client.drive.files.export({'fileId': file.id, 'mimeType':mimeType}); - request.then(async (resp) => { - let filename = file.name; - if(!fsInited) await initFS(['data']); - fs.appendFile( - '/'+bfsDir+'/'+filename, - resp.body, - (e)=>{ - if(e) throw e; - ondownload(resp.body); - res(resp.body); - }); - }); - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - res(await this.driveToBFS( - file, - bfsDir, //rerun - ondownload - )) - } - }); - } - }); - } - - -} - - -export const GDriveRoutes = new GDrive(); //need to call init(apiKey,clientId); \ No newline at end of file diff --git a/src/extras/storage/csv.js b/src/extras/storage/csv.js index 35fcdeb8..bdc3f2ad 100644 --- a/src/extras/storage/csv.js +++ b/src/extras/storage/csv.js @@ -4,7 +4,7 @@ export class CSV { //data=["1|2","11|22"], or data=[[1,2,"xyz"],[2,3,"abc"],etc] constructor(onOpen=this.onOpen, saveButtonId=null, openButtonId=null) { this.onOpen = onOpen; - this.notes = []; //order comments by data index {idx:0,text:"comment"} + this.notes = [{idx:0,text:"comment"}]; //order comments by data index if(saveButtonId !== null) { document.getElementById(saveButtonId).addEventListener('click', this.saveCSV); @@ -33,80 +33,65 @@ export class CSV { //data=["1|2","11|22"], or data=[[1,2,"xyz"],[2,3,"abc"],etc] } //Converts an array of strings (e.g. raw data stream text) or an array of arrays representing lines of data into CSVs - static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n", name=new Date().toISOString()){ + static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){ var hiddenElement = document.createElement('a'); hiddenElement.href = "data:text/csv;charset=utf-8," + encodeURI(csvDat); hiddenElement.target = "_blank"; if (name !== "") { - //if(!name.includes('.csv')) name +='.csv'; hiddenElement.download = name; } else{ - hiddenElement.download = new Date().toISOString() + '.csv'; + hiddenElement.download = Date().toISOString(); } hiddenElement.click(); } static openCSV(delimiter = ",", onOpen = (csvDat, header, path)=>{return csvDat, header, path;}) { - return new Promise((res,rej) => { - var input = document.createElement('input'); - input.accept = '.csv'; - input.type = 'file'; - - input.onchange = (e) => { - var file = e.target.files[0]; - var reader = new FileReader(); - reader.onload = (event) => { - var tempcsvData = event.target.result; - var tempcsvArr = tempcsvData.split("\n"); - let header = []; - var csvDat = []; - tempcsvArr.pop(); - tempcsvArr.forEach((row,i) => { - if(i==0){ header = row.split(delimiter); } - else{ - var temp = row.split(delimiter); - csvDat.push(temp); - } - }); - onOpen(csvDat,header,input.value); - input.value = ''; - res({ - data:csvDat, - header:header, - filename:input.value - }); - } - reader.readAsText(file); + var input = document.createElement('input'); + input.accept = '.csv'; + input.type = 'file'; + + input.onchange = (e) => { + var file = e.target.files[0]; + var reader = new FileReader(); + reader.onload = (event) => { + var tempcsvData = event.target.result; + var tempcsvArr = tempcsvData.split("\n"); + let header = []; + var csvDat = []; + tempcsvArr.pop(); + tempcsvArr.forEach((row,i) => { + if(i==0){ header = row.split(delimiter); } + else{ + var temp = row.split(delimiter); + csvDat.push(temp); + } + }); + onOpen(csvDat,header,input.value); + input.value = ''; } - input.click(); - }); - + reader.readAsText(file); + } + input.click(); } //Dump CSV data without parsing it. static openCSVRaw(onOpen = (csvDat, path)=>{return csvDat, path;}) { - return new Promise((res,rej) => { - var input = document.createElement('input'); - input.accept = '.csv'; - input.type = 'file'; - - input.onchange = (e) => { - var file = e.target.files[0]; - var reader = new FileReader(); - reader.onload = (event) => { - var tempcsvData = event.target.result; - onOpen(tempcsvData, input.value); - input.value = ''; - res({ - data:tempcsvData, - filename: input.value - }) - } - reader.readAsText(file); + var input = document.createElement('input'); + input.accept = '.csv'; + input.type = 'file'; + + input.onchange = (e) => { + var file = e.target.files[0]; + var reader = new FileReader(); + reader.onload = (event) => { + var tempcsvData = event.target.result; + onOpen(tempcsvData, input.value); + input.value = ''; } - input.click(); - }) + reader.readAsText(file); + } + input.click(); } onOpen(csvDat=[],header=[]) { // Customize this function in your init script, access data with ex. console.log(serialMonitor.csvDat), where var serialMonitor = new chromeSerial(defaultUI=false) @@ -116,7 +101,7 @@ export class CSV { //data=["1|2","11|22"], or data=[[1,2,"xyz"],[2,3,"abc"],etc] -//e.g. let csv = CSV.openCSVRaw((data,head,path) => { +//e.g. let csv = CSV.openCSV(',',(data,head,path) => { // let name = path.split('/').pop(); // result = parseCSVData(data,name,head); // console.log(result); @@ -145,9 +130,9 @@ export const parseCSVData = ( for(let j = 0; j < line.length; j++){ - if(!result[header[j]]) result[header[j]] = []; - - result[header[j]].push(line[j]); + if(!result[header[j]]) result[header[j]] + + result[header[j]] = line[j]; } } @@ -156,11 +141,7 @@ export const parseCSVData = ( } ) => { - let lines; - if(data.includes('\r')) - lines = data.split('\r\n'); - else lines = data.split('\n'); - + let lines = data.split('\n'); if(!head) head = lines[0]; lines.shift(); @@ -218,27 +199,27 @@ export function toISOLocal(d) { */ //spits out an array of CSV rows in string format with endlines added export const processDataForCSV = (options={}) => { - if(!options.data) return undefined; - if(!Array.isArray(options.data)) options.data = [options.data]; - if(options.data && !options.header) options.header = Object.keys(options.data[0]); - let head = [...options.header]; - if(head.indexOf('timestamp') > -1) { - head.splice(head.indexOf('timestamp') + 1, 0, 'localized'); - } - - let header = head.join(','); + let header = ''; + if(typeof options.data[0] === 'object' && !Array.isArray(options.data[0])){ + if(options.data[0].x) header = 'x,'; + else if (options.data[0].timestamp) header = 'timestamp,localtime,'; + } + let headeridx = 0; - let lines = []; - let foreach = (obj, i) => { + let lines = {}; //associative array (e.g. timestamp = row) + options.data.forEach((obj, i) => { if(Array.isArray(obj)) { //unstructured data just gets pushed into a column for(let j = 0; j < obj.length; j++) { if(!lines[j]) lines[j] = ''; + if(Array.isArray(obj[j])) { + if(j === 0) header[headeridx] += options.header[headeridx]+new Array(obj[j].length-1).fill('').join(','); //add empty spaces lines[j] += obj[j].join(',') + ','; headeridx+=obj[j].length; } else { + if(j === 0) header[headeridx] += options.header[headeridx]+','; lines[j] += obj[j] + ','; headeridx++; } @@ -250,34 +231,42 @@ export const processDataForCSV = (options={}) => { } else if (obj.timestamp) { x = obj.timestamp; } - let keys = options.header; for(let j = 0; j < x.length; j++) { - if(!lines[j]) lines[j] = x[j] + ','; + + if(!lines[x[j]]) lines[x[j]] = x[j] + ','; if(obj.timestamp) { - keys.splice(keys.indexOf('timestamp'), 1); - lines[j] += toISOLocal(obj.timestamp[j]) + ','; //add local timezone data - } else if (obj.x) { - keys.splice(keys.indexOf('x')); - } - let lastIndex = keys.length - 1; - for(let k = 0; k < keys.length; k++) { - const key = keys[k]; - if(Array.isArray(obj[key][j])) { - lines[j] += obj[key][j].join(',') + (k === lastIndex ? '' : ','); - } - else { - lines[j] += obj[key][j] + (k === lastIndex ? '' : ','); + lines[x[j]] += toISOLocal(obj.timestamp[j]) + ','; //add local timezone data + } + + for(const prop in obj) { + if(prop !== 'x') { + if(!lines[x[j]]) lines[x[j]] = ''; + + if(Array.isArray(obj[prop][j])) { + if(j === 0) header[headeridx] += options.header[headeridx]+Array(obj[prop][j].length-1).fill('').join(','); //add empty spaces + lines[x[j]] += obj[prop][j].join(',') + ','; + headeridx+=obj[prop][j].length; + } + else { + if(j === 0) header[headeridx] += options.header[headeridx]+','; + lines[x[j]] += obj[prop][j] + ','; + headeridx++; + } } } } } - } - - options.data.forEach(foreach); + }); + header.splice(header.length-1,1); //remove last comma header += '\n'; - let joined = lines.join('\n'); + let joined = ''; + + for(const prop in lines) { + lines[prop].splice(lines[prop].length-1,1); //splice off the trailing comma + joined += lines[prop] + '\n'; //add a newline + } let result = {filename:options.filename,header:header,body:joined}; diff --git a/src/extras/storage/gdrivetest/.gitignore b/src/extras/storage/gdrivetest/.gitignore deleted file mode 100644 index ac756779..00000000 --- a/src/extras/storage/gdrivetest/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ - -dist -**/node_modules/** -**/*.pem -**/*.pfxs -**/*.key -**/*.lock -**/package-lock.json -**/*.key -**/*.log diff --git a/src/extras/storage/gdrivetest/index.css b/src/extras/storage/gdrivetest/index.css deleted file mode 100644 index d5ea5431..00000000 --- a/src/extras/storage/gdrivetest/index.css +++ /dev/null @@ -1,9 +0,0 @@ -#floatingDiv { - position: absolute; - width: 100px; - height: 100px; - background-color: red; - text-align: center; - vertical-align: middle; - line-height: 100px; /* The same as your div height */ -} \ No newline at end of file diff --git a/src/extras/storage/gdrivetest/index.html b/src/extras/storage/gdrivetest/index.html deleted file mode 100644 index a5aa66e1..00000000 --- a/src/extras/storage/gdrivetest/index.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - Google Drive File Browser - - - - -

Google Drive File Browser

-
Sign in with Google
-
- - - - - \ No newline at end of file diff --git a/src/extras/storage/gdrivetest/index.js b/src/extras/storage/gdrivetest/index.js deleted file mode 100644 index 47635f08..00000000 --- a/src/extras/storage/gdrivetest/index.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - esbuild + nodejs development server. - Begin your javascript application here. This file serves as a simplified entry point to your app, - all other scripts you want to build can stem from here if you don't want to define more entryPoints - and an outdir in the bundler settings. - - Just ctrl-A + delete all this to get started on your app. - -*/ - -import { GDrive } from '../BFS_GDrive'; - -const apiKey = 'YOUR_GOOGLE_API_KEY'; -const clientId = 'YOUR_GOOGLE_CLIENT_ID'; - -const gdrive = new GDrive(apiKey, clientId); - -const authButton = document.getElementById('auth-button'); -authButton.addEventListener('click', async () => { - try { - await gdrive.handleUserSignIn(); - authButton.style.display = 'none'; - gdrive.createFileBrowser('file-browser-container'); - } catch (error) { - console.error('Error signing in:', error); - } -}); - diff --git a/src/extras/storage/gdrivetest/package.json b/src/extras/storage/gdrivetest/package.json deleted file mode 100644 index 271c951d..00000000 --- a/src/extras/storage/gdrivetest/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "tinybuildapp7431", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \"npm run python\" \"npm start\"", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "", - "dependencies": { - "browserfs": "^1.4.3" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} diff --git a/src/extras/storage/gdrivetest/tinybuild.config.js b/src/extras/storage/gdrivetest/tinybuild.config.js deleted file mode 100644 index cf06d3b8..00000000 --- a/src/extras/storage/gdrivetest/tinybuild.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.js" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:'dist' //exit point folder, define for multiple entryPoints - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files // { platform:'node' } //etc you can also supply an object here to add more specific esbuild settings - bundleTypes: false, //create .d.ts files, //you need a .tsconfig for this to work - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - //bundleIIFE:false, //create an iife build, this is compiled temporarily to create the types files and only saved with bundleIIFE:true - //bundleCommonJS:false, //cjs format outputted as .cjs - minify: true, - sourcemap: false, - //plugins:{} //custom esbuild plugins? e.g. esbuild-sass-plugin for scss support - //includeDefaultPlugins:true //true by default, includes the presets for the streaming imports, worker bundling, and auto npm install - //blobWorkers:true, //package workers as blobs or files? blobs are faster but inflate the main package size - //workerBundler:{minifyWhitespace:true} //bundler settings specific to the worker. e.g. apply platform:'node' when bundling node workers, - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } - // outputs:{ //overwrites main config settings for specific use cases - // node:{ //e.g. for bundleNode - // // external:[] //externals for node environment builds - // }, - // //commonjs:{} //bundleCommonJS - // //browser:{} - // //esm:{} - // iife:{ - // // external:[] //we only use the iife for types so it doesn't really matter if it bundles node, just note otherwise if you need iife for some obscure reason - // } - // }, - - //refer to esbuild docs for more settings - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - //redirect: 'http://localhost:8082' //instead of serving the default content, redirect ot another url e.g. another server - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - reloadscripts: false, //hot swap scripts, can break things if script handles initializations, otherwise css, link, srcs all hot swap without page reloading fairly intelligently - //delay: 50, //millisecond delay on the watch command for hot reloading - //pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - //watch: ['../'], //watch additional directories other than the current working directory - python: false,//7000, //quart server port (configured via the python server script file still) - python_node:7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: 'node_modules/tinybuild/tinybuild/node_server/other/404.html', //default error page, etc. - certpath:'node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem',//if using https, this is required. See cert.pfx.md for instructions - keypath:'node_modules/tinybuild/tinybuild/node_server/ssl/key.pem'//if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/src/extras/storage/sheets_rest.ts b/src/extras/storage/sheets_rest.ts deleted file mode 100644 index 54408e72..00000000 --- a/src/extras/storage/sheets_rest.ts +++ /dev/null @@ -1,210 +0,0 @@ - -function getOrCreateSheet(spreadsheetOptions) { - let { spreadsheetId, sheetName, accessToken } = spreadsheetOptions; - - return fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}?fields=sheets.properties`, { - headers: { - 'Authorization': `Bearer ${accessToken}` - } - }) - .then(response => { - const body = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - const sheets = body.sheets || []; - const sheet = sheets.find(s => s.properties.title === sheetName); - - if (sheet) { - return sheet.properties; - } else { - return createSheet({ spreadsheetId, sheetName, accessToken }); - } - }); -} - -function createSheet(spreadsheetOptions: { - spreadsheetId?: string; - sheetName: string; - accessToken: string; -}) { - - let { spreadsheetId, sheetName, accessToken } = spreadsheetOptions; - - const data = { - requests: [{ - addSheet: { - properties: { - title: sheetName - } - } - }] - }; - - return fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}:batchUpdate`, { - method: 'POST', - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(data) - }) - .then(response => { - const body = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - const sheet = body.replies[0].addSheet.properties; - return sheet; - }); - -} - -async function init(spreadsheetOptions: { - accessToken: string; - spreadsheetName?: string; //either - spreadsheetId?: string; //or - sheetName?: string; -}) { - if (!spreadsheetOptions.spreadsheetId) { - if (!spreadsheetOptions.spreadsheetName) { - throw new Error('Either spreadsheetId or spreadsheetName must be provided'); - } - - // Query Google Drive API to get the spreadsheet ID by name - const driveApiUrl = `https://www.googleapis.com/drive/v3/files?q=name='${spreadsheetOptions.spreadsheetName}'&mimeType='application/vnd.google-apps.spreadsheet'&fields=files(id,name)`; - const driveResponse = await fetch(driveApiUrl, { - headers: { - 'Authorization': `Bearer ${spreadsheetOptions.accessToken}` - } - }); - const driveResponseBody = typeof driveResponse.body === 'string' ? JSON.parse(driveResponse.body) : driveResponse.body; - const file = driveResponseBody.files[0]; - - if (file) { - spreadsheetOptions.spreadsheetId = file.id; - } else { - // If spreadsheet not found, create a new one - const createResponse = await fetch('https://www.googleapis.com/drive/v3/files', { - method: 'POST', - headers: { - 'Authorization': `Bearer ${spreadsheetOptions.accessToken}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - mimeType: 'application/vnd.google-apps.spreadsheet', - name: spreadsheetOptions.spreadsheetName, - }) - }); - let createData = await createResponse.json(); - createData = typeof createData === 'string' ? JSON.parse(createData) : createData; - spreadsheetOptions.spreadsheetId = createData.id; - } - } - - // Fetch spreadsheet to get sheets info - const sheetsResponse = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetOptions.spreadsheetId}?fields=sheets.properties`, { - headers: { - 'Authorization': `Bearer ${spreadsheetOptions.accessToken}` - } - }); - let sheetsData = await sheetsResponse.json(); - sheetsData = typeof sheetsData === 'string' ? JSON.parse(sheetsData) : sheetsData; - - if (!spreadsheetOptions.sheetName) { - if (sheetsData.sheets && sheetsData.sheets.length > 0) { - spreadsheetOptions.sheetName = sheetsData.sheets[0].properties.title; - } else { - throw new Error('No sheets found in the spreadsheet'); - } - } - - const sheetProperties = await getOrCreateSheet({ spreadsheetId: spreadsheetOptions.spreadsheetId, sheetName: spreadsheetOptions.sheetName, accessToken: spreadsheetOptions.accessToken }); - const sheetIndex = sheetProperties.sheetId; - console.log('Sheet exists or was created:', sheetProperties.title, 'with Sheet Index:', sheetIndex); -} - -async function readRange(spreadsheetOptions: { - spreadsheetId: string; - sheetName: string; - range?: string; - accessToken: string; - }): Promise { - const { spreadsheetId, sheetName, range, accessToken } = spreadsheetOptions; - - // If range is provided, use it; otherwise, default to the entire sheet - const fullRange = range ? `${sheetName}!${range}` : sheetName; - const url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${fullRange}`; - const response = await fetch(url, { - headers: { - 'Authorization': `Bearer ${accessToken}` - } - }); - - if (!response.ok) { - throw new Error('Network response was not ok: ' + response.statusText); - } - - const responseBody = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - return responseBody.values || []; -} - -async function writeRange(spreadsheetOptions: { - spreadsheetId: string; - range: string; - values: any[][]; - accessToken: string; -}): Promise { - const { spreadsheetId, range, values, accessToken } = spreadsheetOptions; - - const url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${range}:batchUpdate`; - const response = await fetch(url, { - method: 'POST', - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - valueInputOption: 'USER_ENTERED', - data: [ - { - range: range, - values: values - } - ] - }) - }); - - const responseBody = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - if (!response.ok) { - throw new Error('Network response was not ok ' + (responseBody.error?.message || response.statusText)); - } - return responseBody; -} - - -async function demo( - accessToken='YOUR_ACCESS_TOKEN', - spreadsheetName='MySpreadsheet', - sheetName='Sheet1' -) { - const spreadsheetOptions = { - accessToken, - spreadsheetName, // Either provide this... - //spreadsheetId: 'your-spreadsheet-id', // Or provide this - sheetName - } as any; - - // Initialize the spreadsheet - await init(spreadsheetOptions); - console.log('Spreadsheet initialized.'); - - // Read data from the spreadsheet - const readOptions = { ...spreadsheetOptions, range: 'A1:B2' }; - const data = await readRange(readOptions); - console.log('Data read from the spreadsheet:', data, readOptions); - - // Write data to the spreadsheet - const writeOptions = { ...spreadsheetOptions, range: 'A3', values: [['Hello', 'World'], ['How', 'are you?']] }; - await writeRange(writeOptions); - console.log('Data written to the spreadsheet.', writeOptions); -} - -// // Run the demo -// demo() -// .then(() => console.log('Demo completed successfully')) -// .catch(error => console.error('Demo failed with error:', error)); \ No newline at end of file diff --git a/src/extras/struct/Struct.backend.ts b/src/extras/struct/Struct.backend.ts index 5d0fc613..0b3e29f7 100644 --- a/src/extras/struct/Struct.backend.ts +++ b/src/extras/struct/Struct.backend.ts @@ -1,28 +1,21 @@ -import { ObjectId } from "./datastructures/bson.cjs" +import ObjectID from "bson-objectid" import { AuthorizationStruct, CommentStruct, GroupStruct, ProfileStruct } from "./datastructures/types"; -import { genTimestampFromString, TimeSpecifier } from './genTimestamps' import { Service } from "../../services/Service"; import { User } from '../../services/router/Router'; -import { DS } from "./datastructures/index.js"; - -//todo: -//edit notification system to register to a single object for all notification associated for a single user, saves some space -//template a finer-grained permission system -//instructions - const randomId = (prefix?) => ((prefix) ? `${prefix}_` : '') + Math.floor(1000000000000000*Math.random()) -export const toObjectId = (str) => { - return (typeof str === 'string' && str.length === 24) ? new ObjectId(str) : str //wraps a string with an ObjectId if it isn't +export const toObjectID = (str) => { + return (typeof str === 'string' && str.length === 24) ? ObjectID(str) : str //wraps a string with an objectid if it isn't } -export const getStringId = (mongoid:string|ObjectId) => { - if(typeof mongoid === 'object') return mongoid.toString() //parse strig from mongo ObjectId +export const getStringId = (mongoid:string|ObjectID) => { + if(typeof mongoid === 'object') return mongoid.toString() //parse strig from mongo objectid else return mongoid; } type CollectionsType = { + users?: CollectionType [x:string]: CollectionType } @@ -59,100 +52,77 @@ export class StructBackend extends Service { debug:boolean=false; db: any; // mongodb instance (mongoose) - users:{[key:string]:User} = {}; - collections: CollectionsType = {}; - mode: 'local' | 'mongo' | string = 'local'; - - useAuths: boolean = true; //check if the user querying has the correct permissions - useAccessTokens: boolean = false; //extra security - useRefreshTokens: boolean = false; //fallback - - accessTokens:Map = new Map(); - refreshTokens:Map = new Map(); + users:{[key:string]:User} = {} + collections: CollectionsType = {} + mode: 'local' | 'mongodb' | string + useAuths: boolean = true //check if the user querying has the correct permissions constructor( options?:any, dboptions?:{ users?:{[key:string]:User}, - mode?:'local' | 'mongo' | string, + mode?:'local' | 'mongodb' | string, db?:any, //mongodb instance (mongoose) - collections?:CollectionsType, - useAuths?:boolean, - debug?:boolean, - useAccessTokens?:boolean, - useRefreshTokens?:boolean + collections?:CollectionsType } ) { super(options); this.load(this); - - if(dboptions) { - this.initDB(dboptions); - } - - } - - initDB = (dboptions) => { - this.db = dboptions.db; if(dboptions?.users) this.users = dboptions.users; //set the reference so this keeps concurrent with the user router - if(dboptions.mode) this.mode = dboptions.mode; + if(dboptions?.db) this.mode = (this.db) ? ((dboptions.mode) ? dboptions.mode : 'local') : 'local' if(dboptions?.collections) this.collections = dboptions.collections; - if(dboptions.debug) this.debug = dboptions.debug; - if(dboptions.useAccessTokens) this.useAccessTokens = dboptions.useAccessTokens; - if(dboptions.useRefreshTokens) this.useRefreshTokens = dboptions.useRefreshTokens; - if('useAuths' in dboptions) this.useAuths = dboptions.useAuths; - defaultCollections.forEach(k => { if (!this.collections[k]) { this.collections[k] = (this.db) ? {instance: this.db.collection(k)} : {} this.collections[k].reference = {} } - }); + }) + + } //------------------------------------ //routes to be loaded - query = async (requestingUserId:string,collection?:any,queryObj?:any,findOne?:boolean,skip?:number, token?:string) => { + query = async (requestingUserId:string,collection?:any,queryObj?:any,findOne?:boolean,skip?:number) => { let user = this.users[requestingUserId]; if(!user) return false; if(this.mode.indexOf('mongo') > -1) { - return await this.queryMongo(user,collection,queryObj,findOne,skip,token) + return await this.queryMongo(user,collection,queryObj,findOne,skip) } else { let res = this.getLocalData(user,collection); if(res && !Array.isArray(res)) { let passed = !this.useAuths; if(!res?.ownerId) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,res,'READ',token); - if(passed) return res; + else if(this.useAuths) passed = await this.checkAuthorization(user,res); } if(typeof skip === 'number' && Array.isArray(res)) if(res.length > skip) res.splice(0,skip); let data:any[] = []; if(res) await Promise.all(res.map(async(s) => { let struct = this.getLocalData(getStringId(s._id)); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); })); return data; } } - getUser = async (requestingUserId:string, lookupId:string, basicInfo?:boolean, token?:string) => { + getUser = async (requestingUserId:string, lookupId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data:any; if(this.mode.indexOf('mongo') > -1) { - data = await this.getMongoUser(user, lookupId, undefined, basicInfo, token); + data = await this.getMongoUser(user,lookupId); } else { let struct = this.getLocalData('profile',{_id:lookupId}); - if(!struct) data = {user:undefined}; + if(!struct) data = {user:{}}; else { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) { let groups = this.getLocalData('group',{ownerId:lookupId}); let auths = this.getLocalData('authorization',{ownerId:lookupId}); @@ -164,62 +134,36 @@ export class StructBackend extends Service { return data; } - setUser = async (requestingUserId:string, struct:Partial, token:string) => { + setUser = async (requestingUserId:string, struct:Partial) => { let user = this.users[requestingUserId]; if(!user) return false; let data:any; - - if(struct.accessToken) { - this.accessTokens.set(requestingUserId, token); - } - if(struct.refreshToken) { - this.refreshTokens.set(requestingUserId, struct.refreshToken); - } - - //don't save these to mongodb - delete struct.accessToken; - delete struct.refreshToken; - - //delete on user object too, just to be sure its only on the structbackend object - delete user.accessToken; - delete user.refreshToken; - if(this.mode.indexOf('mongo') > -1) { - data = await this.setMongoUser(user,struct,token); + data = await this.setMongoUser(user,struct); } else { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct, 'WRITE', token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct, 'WRITE'); if(passed) this.setLocalData(struct); return true; - } - if(this.debug) console.log('setUser user:',user,'input:',struct,'output',data); - return data; + } + if(this.debug) console.log('setUser user:',user,'input:',struct,'output',data) + return data; } - getUsersByIds = async (requestingUserId:string, userIds:string[], basicInfo?:boolean) => { + getUsersByIds = async (requestingUserId:string, userIds:string[]) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoUsersByIds(user, userIds, basicInfo); + data = await this.getMongoUsersByIds(user,userIds); } else { data = []; if(Array.isArray(userIds)) { let struct = this.getLocalData('profile',{_id:userIds}); - if(struct) { - if(basicInfo) data.push({ - _id:struct._id, - username:struct.username, - firstName:struct.firstName, - lastName:struct.lastName, - fullName:struct.fullName, - pictureUrl:struct.pictureUrl - }) - else data.push(struct); - } + if(struct) data.push(struct); } } if(this.debug) console.log('getUserByIds: user:',user,'input:',userIds,'output',data) @@ -246,20 +190,20 @@ export class StructBackend extends Service { return data; } - deleteUser = async (requestingUserId:string, userId:string, deleteData?:boolean, token?:string) => { + deleteUser = async (requestingUserId:string, userId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoUser(user,userId,deleteData,token); + data = await this.deleteMongoUser(user,userId); } else { data = false; let struct = this.getLocalData(userId); if(struct) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(passed) data = this.deleteLocalData(struct); } } @@ -267,26 +211,25 @@ export class StructBackend extends Service { return data; } - setData = async (requestingUserId:string, structs:any[], notify?:boolean, token?:string) => { + setData = async (requestingUserId:string, structs:any[], notify?:boolean) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.setMongoData(user,structs,notify,token); //input array of structs - + data = await this.setMongoData(user,structs,notify); //input array of structs } else { let non_notes:any[] = []; data = []; await Promise.all(structs.map(async(structId) => { let struct = this.getLocalData(structId); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE'); if(passed) { if(!this.collections[struct.structType]) { - this.collections[struct.structType] = {} + this.collections[struct.structType] = (this.db) ? {instance: this.db.collection(struct.structType)} : {} this.collections[struct.structType].reference = {} } this.setLocalData(struct); @@ -302,13 +245,13 @@ export class StructBackend extends Service { return data; } - getData = async (requestingUserId:string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number, token?:string) => { + getData = async (requestingUserId:string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoData(user, collection, ownerId, dict, limit, skip, token); + data = await this.getMongoData(user, collection, ownerId, dict, limit, skip); } else { data = []; let structs; @@ -318,8 +261,8 @@ export class StructBackend extends Service { if(structs) await Promise.all(structs.map(async(s) => { let struct = this.getLocalData(getStringId(s._id)); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); })); } @@ -327,13 +270,13 @@ export class StructBackend extends Service { return data; } - getDataByIds = async (requestingUserId:string, structIds:string[], ownerId?:string, collection?:string, token?:string) => { + getDataByIds = async (requestingUserId:string, structIds:string[], ownerId?:string, collection?:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoDataByIds(user, structIds, ownerId, collection, token); + data = await this.getMongoDataByIds(user, structIds, ownerId, collection); } else { data = []; let structs; @@ -342,8 +285,8 @@ export class StructBackend extends Service { if(structs)await Promise.all(structs.map(async(s) => { let struct = this.getLocalData(getStringId(s._id)); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); })); } @@ -351,12 +294,13 @@ export class StructBackend extends Service { return data; } - getAllData = async (requestingUserId:string, ownerId:string, excludedCollections?:string[], timeRange?:[number|TimeSpecifier,number|TimeSpecifier], token?:string) => { + getAllData = async (requestingUserId:string, ownerId:string, excludedCollections?:string[]) => { let user = this.users[requestingUserId]; if(!user) return false; + let data; if(this.mode.includes('mongo')) { - data = await this.getAllUserMongoData(user,ownerId,excludedCollections, timeRange, token); + data = await this.getAllUserMongoData(user,ownerId,excludedCollections); } else { let result = this.getLocalData(undefined,{ownerId:ownerId}); data = []; @@ -364,15 +308,15 @@ export class StructBackend extends Service { if(excludedCollections) { if(excludedCollections.indexOf(struct.structType) < 0) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); } } else { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); } })); @@ -381,20 +325,20 @@ export class StructBackend extends Service { return data; } - deleteData = async (requestingUserId:string, structIds:string[], token?:string) => { + deleteData = async (requestingUserId:string, structIds:string[]) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoData(user,structIds,token); + data = await this.deleteMongoData(user,structIds); } else { data = false; await Promise.all(structIds.map(async (structId) => { let struct = this.getLocalData(structId); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(passed) this.deleteLocalData(struct); data = true; })); @@ -423,7 +367,7 @@ export class StructBackend extends Service { } else { result.forEach((struct)=>{ - if(Object.keys(struct.users).includes(getStringId(user._id as string|ObjectId))) data.push(struct); + if(Object.keys(struct.users).includes(getStringId(user._id as string|ObjectID))) data.push(struct); }); } } @@ -432,19 +376,19 @@ export class StructBackend extends Service { return data; } - deleteGroup = async (requestingUserId:string, groupId:string, token?:string) => { + deleteGroup = async (requestingUserId:string, groupId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoGroup(user,groupId,token); + data = await this.deleteMongoGroup(user,groupId); } else { let struct = this.getLocalData('group',groupId); let passed = !this.useAuths; if(struct) { - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); } if(passed) { data = true; @@ -454,13 +398,13 @@ export class StructBackend extends Service { return data; } - getAuthorizations = async (requestingUserId:string, ownerId?: string, authId?: string, token?:string) => { + getAuthorizations = async (requestingUserId:string, ownerId?: string, authId?: string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoAuthorizations(user,ownerId,authId, token); + data = await this.getMongoAuthorizations(user,ownerId,authId); } else { if(authId) { let result = this.getLocalData('authorization',{_id:authId}); @@ -473,21 +417,21 @@ export class StructBackend extends Service { return data; } - deleteAuthorization = async (requestingUserId:string, authId:string, token?:string) => { + deleteAuthorization = async (requestingUserId:string, authId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoAuthorization(user,authId,token); + data = await this.deleteMongoAuthorization(user,authId); } else { data = true; let struct = this.getLocalData('authorization',{_id:authId}); if(struct) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(passed) data = this.deleteLocalData(struct); } } @@ -498,14 +442,8 @@ export class StructBackend extends Service { //------------------------------------ //internalish stuff - - getToken = (user:Partial) => { - return this.useAccessTokens ? this.accessTokens.get(user._id) - : - this.useRefreshTokens ? this.refreshTokens.get(user._id) : undefined - } - notificationStruct = (parentStruct:any= {}) => { + notificationStruct(parentStruct:any= {}) { let structType = 'notification'; let struct = { structType:structType, @@ -515,18 +453,15 @@ export class StructBackend extends Service { alert:false, //can throw an alert if there is an alert flag on the struct ownerId: '', parentUserId: '', - parent: { - structType:parentStruct?.structType, - _id:getStringId(parentStruct?._id) - }, //where it belongs + parent: {structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}, //where it belongs }; return struct; } //when passing structs to be set, check them for if notifications need to be created - //TODO: need to make this more flexible in the cases you DON'T want an update. I.e. a notification filter struct. - checkToNotify = async (user:Partial,structs:any[]=[], mode=this.mode) => { + //TODO: need to make this more flexible in the cases you DON'T want an update + async checkToNotify(user:Partial,structs:any[]=[], mode=this.mode) { //console.log('CHECK TO NOTIFY', structs) if(structs.length === 0) return false; if(typeof user === 'string') { @@ -542,9 +477,9 @@ export class StructBackend extends Service { let newNotifications :any[] = []; structs.forEach(async (struct)=>{ if(struct?._id) { - if (struct.ownerId && user?._id !== struct.ownerId) { //a struct you own being updated by another user + if (user?._id !== struct.ownerId) { //a struct you own being updated by another user let newNotification = this.notificationStruct(struct); - newNotification._id = 'notification_'+getStringId(struct._id)+'_'+struct.ownerId; //overwrites notifications for the same parent + newNotification._id = 'notification_'+getStringId(struct._id); //overwrites notifications for the same parent newNotification.ownerId = struct.ownerId; newNotification.note = struct.structType; //redundant now newNotification.parentUserId = struct.ownerId; @@ -557,7 +492,7 @@ export class StructBackend extends Service { Object.keys(struct.users).forEach((usr)=>{ if(usr !== user._id as string) { let newNotification = this.notificationStruct(struct); - newNotification._id = 'notification_'+getStringId(struct._id)+'_'+usr; //overwrites notifications for the same parent + newNotification._id = 'notification_'+getStringId(struct._id); //overwrites notifications for the same parent newNotification.ownerId = usr; newNotification.note = struct.structType; if(struct.alert) newNotification.alert = struct.alert; @@ -571,9 +506,8 @@ export class StructBackend extends Service { let auths :any[] = []; if(mode.includes('mongo')) { let s = this.collections.authorization.instance.find({ $or:[{authorizedId: user._id as string},{authorizerId: user._id as string}] }); - let arr = await s.toArray(); - if(arr.length > 0) { - arr.forEach(d => auths.push(d)); + if(await s.count() > 0) { + await s.forEach(d => auths.push(d)); } } else { auths = this.getLocalData('authorization',{authorizedId:user._id as string}); @@ -585,7 +519,7 @@ export class StructBackend extends Service { if(auth.status === 'OKAY' && auth.authorizations['peer']) { let newNotification = this.notificationStruct(struct); newNotification.ownerId = auth.authorizedId; - newNotification._id = 'notification_'+getStringId(struct._id)+'_'+auth.authorizedId; //overwrites notifications for the same parent + newNotification._id = 'notification_'+getStringId(struct._id); //overwrites notifications for the same parent newNotification.note = struct.structType; newNotification.parentUserId = struct.ownerId; if(struct.alert) newNotification.alert = struct.alert; @@ -603,14 +537,13 @@ export class StructBackend extends Service { //console.log('NEW NOTIFICATIONS', newNotifications) if(newNotifications.length > 0) { if(mode.includes('mongo')){ - //console.log('new notes', newNotifications); - await this.setMongoData(user, newNotifications, true, this.getToken(user)); //set the DB, let the user get them + await this.setMongoData(user, newNotifications); //set the DB, let the user get them } else { this.setLocalData(newNotifications); } // console.log(usersToNotify); for(const uid in usersToNotify) { - this.users[uid]?.sendAll({route:'structNotification',args:true}); //notify on all available connections for a user (e.g. phone + laptop) + this.users[uid].send({route:'structNotification',args:true}); } return true; @@ -618,50 +551,50 @@ export class StructBackend extends Service { } //general mongodb query - queryMongo = async (user:Partial,collection:string, queryObj:any={}, findOne:boolean=false, skip:number=0, token?:string) => { + async queryMongo(user:Partial,collection:string, queryObj:any={}, findOne:boolean=false, skip:number=0) { if(!collection && !queryObj) return undefined; else if(findOne){ - let res = await this.db.collection(collection).findOne(queryObj); + let res = this.db.collection(collection).findOne(queryObj); if(!res) return undefined; let passed = !this.useAuths; if(!res?.ownerId) { //return anyway if not matching our struct format passed = true; } else if((getStringId(user._id as string) !== res.ownerId || (getStringId(user._id as string) === res.ownerId && (user.userRoles as any)?.admincontrol))) { - if(this.useAuths) passed = await this.checkAuthorization(user,res,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,res); } if(passed) return res; else return undefined; } else { - let res = this.db.collection(collection).find(queryObj).sort({ $natural: -1 }).skip(skip); + let res = await this.db.collection(collection).find(queryObj).sort({ $natural: -1 }).skip(skip); let structs :any[] = []; - let arr = await res.toArray(); - if(arr.length > 0) { + if(await res.count() > 0) { let passed = !this.useAuths; let checkedAuth = ''; - for(const s of arr){ + await res.forEach(async (s) => { if(!s?.ownerId) { //return anyway if not matching our struct format passed = true; } else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed) structs.push(s); - } + }) } return structs; } } //structs can be Struct objects or they can be an array with a secondary option e.g. [Struct,{$push:{x:[1,2,3]}}] - setMongoData = async (user:Partial,structs:any[] = [], notify=true, token?:string) => { + async setMongoData(user:Partial,structs:any[] = [], notify=true) { - //console.log(user,structs); + //console.log(structs,user); let firstwrite = false; + //console.log(structs); if(structs.length > 0) { let passed = !this.useAuths; let checkedAuth = ''; @@ -671,37 +604,33 @@ export class StructBackend extends Service { secondary = struct[1]; struct = struct[0]; } - - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; //if no owner, it's public + if(!struct?.ownerId) passed = true; //if no owner, it's public else if((getStringId(user._id as string) !== struct.ownerId || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== struct.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); checkedAuth = struct.ownerId; } if(passed) { if(struct.structType) { if(!this.collections[struct.structType]) { - this.collections[struct.structType] = {} + this.collections[struct.structType] = (this.db) ? {instance: this.db.collection(struct.structType)} : {} this.collections[struct.structType].reference = {} } let copy = JSON.parse(JSON.stringify(struct)); if(copy._id) delete copy._id; //if(copy._id && copy.structType !== 'profile' && copy.structType !== 'notification') - //else copy._id = toObjectId(struct._id); + //else copy._id = toObjectID(struct._id); //if(struct.structType === 'notification') console.log(struct); if (struct._id) { if(getStringId(struct._id).includes('defaultId')) { - await this.db.collection(struct.structType ? struct.structType : 'data').insertOne(copy); + await this.db.collection(struct.structType).insertOne(copy); firstwrite = true; } - else if (struct.structType === 'notification') - await this.db.collection(struct.structType ? struct.structType : 'data').updateOne( - {_id:struct._id}, {$set: copy, ...secondary}, {upsert: true, unique: false} - ); - else await this.db.collection(struct.structType ? struct.structType : 'data').updateOne({_id: toObjectId(struct._id)}, {$set: copy, ...secondary}, {upsert: true}); + else if (struct.structType === 'notification') await this.db.collection(struct.structType).updateOne({parent: struct.parent, _id:struct._id}, {$set: copy, ...secondary}, {upsert: true, unique: false}); + else await this.db.collection(struct.structType).updateOne({_id: toObjectID(struct._id)}, {$set: copy, ...secondary}, {upsert: true}); } else if(struct.structType) { - this.db.collection(struct.structType ? struct.structType : 'data').insertOne(copy); + this.db.collection(struct.structType).insertOne(copy); } } } @@ -739,7 +668,7 @@ export class StructBackend extends Service { let pulledReply; await Promise.all(['discussion','chatroom','comment'].map(async (name) => { - let found = await this.db.collection(name).findOne({_id:toObjectId(replyToId)}); + let found = await this.db.collection(name).findOne({_id:toObjectID(replyToId)}); if(found) pulledReply = found; })); //console.log(pulledReply) @@ -777,7 +706,7 @@ export class StructBackend extends Service { await Promise.all(toUpdate.map(async(s)=>{ let copy = JSON.parse(JSON.stringify(s)); delete copy._id; - await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set: copy},{upsert: false}); + await this.db.collection(s.structType).updateOne({_id:toObjectID(s._id)},{$set: copy},{upsert: false}); })); // console.log('pulled comment',pulledComment) @@ -799,7 +728,6 @@ export class StructBackend extends Service { })); //console.log('toReturn: ',toReturn) if(notify) this.checkToNotify(user,toReturn); - //console.log(toReturn); return toReturn; } else { @@ -814,38 +742,29 @@ export class StructBackend extends Service { else return false; } - setMongoUser = async (user:Partial,struct:Partial, token?:string) => { + async setMongoUser(user:Partial,struct:Partial) { if(struct._id) { //this has a second id that matches the token id - const _id = toObjectId(struct._id); - let usersearch = {_id}; + const _id = toObjectID(struct._id); + let usersearch = (_id !== struct._id) ? { _id } : {id: struct.id}; let userexists = await this.collections.profile.instance.findOne(usersearch); if(userexists) { - if( - getStringId(user._id as string) !== struct.ownerId || - (getStringId(user._id as string) === struct.ownerId && - (user.userRoles as any)?.admincontrol) - ) { + if(getStringId(user._id as string) !== struct.ownerId || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) - passed = true; - else if(this.useAuths) - passed = await this.checkAuthorization(user,struct,'WRITE',token); - if(!passed) - return false; + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); + if(!passed) return false; } } let copy = JSON.parse(JSON.stringify(struct)); - copy._id = _id; if(this.debug) console.log('RETURNS PROFILE', struct) // Only Set _id if Appropriate - await this.collections.profile.instance.updateOne( - usersearch, {$set: copy}, {upsert: true}); + await this.collections.profile.instance.updateOne(usersearch, {$set: copy}, {upsert: true}); user = await this.collections.profile.instance.findOne(usersearch); this.checkToNotify(user, [struct]); @@ -853,23 +772,20 @@ export class StructBackend extends Service { } else return false; } - setGroup = async (user:Partial,struct:any, mode=this.mode, token?:string) => { + async setGroup(user:Partial,struct:any, mode=this.mode) { if(struct?._id) { - - let uid = getStringId(user._id as string); - let exists:any = undefined; if(mode.includes('mongo')) { exists = await this.collections.group.instance.findOne({name:struct.name}); } else { exists = this.getLocalData('group',{_id:getStringId(struct._id)}); } - if(exists && (exists.ownerId !== struct.ownerId || struct.admins.indexOf(uid) < 0) ) return false; //BOUNCE + if(exists && (exists.ownerId !== struct.ownerId || struct.admins.indexOf(getStringId(user._id as string)) < 0) ) return false; //BOUNCE - if(uid !== struct.ownerId) { + if(getStringId(user._id as string) !== struct.ownerId) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(!passed) return false; } @@ -883,11 +799,10 @@ export class StructBackend extends Service { let ids = {}; if(mode.includes('mongo')) { let cursor = this.collections.profile.instance.find({ $or: allusers }); //encryption references - let arr = cursor.toArray(); - if(arr.length > 0) { - arr.forEach((user) => { - users[uid] = user; - ids[uid] = true; + if( await cursor.count() > 0) { + await cursor.forEach((user) => { + users[getStringId(user._id as string)] = user; + ids[getStringId(user._id as string)] = true; }); } } else { @@ -928,12 +843,12 @@ export class StructBackend extends Service { //console.log(struct) if(mode.includes('mongo')){ if(getStringId(struct._id).includes('defaultId')) { - await this.db.collection(struct.structType ? struct.structType : 'data').insertOne(copy); + await this.db.collection(struct.structType).insertOne(copy); delete struct._id; - struct = await this.db.collection(struct.structType ? struct.structType : 'data').findOne(struct); + struct = await this.db.collection(struct.structType).findOne(struct); struct._id = getStringId(struct._id); } - else await this.collections.group.instance.updateOne({ _id: toObjectId(struct._id) }, {$set: copy}, {upsert: true}); + else await this.collections.group.instance.updateOne({ _id: toObjectID(struct._id) }, {$set: copy}, {upsert: true}); } else { this.setLocalData(struct); } @@ -944,174 +859,56 @@ export class StructBackend extends Service { } else return false; } - getMongoUser = ( - user:Partial, - info='', - requireAuth=true, - basicInfo=false, - token?:string - ):Promise<{}|{user:ProfileStruct,authorizations:AuthorizationStruct[], groups:GroupStruct[]|{user:ProfileStruct}}> => { + // + async getMongoUser(user:Partial,info='', bypassAuth=false):Promise<{}|{user:ProfileStruct,authorizations:AuthorizationStruct[], groups:GroupStruct[]|{user:ProfileStruct}}> { return new Promise(async resolve => { const query:any[] = [{email: info},{id: info},{username:info}] - //console.log('creating query with', info); - try {query.push({_id: toObjectId(info)})} catch (e) {console.log('error creating ObjectId with ', info);} + try {query.push({_id: toObjectID(info)})} catch (e) {} let u = await this.collections.profile.instance.findOne({$or: query}); //encryption references - if(!u || u == null) resolve(undefined); + if(!u || u == null) resolve({}); else { - u._id = getStringId(u._id); + u._id = getStringId(u._id) if (!u.ownerId) u.ownerId = u._id - if(basicInfo) { - - if(this.useAccessTokens || this.useRefreshTokens) { - if(this.getToken(user) !== token) //not authorized without a current token - resolve( undefined as any); - } - - let stripped = { - username:u.username, - firstName:u.firstName, - lastName:u.lastName, - fullName:u.fullName, - pictureUrl:u.pictureUrl, - _id:u._id - } - - u = stripped; - - resolve({user:u}); - } else if (requireAuth){ + if (u && bypassAuth === false){ if(getStringId(user._id as string) !== u._id || (getStringId(user._id as string) === u._id && (user.userRoles as any)?.admincontrol)) { // TODO: Ensure that passed users will always have the same ObjectId (not necessarily id...) let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,u,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,u); if(!passed) resolve(undefined as any); } // console.log(u); let authorizations :any[] = []; let auths = this.collections.authorization.instance.find({ownerId:u._id}); - let aarr = await auths.toArray(); - if(auths.toArray().length > 0) { - aarr.forEach(d => authorizations.push(d)); + if((await auths.count() > 0)) { + await auths.forEach(d => authorizations.push(d)); } let gs = this.collections.group.instance.find({users:{$all:[u._id]}}); - let arr = await gs.toArray(); let groups :any[] = []; - if((arr.length > 0)) { - arr.forEach(d => groups.push(d)); + if((await gs.count() > 0)) { + await gs.forEach(d => groups.push(d)); } resolve({user:u, authorizations, groups}); - } else { - if(this.useAccessTokens || this.useRefreshTokens) { - if(this.getToken(user) !== token) //not authorized without a current token - resolve( undefined as any); - } - resolve({user:u}); - } - } - }); - } - - //safely query basic identifying information - queryUsers = ( - user:Partial, - info='', - limit=0, - skip=0, - requireAuth=false, - token?:string - ):Promise<{}|{user:ProfileStruct,authorizations:AuthorizationStruct[], groups:GroupStruct[]|{user:ProfileStruct}}> => { - if(typeof user === 'string') user = this.users[user]; - if(!user) return; - return new Promise(async resolve => { - let q = { $regex: `^${info}`, $options: 'i'}; - const query:any[] = [{email: q},{username:q},{firstName:q},{lastName:q},{name:q}] - - let arr; - - if(this.mode.includes('mongo')) { - let users = this.collections.profile.instance.find({$or: query}, {projection:shallowqueryDummy}).skip(skip); //encryption references - if(limit > 0) users.limit(limit); - await users; - - arr = await users.toArray(); - } else { - arr = [] as any; - for(let i = 0; i < query.length; i++) { - let dat = this.getLocalData('profile',query[i]); - if(Array.isArray(dat)) { - dat.forEach((u) => { - arr.push({ - firstName:u.firstName, - lastName:u.lastName, - fullName:u.fullName, - username:u.username, - pictureUrl:u.pictureUrl - }); - }) - } - else if(dat) arr.push({ - firstName:dat.firstName, - lastName:dat.lastName, - fullName:dat.fullName, - username:dat.username, - pictureUrl:dat.pictureUrl - }); - } - } - - if(requireAuth) { - let result = []; - let strid = getStringId(user._id as string); - for(let i = 0; i < arr.length; i++) { - let u = arr[i]; - u._id = getStringId(u._id); //converts to string - if(strid !== u._id || (strid === u._id && (user.userRoles as any)?.admincontrol)) { - let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,u,'READ',token); - if(passed) result.push(u); - } - } - arr = result; - } else if(this.useAccessTokens || this.useRefreshTokens) { - let tk = this.getToken(user); - if(!tk || tk !== token) //not authorized without a current token - { resolve(false); return; } + } else resolve({user:u}); } - - resolve(arr); - }); } - - getMongoUsersByIds = async (user:Partial, userIds:any[]=[], basicInfo?:boolean) => { + //safely returns the profile id, username, and email and other basic info based on the user role set applied + async getMongoUsersByIds(user:Partial,userIds:any[]=[]) { let usrs :any[] = []; userIds.forEach((u) => { - try {usrs.push({_id:toObjectId(u)});} catch {} + try {usrs.push({_id:toObjectID(u)});} catch {} }); - let found :any[] = []; if (usrs.length > 0){ let users = this.collections.profile.instance.find({$or:usrs}); - let arr = await users.toArray(); - //console.log(arr); - if(arr.length > 0) { - arr.forEach((u) => { - if(basicInfo) { - found.push({ - username:u.username, - firstName:u.firstName, - lastName:u.lastName, - fullName:u.fullName, - pictureUrl:u.pictureUrl, - _id:u._id - }) - } - else found.push(u); + if(await users.count() > 0) { + await users.forEach((u) => { + found.push(u); }); } } @@ -1119,28 +916,26 @@ export class StructBackend extends Service { return found as ProfileStruct[]; } - getMongoUsersByRole = async (user:Partial,role:string) => { + //safely returns the profile id, username, and email and other basic info based on the user role set applied + async getMongoUsersByRole(user:Partial,role:string) { let users = this.collections.profile.instance.find({ userRoles:{$all: {[role]:true}} }); let found :any[] = []; - let arr = await users.toArray(); - if(arr.length > 0) { - arr.forEach((u) => { + if(await users.count() > 0) { + await users.forEach((u) => { found.push(u); }); } return found as ProfileStruct[]; } - getMongoDataByIds = async (user:Partial, structIds:string[], ownerId:string|undefined, collection:string|undefined, token?:string) => { - - let uid = getStringId(user._id as string); + async getMongoDataByIds(user:Partial, structIds:string[], ownerId:string|undefined, collection:string|undefined) { if(structIds.length > 0) { let query :any[] = []; structIds.forEach( (_id)=>{ - let q = {_id:toObjectId(_id)}; + let q = {_id:toObjectID(_id)}; if(ownerId) (q as any).ownerId = ownerId; query.push(q); }) @@ -1148,32 +943,30 @@ export class StructBackend extends Service { if(!collection) { await Promise.all(Object.keys(this.collections).map(async (name) => { let cursor = await this.db.collection(name).find({$or:query}); - let arr = await cursor.toArray(); - if(arr.length > 0) { + + if(await cursor.count() > 0) { let passed = true; let checkedAuth = ''; - for(let i = 0; i < arr.length; i++) { - let s = arr[i]; + await cursor.forEach(async (s) => { if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed) found.push(s); - } + }) } })); } else { let cursor = await this.db.collection(collection).find({$or:query}); - let arr = await cursor.toArray(); - if(arr.length > 0) { + if(await cursor.count() > 0) { let passed = true; let checkedAuth = ''; - arr.forEach(async (s) => { + await cursor.forEach(async (s) => { if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed) found.push(s); @@ -1186,89 +979,65 @@ export class StructBackend extends Service { } //get all data for an associated user, can add a search string - getMongoData = async (user:Partial, collection:string|undefined, ownerId:string|undefined, dict:any|undefined={}, limit=0, skip=0, token?:string) => { + async getMongoData(user:Partial, collection:string|undefined, ownerId:string|undefined, dict:any|undefined={}, limit=0, skip=0) { if (!ownerId) ownerId = dict?.ownerId // TODO: Ensure that replacing ownerId, key, value with dict was successful if(!dict) dict = {}; - if (dict._id) dict._id = toObjectId(dict._id) - - let uid = getStringId(user._id as string); + if (dict._id) dict._id = toObjectID(dict._id) let structs :any[] = []; let passed = true; let checkedAuth = ''; - - let cursor; - if(!collection && !ownerId && !dict) return []; else if(!collection && ownerId && Object.keys(dict).length === 0) return await this.getAllUserMongoData(user,ownerId); else if((!dict || Object.keys(dict).length === 0) && ownerId && collection) { - cursor = this.db.collection(collection).find({ownerId}).sort({ $natural: -1 }).skip(skip); - } else if (collection && Object.keys(dict).length > 0) { - if(ownerId) dict.ownerId = ownerId; - cursor = await this.db.collection(collection).find(dict).sort({ $natural: -1 }).skip(skip); - } - - if(cursor) { + let cursor = this.db.collection(collection).find({ownerId}).sort({ $natural: -1 }).skip(skip); if(limit > 0) cursor.limit(limit); - let arr = await cursor.toArray(); - if(arr.length > 0) { - for(let i = 0; i < arr.length; i++) { - let s = arr[i]; + if(await cursor.count() > 0) { + await cursor.forEach(async (s) => { if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed === true) structs.push(s); - } + }); } - } else if (!collection && Object.keys(dict).length > 0 && !ownerId) { //need to search all collections in this case + } else if (Object.keys(dict).length > 0 && ownerId) { + let found = await this.db.collection(collection).findOne({ownerId:ownerId,...dict}); + if(found) structs.push(found); + } else if (Object.keys(dict).length > 0 && !ownerId) { //need to search all collections in this case await Promise.all(Object.keys(this.collections).map(async (name) => { - cursor = await this.db.collection(name).find(dict).sort({ $natural: -1 }).skip(skip);; - if(cursor) { - if(limit > 0) cursor.limit(limit); - let arr = await cursor.toArray(); - if(arr.length > 0) { - for(let i = 0; i < arr.length; i++) { - let s = arr[i]; - if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); - checkedAuth = s.ownerId; - } - if(passed === true) structs.push(s); - } + let found = await this.db.collection(name).findOne(dict); + if(found) { + if(!found?.ownerId) passed = true; + else if((getStringId(user._id as string) !== found.ownerId || (getStringId(user._id as string) === found.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== found.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,found); + checkedAuth = found.ownerId; } + structs.push(found); + return } })); } - //console.log('\n\n\n getData passed:',passed, '\n\n\n res:', JSON.stringify(structs), '\n\nargs', collection, ownerId, JSON.stringify(dict)); - if(!passed) return []; //need to make this better + if(!passed) return []; return structs; } - getAllUserMongoData = async (user:Partial, ownerId, excluded:any[]=[], timeRange?:[number|TimeSpecifier,number|TimeSpecifier], token?:string) => { + async getAllUserMongoData(user:Partial,ownerId,excluded:any[]=[]) { let structs :any[] = []; let passed = true; let checkedId = ''; await Promise.all(Object.keys(this.collections).map(async (name,j) => { if(passed && excluded.indexOf(name) < 0) { - let query = {ownerId:ownerId} as any; - if(timeRange) { - if(typeof timeRange[0] === 'string') timeRange[0] = genTimestampFromString(timeRange[0]); - if(typeof timeRange[1] === 'string') timeRange[1] = genTimestampFromString(timeRange[1]); - query.timestamp = {$gt:timeRange[0],$lt:timeRange[1]}; - } - let cursor = this.db.collection(name).find(query); - let arr = await cursor.toArray(); - let count = arr.length; + let cursor = this.db.collection(name).find({ownerId:ownerId}); + let count = await cursor.count(); for(let k = 0; k < count; k++) { - let struct = arr[k]; + let struct = await cursor.next(); if(!ownerId) passed = true; else if((getStringId(user._id as string) !== ownerId || (getStringId(user._id as string) === ownerId && (user.userRoles as any)?.admincontrol)) && checkedId !== ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,struct); //console.log(passed) checkedId = ownerId; } @@ -1286,19 +1055,19 @@ export class StructBackend extends Service { } //passing in structrefs to define the collection (structType) and id - getMongoDataByRefs = async (user:Partial,structRefs:any[]=[], token?:string) => { + async getMongoDataByRefs(user:Partial,structRefs:any[]=[]) { let structs :any[] = []; //structRef = {structType, id} if(structs.length > 0) { let checkedAuth = ''; structRefs.forEach(async (ref)=>{ if(ref.structType && getStringId(ref._id)) { - let struct = await this.db.collection(ref.structType).findOne({_id: toObjectId(ref._id)}); + let struct = await this.db.collection(ref.structType).findOne({_id: toObjectID(ref._id)}); if(struct) { let passed = true; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; + if(!struct?.ownerId) passed = true; else if((getStringId(user._id as string) !== struct.ownerId || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== struct.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,struct); checkedAuth = struct.ownerId; } if(passed === true) { @@ -1311,62 +1080,60 @@ export class StructBackend extends Service { return structs; } - getMongoAuthorizations = async (user:Partial,ownerId=getStringId(user._id as string), authId='', token?:string) => { + async getMongoAuthorizations(user:Partial,ownerId=getStringId(user._id as string), authId='') { let auths :any[] = []; //console.log(user); if(authId.length === 0 ) { let cursor = this.collections.authorization.instance.find({ownerId:ownerId}); - let arr = await cursor.toArray(); - if(arr.length > 0) { - arr.forEach((a) => { + if(await cursor.count > 0) { + await cursor.forEach((a) => { auths.push(a) }); } } - else auths.push(await this.collections.authorization.instance.findOne({_id: toObjectId(authId), ownerId:ownerId})); + else auths.push(await this.collections.authorization.instance.findOne({_id: toObjectID(authId), ownerId:ownerId})); if(!auths[0]?.ownerId) true; else if(getStringId(user._id as string) !== auths[0]?.ownerId) { let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,auths[0],'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,auths[0]); if(!passed) return undefined; } return auths as AuthorizationStruct[]; } - getMongoGroups = async (user:Partial, userId=getStringId(user._id as string), groupId='') => { + async getMongoGroups(user:Partial, userId=getStringId(user._id as string), groupId='') { let groups :any[] = []; if(groupId.length === 0 ) { let cursor = this.collections.group.instance.find({users:{$all:[userId]}}); - let arr = await cursor.toArray(); - if(arr.length > 0) { - arr.forEach((a) => { + if(await cursor.count > 0) { + await cursor.forEach((a) => { groups.push(a) }); } } else { - try {groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId), users:{$all:[userId]}}));} catch {} + try {groups.push(await this.collections.group.instance.findOne({_id:toObjectID(groupId), users:{$all:[userId]}}));} catch {} } return groups as GroupStruct[]; } //general delete function - deleteMongoData = async (user:Partial,structRefs:any[]=[], token?:string) => { + async deleteMongoData(user:Partial,structRefs:any[]=[]) { // let ids :any[] = []; let structs :any[] = []; await Promise.all(structRefs.map(async (ref) => { try { - let _id = toObjectId(ref._id) + let _id = toObjectID(ref._id) let struct = await this.db.collection(ref.structType).findOne({_id}); if(struct) { structs.push(struct); let notifications = await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}}); - let count = notifications.toArray().length; + let count = await notifications.count(); for(let i = 0; i < count; i++) { let note = await notifications.next(); if(note) structs.push(note); //remove any associated notifications with a piece of data @@ -1379,23 +1146,22 @@ export class StructBackend extends Service { let checkedOwner = ''; await Promise.all(structs.map(async (struct,i)=>{ let passed = true; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; + if(!struct?.ownerId) passed = true; else if((struct.ownerId !== getStringId(user._id as string) || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) && struct.ownerId !== checkedOwner) { checkedOwner = struct.ownerId; - if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE'); } if(passed) { //console.log(passed); - await this.db.collection(struct.structType ? struct.structType : 'data').deleteOne({_id:toObjectId(struct._id)}); + await this.db.collection(struct.structType).deleteOne({_id:toObjectID(struct._id)}); //delete any associated notifications, too if(struct.users) { Object.keys(struct.users).forEach((uid)=> { - if(uid !== getStringId(user._id as string) && uid !== struct.ownerId && this.users[uid]) - this.users[uid]?.sendAll({route:'structDeleted',args:{_id:getStringId(struct._id),structType:struct.structType}}) + if(uid !== getStringId(user._id as string) && uid !== struct.ownerId && this.users[uid]) this.users[uid].send({route:'structDeleted',args:getStringId(struct._id)}) }); } if(struct.ownerId !== user._id as string && this.users[struct.ownerId]) { - this.users[struct.ownerId]?.sendAll({route:'structDeleted',args:{_id:getStringId(struct._id),structType:struct.structType}}) + this.users[struct.ownerId].send({route:'structDeleted',args:getStringId(struct._id)}) } } })); @@ -1404,83 +1170,63 @@ export class StructBackend extends Service { } //specific delete functions (the above works for everything) - deleteMongoUser = async (user:Partial, userId, deleteData?:boolean, token?:string) => { + async deleteMongoUser(user:Partial,userId) { if(getStringId(user._id as string) !== userId || (getStringId(user._id as string) === userId && (user.userRoles as any)?.admincontrol)) { let u = await this.collections.profile.instance.findOne({ id: userId }); let passed = !this.useAuths; if(!u?.ownerId) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,u,'WRITE',token); + else if(this.useAuths) passed = await this.checkAuthorization(user,u,'WRITE'); if(!passed) return false; } await this.collections.profile.instance.deleteOne({ id: userId }); - if(deleteData) { - for(const key in this.collections) { - this.collections[key].instance.deleteMany({ ownerId: userId }); - this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}}); - } - } - - if(getStringId(user._id as string) !== userId && this.users[userId]) this.users[userId]?.sendAll({route:'structDeleted',args:{_id:userId,structType:'profile'}}); + if(getStringId(user._id as string) !== userId && this.users[userId]) this.users[userId].send({route:'structDeleted',args:userId}); //now delete their authorizations and data too (optional?) return true; } - deleteMongoGroup = async (user:Partial,groupId, token?:string) => { - let s = await this.collections.group.instance.findOne({ _id: toObjectId(groupId) }); + async deleteMongoGroup(user:Partial,groupId) { + let s = await this.collections.group.instance.findOne({ _id: toObjectID(groupId) }); if(s) { if(!s?.ownerId) true; else if(getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol) ) { let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE'); if(!passed) return false; } if(s.users) { - Object.keys(s.users).forEach((u) => { - this.users[u]?.sendAll({route:'structDeleted',args:{_id:getStringId(s._id), structType:s.structType}}); - }); + Object.keys(s.users).forEach((u) => { this.users[s.authorizerId].send({route:'structDeleted',args:getStringId(s._id)}); }); } - await this.collections.group.instance.deleteOne({ _id:toObjectId(groupId) }); + await this.collections.group.instance.deleteOne({ _id:toObjectID(groupId) }); return true; } else return false; } - deleteMongoAuthorization = async (user:Partial, authId, token?:string) => { - let s = await this.collections.authorization.instance.findOne({ _id: toObjectId(authId) }); - let uid = getStringId(user._id as string); + async deleteMongoAuthorization(user:Partial,authId) { + let s = await this.collections.authorization.instance.findOne({ _id: toObjectID(authId) }); if(s) { - if(uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) { + if(getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) { let passed = !this.useAuths; if(!s?.ownerId) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE',token); + else if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE'); if(!passed) return false; } - if(s.associatedAuthId) { //belonging to the other user + if(s.associatedAuthId) { if(this.debug) console.log(s); - - await this.collections.authorization.instance.deleteOne({ _id: toObjectId(s.associatedAuthId) }); //remove the other auth too - - if(s.authorizerId !== uid) this.users[s.authorizerId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s.associatedAuthId), structType:s.structType}}); - else if (s.authorizedId !== uid) this.users[s.authorizedId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s.associatedAuthId), structType:s.structType}}); + await this.collections.authorization.instance.deleteOne({ _id: toObjectID(s.associatedAuthId) }); //remove the other auth too + if(s.authorizerId && s.authorizerId !== getStringId(user._id as string)) this.users[s.authorizerId].send({route:'structDeleted',args:getStringId(s._id)}); + else if (s.authorizedId && s.authorizedId !== getStringId(user._id as string)) this.users[s.authorizerId].send({route:'structDeleted',args:getStringId(s._id)}); } - await this.collections.authorization.instance.deleteOne({ _id: toObjectId(authId) }); - - if(s.authorizerId === uid) this.users[s.authorizerId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s._id), structType:s.structType}}); - else if (s.authorizedId === uid) this.users[s.authorizedId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s._id), structType:s.structType}}); - + await this.collections.authorization.instance.deleteOne({ _id: toObjectID(authId) }); return true; } else return false; } - setAuthorization = async ( - user:Partial, - authStruct, - token?:string - ) => { + async setAuthorization(user:Partial, authStruct, mode=this.mode) { //check against authorization db to allow or deny client/professional requests. //i.e. we need to preauthorize people to use stuff and allow each other to view sensitive data to cover our asses @@ -1501,15 +1247,12 @@ export class StructBackend extends Service { */ let u1, u2; - - let mmode = this.mode.includes('mongo'); - - if(mmode) { - u1 = (await this.getMongoUser(user, authStruct.authorizedId, false) as any).user; //can authorize via email, id, or username - u2 = (await this.getMongoUser(user, authStruct.authorizerId, false) as any).user; + if(mode.includes('mongo')) { + u1 = (await this.getMongoUser(user, authStruct.authorizedId, true) as any).user; //can authorize via email, id, or username + u2 = (await this.getMongoUser(user, authStruct.authorizerId, true) as any).user; } else { - u1 = this.getLocalData('profile',{'_id':authStruct.authorizedId})?.[0]; - u2 = this.getLocalData('profile',{'_id':authStruct.authorizerId})?.[0]; + u1 = this.getLocalData('profile',{'_id':authStruct.authorizedId})[0]; + u2 = this.getLocalData('profile',{'_id':authStruct.authorizerId})[0]; } //console.log(u1,u2) @@ -1520,43 +1263,31 @@ export class StructBackend extends Service { if(authStruct.authorizerId !== getStringId(u2._id)) authStruct.authorizerId = getStringId(u2._id); if(!authStruct.authorizedName) { - if(u1.name) authStruct.authorizedName = u1.name; - else if(u1.username) authStruct.authorizedName = u1.username; + if(u1.username) authStruct.authorizedName = u1.username; else if (u1.email) authStruct.authorizedName = u1.email; } if(!authStruct.authorizerName) { - if(u1.name) authStruct.authorizedName = u1.name; - else if(u2.username) authStruct.authorizerName = u2.username; + if(u2.username) authStruct.authorizerName = u2.username; else if (u2.email) authStruct.authorizerName = u2.email; } //console.log(authStruct); if(!authStruct?.ownerId) true; - else if( - (getStringId(user._id as string) !== authStruct.ownerId || ( - getStringId(user._id as string) === authStruct.ownerId && - (user.userRoles as any)?.admincontrol) - ) && - ( - getStringId(user._id as string) !== authStruct.authorizedId && - getStringId(user._id as string) !== authStruct.authorizerId - ) - ) { + else if((getStringId(user._id as string) !== authStruct.ownerId || (getStringId(user._id as string) === authStruct.ownerId && (user.userRoles as any)?.admincontrol)) && (getStringId(user._id as string) !== authStruct.authorizedId && getStringId(user._id as string) !== authStruct.authorizerId)) { let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,authStruct,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user,authStruct,'WRITE'); if(!passed) return false; } let auths :any[] = []; - if(mmode){ - let s = await this.collections.authorization.instance.find( + if(mode.includes('mongo')){ + let s = this.collections.authorization.instance.find( { $and: [ { authorizedId: authStruct.authorizedId }, { authorizerId: authStruct.authorizerId } ] } ); - let arr = await s.toArray(); - if (arr.length > 0) { - arr.forEach(d => auths.push(d)); + if ((await s.count()) > 0) { + await s.forEach(d => auths.push(d)); } } else { let s = this.getLocalData('authorization',{authorizedId:authStruct.authorizedId}); @@ -1569,8 +1300,7 @@ export class StructBackend extends Service { let otherAuthset; if(Array.isArray(auths)) { - for(let i = 0; i < auths.length; i++) { - const auth = auths[i]; + auths.forEach(async (auth) => { if(auth.ownerId === getStringId(user._id as string)) { //got your own auth //do nothing, just update your struct on the server if the other isn't found } else { //got the other associated user's auth, now can compare and verify @@ -1595,53 +1325,36 @@ export class StructBackend extends Service { auth.associatedAuthId = getStringId(authStruct._id); otherAuthset = auth; let copy = JSON.parse(JSON.stringify(auth)); - if(mmode) { + if(mode.includes('mongo')) { delete copy._id; - await this.collections.authorization.instance.updateOne( - { $and: [ - { authorizedId: authStruct.authorizedId }, - { authorizerId: authStruct.authorizerId }, - { ownerId: auth.ownerId } ] - }, {$set: copy}, {upsert: true}); + await this.collections.authorization.instance.updateOne({ $and: [ { authorizedId: authStruct.authorizedId }, { authorizerId: authStruct.authorizerId }, { ownerId: auth.ownerId } ] }, {$set: copy}, {upsert: true}); } else { this.setLocalData(copy); } } - } + }); } let copy = JSON.parse(JSON.stringify(authStruct)); - if(mmode) { + if(mode.includes('mongo')) { delete copy._id; await this.collections.authorization.instance.updateOne({ $and: [ { authorizedId: authStruct.authorizedId }, { authorizerId: authStruct.authorizerId }, { ownerId: authStruct.ownerId } ] }, {$set: copy}, {upsert: true}); } else { this.setLocalData(copy); } - if(getStringId(authStruct._id).includes('defaultId') && mmode) { + if(getStringId(authStruct._id).includes('defaultId') && mode.includes('mongo')) { let replacedAuth = await this.collections.authorization.instance.findOne(copy); if(replacedAuth) { authStruct._id = getStringId(replacedAuth._id); if(otherAuthset) { - let otherAuth = await this.collections.authorization.instance.findOne( - {$and: [ - { authorizedId: otherAuthset.authorizedId }, - { authorizerId: otherAuthset.authorizerId }, - { ownerId: otherAuthset.ownerId } ] - } - ); + let otherAuth = await this.collections.authorization.instance.findOne({$and: [ { authorizedId: otherAuthset.authorizedId }, { authorizerId: otherAuthset.authorizerId }, { ownerId: otherAuthset.ownerId } ] }); if(otherAuth) { otherAuth.associatedAuthId = getStringId(authStruct._id); let copy2 = JSON.parse(JSON.stringify(otherAuth)); delete copy2._id; - await this.collections.authorization.instance.updateOne( - { $and: [ - { authorizedId: otherAuth.authorizedId }, - { authorizerId: otherAuth.authorizerId }, - { ownerId: otherAuth.ownerId } - ] }, {$set: copy2}, {upsert: true} - ); + await this.collections.authorization.instance.updateOne({ $and: [ { authorizedId: otherAuth.authorizedId }, { authorizerId: otherAuth.authorizerId }, { ownerId: otherAuth.ownerId } ] }, {$set: copy2}, {upsert: true}); this.checkToNotify(user,[otherAuth]); } } @@ -1651,28 +1364,17 @@ export class StructBackend extends Service { return authStruct as AuthorizationStruct; //pass back the (potentially modified) authStruct } - //TODO: fine grained struct filtering - checkAuthorization = async ( + + async checkAuthorization( user:string|Partial|{_id:string}, struct, request='READ', //'WRITE' - token?:string - ) => { + mode = this.mode + ) { /* If user is not the owner of the struct, check that they have permissions */ - if(typeof user === 'string') { - if(this.users[user]) - user = this.users[user]; - else user = {_id:user}; - } - //console.log(struct) - // console.log( - // 'user', user._id, - // 'struct', struct - // ) - if(!user || !struct) return false; if(!struct.ownerId) return true; //no owner, return true @@ -1680,73 +1382,32 @@ export class StructBackend extends Service { if(typeof user === 'object') { if(struct.ownerId === getStringId(user._id as string)) { if((user as ProfileStruct).userRoles?.['admincontrol']) { - //do something + //do somethign } - //console.log('is owner') - return true; - } //else console.log('not owner') - } - - if(this.useAccessTokens) { //pass an access token for single client validation - if(!this.accessTokens.get(user._id) || this.accessTokens.get(user._id) !== token) //not authorized without a current token - { - //console.log('failed useAccessTokens') - return false; - } //else console.log('passed useAccessTokens'); - } - else if (this.useRefreshTokens) { //pass a refresh token for multi client validation - if(!this.refreshTokens.get(user._id) || this.refreshTokens.get(user._id) !== token) //not authorized without a current token - { - //console.log('failed useRefreshTokens') - return false; - } //else console.log('passed useRefreshTokens'); + else return true; + } + } else if (typeof user === 'string') { + if(struct.ownerId === user) { + return true; + } + else user = {_id:user}; } let auth1, auth2; - if(this.mode.includes('mongo')) { - auth1 = await this.collections.authorization.instance.findOne( - { $or: [ - { - authorizedId:getStringId(user._id as string), - authorizerId:struct.ownerId, - ownerId:getStringId(user._id as string) - }, - { - authorizedId:struct.ownerId, - authorizerId:getStringId(user._id as string), - ownerId:getStringId(user._id as string) - } - ] - } - ); - if(!auth1) return false; - auth2 = await this.collections.authorization.instance.findOne( - { $or: [ - { - authorizedId:getStringId(user._id as string), - authorizerId:struct.ownerId, - ownerId:getStringId(struct.ownerId as string) - }, - { - authorizedId:struct.ownerId, - authorizerId:getStringId(user._id as string), - ownerId:getStringId(struct.ownerId as string) - } - ] - } - ); + if(mode.includes('mongo')) { + auth1 = await this.collections.authorization.instance.findOne({$or: [{authorizedId:getStringId(user._id as string),authorizerId:struct.ownerId, ownerId:getStringId(user._id as string)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id as string), ownerId:getStringId(user._id as string)}]}); + auth2 = await this.collections.authorization.instance.findOne({$or: [{authorizedId:getStringId(user._id as string),authorizerId:struct.ownerId, ownerId:struct.ownerId},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id as string), ownerId:struct.ownerId}]}); } else { auth1 = this.getLocalData('authorization', {ownerId:getStringId(user._id as string)}).find((o) => { - if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) - return true; + if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) return true; }); auth2 = this.getLocalData('authorization', {ownerId:struct.ownerId}).find((o) => { - if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) - return true; + if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) return true; }); } if(!auth1 || !auth2) { + //console.log('auth bounced', user, struct, auth1, auth2); return false; } @@ -1768,6 +1429,7 @@ export class StructBackend extends Service { if(struct.structType === 'group') { if (auth1.authorizations[struct.name+'_admin'] && auth2.authorizations[struct.name+'_admin']) passed = true; + else passed = false; } //peers have access to most data for a user else if(auth1.authorizations['peer'] && auth2.authorizations['peer']) passed = true; @@ -1841,7 +1503,7 @@ export class StructBackend extends Service { //Local Data stuff (for non-mongodb usage of this server) //just assigns replacement object to old object if it exists, keeps things from losing parent context in UI - overwriteLocalData = (structs) => { + overwriteLocalData (structs) { if(Array.isArray(structs)){ structs.forEach((struct) => { let localdat = this.getLocalData(struct.structType,{'ownerId': struct.ownerId, '_id':getStringId(struct._id)}); @@ -1859,7 +1521,7 @@ export class StructBackend extends Service { } } - setLocalData = (structs) => { + setLocalData (structs) { let setInCollection = (s) => { let type = s.structType; @@ -1882,7 +1544,7 @@ export class StructBackend extends Service { } //pull a struct by collection, owner, and key/value pair from the local platform, leave collection blank to pull all ownerId associated data - getLocalData = (collection, query?): any => { + getLocalData(collection, query?): any { // Split Query let ownerId, key, value; @@ -1950,7 +1612,7 @@ export class StructBackend extends Service { } - deleteLocalData = (struct) => { + deleteLocalData(struct) { if(!struct) throw new Error('Struct not supplied') if(!struct.structType || !struct._id) return false; @@ -1959,13 +1621,4 @@ export class StructBackend extends Service { return true; } -} - - -let shallowqueryDummy = DS.ProfileStruct(); -for(const key in shallowqueryDummy) { - if(key === 'username'||key === 'lastName'||key === 'firstName'||key === 'name'||key === '_id'||key === 'pictureUrl') shallowqueryDummy[key] = 1 as any; - else delete shallowqueryDummy[key]; -} -//console.log(shallowqueryDummy); - +} \ No newline at end of file diff --git a/src/extras/struct/Struct.frontend.ts b/src/extras/struct/Struct.frontend.ts index 815fb349..1e5bc098 100644 --- a/src/extras/struct/Struct.frontend.ts +++ b/src/extras/struct/Struct.frontend.ts @@ -1,9 +1,7 @@ import { DataTablet, DS } from './datastructures/index' import { Data, ProfileStruct, AuthorizationStruct, GroupStruct, DataStruct, EventStruct, ChatroomStruct, CommentStruct, Struct } from './datastructures/types'; -import { genTimestampFromString, TimeSpecifier } from './genTimestamps' import { Service } from '../../services/Service'; import { User } from '../../services/router/Router'; -import { GraphNodeProperties } from '../../core/Graph'; export const randomId = (prefix?) => ((prefix) ? `${prefix}` : '') + Math.floor(1000000000000000*Math.random()) @@ -12,22 +10,14 @@ export const pseudoObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).t //intended for use with a UserRouter -export type StructFrontendProps = { - useAccessTokens?:boolean, - useRefreshTokens?:boolean -} & GraphNodeProperties - export class StructFrontend extends Service { name='structs' - currentUser: User //user from the endpoint service (e.g. websockets, Router) whose endpoints we want to use + currentUser: User //user from the UserRouter whose endpoints we want to use tablet = new DataTablet(); //DataTablet collections = this.tablet.collections; id: string = randomId() - useAccessTokens=false; - useRefreshTokens=false; - constructor( options?:any, user?:Partial @@ -35,21 +25,12 @@ export class StructFrontend extends Service { super(options); this.load(this); - if(options.useAccessTokens) this.useAccessTokens = options.useAccessTokens; - if(options.useRefreshTokens) this.useRefreshTokens = options.useRefreshTokens; - - if(user instanceof Object && Object.keys(user).length > 0) - this.setupUser(user); // Declares currentUser - } - - getToken(user:Partial) { - if(this.useAccessTokens) return user.accessToken; - else if (this.useRefreshTokens) return user.refreshToken; + if (user instanceof Object && Object.keys(user).length > 0) this.setupUser(user) // Declares currentUser } //TODO: make this able to be awaited to return the currentUser //uses a bunch of the functions below to set up a user and get their data w/ some cross checking for consistent profiles - setupUser = async(userinfo:Partial, callback=(currentUser)=>{}) => { + async setupUser(userinfo:Partial, callback=(currentUser)=>{}) { if(!userinfo) { console.error('must provide a minimum info object! e.g. {_id:"abc123"}'); @@ -64,20 +45,18 @@ export class StructFrontend extends Service { // let res = await this.login(); //console.log("Generating/Getting User: ", userinfo._id) - //console.log('getting user'); let res = await this.getUser(userinfo._id); - //console.log('setting user'); let user = res?.user; // console.log('user gotten', user) // console.log("getUser", user); let u; let newu = false; - //console.log('getUser result',user); - + console.log('getUser result',user); if(!user || !user._id) { //no profile, create new one and push initial results // if(!userinfo._id) userinfo._id = userinfo._id; - u = this.userStruct(userinfo,false); + console.log('creating new profile'); + u = this.userStruct(userinfo,true); newu = true; let wasSet = await this.setUser(u); let structs = this.getLocalData(undefined,{'ownerId': u._id}); @@ -90,21 +69,6 @@ export class StructFrontend extends Service { } else { u = user; - - let toUpdate = {_id:userinfo._id, ownerId: userinfo._id}; - let struct = this.userStruct(userinfo,false); - for(const key in struct) { - if((userinfo[key] && user[key] !== userinfo[key])) { - toUpdate[key] = userinfo[key]; - user[key] = userinfo[key]; - } - else if(struct[key] && !user[key]) { - toUpdate[key] = struct[key]; - user[key] = struct[key]; - } - } - - if(Object.keys(toUpdate).length > 2) await this.setUser(toUpdate as any); // u._id = user._id; //replace the unique mongo id for the secondary profile struct with the id for the userinfo for temp lookup purposes if(res?.authorizations){ @@ -122,7 +86,7 @@ export class StructFrontend extends Service { if(newu) {this.setLocalData(u);} else { - let data = await this.getAllUserData(u._id,undefined, [genTimestampFromString('last day'),Date.now()]); //todo: only query latest data + let data = await this.getAllUserData(u._id,undefined); //console.log("getServerData", data); if(!data || data.length === 0) { @@ -157,7 +121,6 @@ export class StructFrontend extends Service { }); if(toDelete.length > 0) this.deleteData(toDelete); //extraneous comments - //console.log('data:', data, 'resolve notifications:', notes); if(notes.length > 0) { this.resolveNotifications(notes, false, undefined); changed = true; @@ -174,12 +137,11 @@ export class StructFrontend extends Service { // u = new UserObj(u) // u = getUserCodes(u, true) this.setLocalData(u); //user is now set up in whatever case - //console.log('collections', this.tablet.collections); + console.log('collections', this.tablet.collections); } //console.log('u::',u) if(u) { - if(this.currentUser) Object.assign(this.currentUser,u); - else this.currentUser = u; + this.currentUser = u; callback(this.currentUser); //console.log('currentUser', u) return this.currentUser; @@ -240,7 +202,7 @@ export class StructFrontend extends Service { delete this.currentUser.userRoles[struct.name+'_client']; uset = true; } - if(uset) this.setUser(this.currentUser as any); //update roles + if(uset) this.setUser(this.currentUser); //update roles } } this.setLocalData(struct); @@ -276,21 +238,21 @@ export class StructFrontend extends Service { }); } + //console.log(data); + if (data?.message === 'notifications') { + //console.log('notifications', this.currentUser); + this.checkForNotifications(); //pull notifications + } + if (data?.message === 'deleted') { + this.deleteLocalData(data.data); //remove local instance + } + this.onResult(data); } - structNotification = () => { - //console.log('struct notifications') - this.checkForNotifications(); - } - - structDeleted = (struct:{_id:string,structType:string}) => { - this.deleteLocalData([struct]); //remove local instance - } - //just a customizable callback to preserve the default while adding your own - onResult = (data) => { - + onResult(data) { + } @@ -311,13 +273,13 @@ export class StructFrontend extends Service { parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) } */ - addStruct = async ( + async addStruct ( structType:string='struct', props:any={}, //add any props you want to set, adding users[] with ids will tell who to notify if this struct is updated parentUser?:{[key:string]:any}, parentStruct?:{[key:string]:any}, updateServer:boolean = true - ) => { + ) { let newStruct = DS.Struct(structType, props, parentUser, parentStruct); if(updateServer) newStruct = await this.updateServerData([newStruct])[0]; @@ -326,40 +288,19 @@ export class StructFrontend extends Service { } //info can be email, id, username, or name. Returns their profile and authorizations - getUser = async (info:string|number='', basicInfo?:boolean, callback=this.baseServerCallback) => { + getUser = async (info:string|number='',callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getUser', args:[this.currentUser._id, info, basicInfo, this.getToken(this.currentUser)]})); + let res = (await this.currentUser.request({route:'getUser', args:[this.currentUser._id, info]}))?.[0]; callback(res); - return (res as {user:ProfileStruct, groups:GroupStruct[], authorizations:AuthorizationStruct[]} | undefined); - } - } - - //safely query user basic identification info for lookup - queryUsers = async ( - info:string, //name, email, username, etc - skip?:number, - limit?:number, - callback=this.baseServerCallback - ) => { - if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'queryUsers', args:[ - this.currentUser._id, - info, - skip, - limit, - undefined, - this.getToken(this.currentUser) - ]})) // Pass Array - callback(res); - return res + return (res as {user:ProfileStruct, groups:[], authorizations:[]} | undefined); } } //get user basic info by id - getUsers = async (ids:(string|number)[]=[], basicInfo?:boolean, callback=this.baseServerCallback) => { + getUsers = async (ids:(string|number)[]=[],callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getUsersByIds', args:[this.currentUser._id, ids, basicInfo]})) // Pass Array - callback(res); + let res = (await this.currentUser.request({route:'getUsersByIds', args:[this.currentUser._id, ids]})) // Pass Array + callback(res) return res } } @@ -374,44 +315,27 @@ export class StructFrontend extends Service { } //pull all of the collections (except excluded collection names e.g. 'groups') for a user from the server - getAllUserData = async (ownerId:string|number, excluded:any[]=[], timeRange?:[number|TimeSpecifier,number|TimeSpecifier], callback=this.baseServerCallback) => { - if(timeRange) { - if(typeof timeRange[0] === 'string') timeRange[0] = genTimestampFromString(timeRange[0]); - if(typeof timeRange[1] === 'string') timeRange[1] = genTimestampFromString(timeRange[1]); - } + getAllUserData = async (ownerId:string|number, excluded:any[]=[], callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getAllData', args:[this.currentUser._id, ownerId, excluded, timeRange, this.getToken(this.currentUser)]} )); + let res = (await this.currentUser.request({route:'getAllData', args:[ownerId, excluded]} )); callback(res) return res } } - query = async (collection:string, mongoQuery={}, findOne=false, skip=0, callback=this.baseServerCallback) => { + query = async (collection:string, queryObj={}, findOne=false, skip=0, callback=this.baseServerCallback) => { if(this.currentUser?.request) { - if(!collection || !mongoQuery) return undefined; - let res = (await this.currentUser.request({route:'query',args:[this.currentUser._id, collection, mongoQuery, findOne, skip, this.getToken(this.currentUser)]} )); + if(!collection || !queryObj) return undefined; + let res = (await this.currentUser.request({route:'query',args:[this.currentUser._id, collection,queryObj,findOne,skip]} )); if(typeof callback === 'function') callback(res); return res; } } - //get data by a range of time via utcTimeStamps, default key is timestamp - getDataByTimeRange(collection, timeRange?:[number|TimeSpecifier,number|TimeSpecifier], ownerId?:string|number|undefined, limit:number=0, skip:number=0, key?:string) { - let query = {} as any; - if(timeRange) { - if(typeof timeRange[0] === 'string') timeRange[0] = genTimestampFromString(timeRange[0]); - if(typeof timeRange[1] === 'string') timeRange[1] = genTimestampFromString(timeRange[1]); - } - let range = {$gt:timeRange[0],$lt:timeRange[1]} - if(key) query[key] = range; - else query.timestamp = range; - return this.getData(collection, ownerId, query, limit, skip); - } - //get data by specified details from the server. You can provide only one of the first 3 elements. The searchDict is for mongoDB search keys - getData = async (collection:string, ownerId?:string|number|undefined, searchDict?, limit:number=0, skip:number=0, callback=this.baseServerCallback) => { + getData = async (collection:string,ownerId?:string|number|undefined,searchDict?,limit:number=0,skip:number=0,callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getData', args:[this.currentUser._id, collection, ownerId, searchDict, limit, skip, this.getToken(this.currentUser)]}));//?.[0] + let res = (await this.currentUser.request({route:'getData', args:[this.currentUser._id, collection, ownerId, searchDict, limit, skip]}));//?.[0] //console.log('GET DATA RES', res, JSON.stringify(collection), JSON.stringify(ownerId)); if(typeof callback === 'function') callback(res); return res; @@ -421,17 +345,17 @@ export class StructFrontend extends Service { //get data by specified details from the server. You can provide only one of the first 3 elements. The searchDict is for mongoDB search keys getDataByIds = async (structIds:any[]=[],ownerId?:string|number|undefined,collection?:string|undefined,callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getDataByIds', args:[this.currentUser._id, structIds, ownerId, collection, this.getToken(this.currentUser)]})); + let res = (await this.currentUser.request({route:'getDataByIds', args:[this.currentUser._id, structIds, ownerId, collection]})); if(typeof callback === 'function') callback(res); return res } } //get struct based on the parentId - getStructParentData = async (struct:Struct,callback=this.baseServerCallback) => { - if(!struct?.parent) return; + getStructParentData = async (struct:any,callback=this.baseServerCallback) => { + if(!struct.parent) return; if(this.currentUser?.request) { - let args = [this.currentUser._id, struct.parent?.structType,'_id',struct.parent?._id, this.getToken(this.currentUser)]; + let args = [this.currentUser._id, struct.parent?.structType,'_id',struct.parent?._id]; let res = (await this.currentUser.request({route:'getData', args}))?.[0] if(typeof callback === 'function') callback(res); @@ -455,9 +379,9 @@ export class StructFrontend extends Service { //sets the user profile data on the server - setUser = async (userStruct:ProfileStruct,callback=this.baseServerCallback) => { - if(userStruct && this.currentUser?.request) { - let res = (await this.currentUser.request({route:'setUser', args:[this.currentUser._id, this.stripStruct(userStruct), this.getToken(this.currentUser)]})) + setUser = async (userStruct={},callback=this.baseServerCallback) => { + if(this.currentUser?.request) { + let res = (await this.currentUser.request({route:'setUser', args:[this.currentUser._id, this.stripStruct(userStruct)]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -496,12 +420,13 @@ export class StructFrontend extends Service { user[prop] = usertoken[prop]; changed = true; } } - if(changed) return await this.setUser(user as any,callback); + if(changed) return await this.setUser(user,callback); return changed; } /* strip circular references and update data on the server, default callback will process the returned structs back into */ setData = async (structs:Partial|Partial[]=[],notify=true,callback=this.baseServerCallback) => { + if(this.currentUser?.request) { const copies = new Array(); if(!Array.isArray(structs) && typeof structs === 'object') structs = [structs]; @@ -509,7 +434,7 @@ export class StructFrontend extends Service { copies.push(this.stripStruct(struct)); }) - let res = (await this.currentUser.request({route:'setData', args:[this.currentUser._id, copies, notify, this.getToken(this.currentUser)]})); + let res = (await this.currentUser.request({route:'setData', args:[this.currentUser._id, copies, notify]})); if(typeof callback === 'function') callback(res); return res; } @@ -553,27 +478,27 @@ export class StructFrontend extends Service { } }); //console.log('deleting',toDelete); - let res = (await this.currentUser.request({route:'deleteData', args:[this.currentUser._id, toDelete, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'deleteData', args:[this.currentUser._id, toDelete]}))?.[0] if(typeof callback === 'function') callback(res) return res } } //delete user profile by ID on the server - deleteUser = async (userId:string=this.currentUser._id, deleteData?:boolean, callback=this.baseServerCallback) => { + deleteUser = async (userId, callback=this.baseServerCallback) => { if(this.currentUser?.request) { if(!userId) return; - let res = (await this.currentUser.request({route:'deleteUser', args:[this.currentUser._id, userId, deleteData, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'deleteUser', args:[this.currentUser._id, userId]}))?.[0] if(typeof callback === 'function') callback(res) return res } } //set a group struct on the server - setGroup = async (groupStruct:GroupStruct,callback=this.baseServerCallback) => { - if(groupStruct && this.currentUser?.request) { - let res = (await this.currentUser.request({route:'setGroup', args:[this.currentUser._id, this.stripStruct(groupStruct), this.getToken(this.currentUser)]})) + setGroup = async (groupStruct={},callback=this.baseServerCallback) => { + if(this.currentUser?.request) { + let res = (await this.currentUser.request({route:'setGroup', args:[this.currentUser._id, this.stripStruct(groupStruct)]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -582,7 +507,7 @@ export class StructFrontend extends Service { //get group structs or single one by Id getUserGroups = async (userId=this.currentUser._id, groupId='',callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getUserGroups', args:[this.currentUser._id, userId,groupId, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'getUserGroups', args:[this.currentUser._id, userId,groupId]})) if(typeof callback === 'function') callback(res) return res } @@ -594,16 +519,16 @@ export class StructFrontend extends Service { if(!groupId) return; this.deleteLocalData(groupId); - let res = (await this.currentUser.request({route:'deleteGroup', args:[this.currentUser._id, groupId, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'deleteGroup', args:[this.currentUser._id, groupId]}))?.[0] if(typeof callback === 'function') callback(res) return res } } //set an authorization struct on the server - setAuthorization = async (authorizationStruct:AuthorizationStruct,callback=this.baseServerCallback) => { - if(authorizationStruct && this.currentUser?.request) { - let res = (await this.currentUser.request({route:'setAuthorization', args:[this.currentUser._id, this.stripStruct(authorizationStruct), this.getToken(this.currentUser)]})) + setAuthorization = async (authorizationStruct={},callback=this.baseServerCallback) => { + if(this.currentUser?.request) { + let res = (await this.currentUser.request({route:'setAuthorization', args:[this.currentUser._id, this.stripStruct(authorizationStruct)]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -613,7 +538,7 @@ export class StructFrontend extends Service { getAuthorizations = async (userId=this.currentUser?._id, authorizationId='',callback=this.baseServerCallback) => { if(this.currentUser?.request) { if(userId === undefined) return; - let res = (await this.currentUser.request({route:'getAuthorizations', args:[this.currentUser._id, userId, authorizationId, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'getAuthorizations', args:[this.currentUser._id, userId, authorizationId]})) if(typeof callback === 'function') callback(res) return res } @@ -624,7 +549,8 @@ export class StructFrontend extends Service { if(this.currentUser?.request) { if(!authorizationId) return; this.deleteLocalData(authorizationId); - let res = (await this.currentUser.request({route:'deleteAuthorization', args:[this.currentUser._id, authorizationId, this.getToken(this.currentUser)]})); + + let res = (await this.currentUser.request({route:'deleteAuthorization', args:[authorizationId]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -676,6 +602,7 @@ export class StructFrontend extends Service { return true; } + //setup authorizations automatically based on group setAuthorizationsByGroup = async (user=this.currentUser) => { @@ -830,13 +757,12 @@ export class StructFrontend extends Service { let u = authorizationStruct.authorizerId; if(u) { return new Promise(async resolve => { - this.getUser(u, true, async (data)=> { - let res; - if(!collection) res = await this.getAllUserData(u,['notification'],undefined,callback); - else res = await this.getData(collection,u,searchDict,limit,skip,callback); + this.getUser(u,async (data)=> { + if(!collection) await this.getAllUserData(u,['notification'],callback); + else await this.getData(collection,u,searchDict,limit,skip,callback); - resolve(res) - callback(res); + resolve(data) + callback(data); }); //gets profile deets }) } else return undefined; @@ -852,10 +778,10 @@ export class StructFrontend extends Service { let u = o.authorizerId; if(u) { let data; - let user = await this.getUser(u, true, callback); + let user = await this.getUser(u,callback); if(user) results.push(user); - if(!collection) data = await this.getAllUserData(u,['notification'],undefined,callback); + if(!collection) data = await this.getAllUserData(u,['notification'],callback); else data = await this.getData(collection,u,searchDict,limit,skip,callback); if(data) results.push(data); } @@ -898,11 +824,11 @@ export class StructFrontend extends Service { //get auths where you have granted somebody peer access getLocalUserPeerIds = (user=this.currentUser) => { - if(!user) return {} as any; - let result:any = {}; + if(!user) return [] as any[]; + let result:any[] = []; let authorizations = this.getLocalData('authorization',user._id); authorizations.forEach((a)=>{ - if(a.authorizations['peer'] && a.authorizerId === user._id) result[a.authorizedId] = true; + if(a.authorizations['peer'] && a.authorizerId === user._id) result.push(a.authorizedId); }); return result; } @@ -929,33 +855,31 @@ export class StructFrontend extends Service { } //pass a single struct or array of structs - deleteLocalData(structs:Struct[]) { + deleteLocalData(structs) { if(Array.isArray(structs)) structs.forEach(s => this.deleteStruct(s)); else this.deleteStruct(structs); //single return true; } - deleteStruct(struct:Struct) { - if(typeof struct === 'string') struct = this.getLocalData(undefined,{_id:struct}); //get the struct if an id was supplied + deleteStruct(struct) { + if(typeof struct === 'string') struct = this.getLocalData(struct); //get the struct if an id was supplied if(!struct) throw new Error('Struct not supplied') if(!struct.structType || !struct._id) return false; - this.tablet.collections.get(struct.structType as string).delete(struct._id); + this.tablet.collections.get(struct.structType).delete(struct._id); return true; } //strips circular references from the struct used clientside, returns a soft copy with the changes - stripStruct(struct:Struct) { + stripStruct(struct={}) { const copy = Object.assign({ }, struct); for(const prop in copy) { - if(copy[prop] === undefined || copy[prop] === "" || copy[prop].constructor.name === 'Map' || copy[prop].constructor.name === 'Set' || typeof copy[prop] === 'function') delete copy[prop]; //delete undefined - else if (Array.isArray(copy[prop]) && copy[prop].length === 0) delete copy[prop]; //get rid of empty arrays - else if(typeof copy[prop] === 'object' && Object.keys(copy[prop]).length === 0) delete copy[prop]; //get rid of empty objects + if(copy[prop] === undefined || copy[prop].constructor.name === 'Map' || typeof copy[prop] === 'function') delete copy[prop]; //delete undefined } return copy; } //create a struct with the prepared props to be filled out - createStruct(structType:string,props:{[key:string]:any},parentUser=this.currentUser,parentStruct?:Struct):any { + createStruct(structType,props,parentUser=this.currentUser,parentStruct?):any { let struct = DS.Struct(structType,props,parentUser,parentStruct) return struct; } @@ -965,22 +889,14 @@ export class StructFrontend extends Service { currentUser=false ) { let user = DS.ProfileStruct(undefined, props, props); - if(!user.name && user.firstName) - user.name = user.firstName + ' ' + user.lastName; - else if(user.name && !user.firstName) { - let split = user.name.split(' '); - user.firstName = split[0]; - user.lastName = split[split.length-1]; - } if(props._id) user.id = props._id; //references the token id else if(props.id) user.id = props.id; - else user.id = 'user'+Math.floor(Math.random()*1000000000000000); + else user.id = 'user'+Math.floor(Math.random()*10000000000); user._id = user.id as any; //for mongo stuff user.ownerId = user.id; - let dummy = DS.ProfileStruct(); for(const prop in props) { - if(Object.keys(dummy).indexOf(prop) < 0) { + if(Object.keys(DS.ProfileStruct()).indexOf(prop) < 0) { delete user[prop]; } //delete non-dependent data (e.g. tokens we only want to keep in a secure collection) } @@ -995,7 +911,7 @@ export class StructFrontend extends Service { authorizerUserName='', authorizedUserId='', authorizedUserName='', - authorizations:{}={}, + authorizations:{}={}, // TODO: really any[] or has type?? structs:{}={}, excluded:{}={}, groups:{}={}, @@ -1015,6 +931,7 @@ export class StructFrontend extends Service { newAuthorization.expires = expires; newAuthorization.status = 'PENDING'; newAuthorization.associatedAuthId = ''; + newAuthorization.ownerId = parentUser._id; //console.log('new authorization', newAuthorization) newAuthorization = await this.setAuthorization(newAuthorization); @@ -1043,6 +960,7 @@ export class StructFrontend extends Service { Object.assign(newGroup.users, newGroup.admins); Object.assign(newGroup.users, newGroup.peers); Object.assign(newGroup.users, newGroup.clients); + newGroup.ownerId = parentUser._id; //this.setLocalData(newGroup); @@ -1083,6 +1001,7 @@ export class StructFrontend extends Service { newDataInstance.type = type; newDataInstance.data = data; newDataInstance.expires = expires; + newDataInstance.ownerId = parentUser._id; //this.setLocalData(newDataInstance); @@ -1093,23 +1012,20 @@ export class StructFrontend extends Service { addEvent = async ( parentUser:Partial, - author:string='', - event:string|number='', - notes:string='', - startTime:string|number=undefined, - endTime:string|number=undefined, - grade:string|number=undefined, - value:any=undefined, - units:string=undefined, - location:any=undefined, - attachments:string|Data[]=undefined, - users:{[key:string]:true}=undefined, + author='', + event='', + notes='', + startTime=0, + endTime=0, + grade=0, + attachments:string|Data[]=[], + users:{}={}, updateServer=true ) => { if(!parentUser) return undefined; - if(users && Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); + if(Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); - let newEvent = this.createStruct('event', undefined, parentUser as any); + let newEvent = this.createStruct('event',undefined,parentUser as any); newEvent.author = author; newEvent.event = event; newEvent.notes = notes; @@ -1117,10 +1033,8 @@ export class StructFrontend extends Service { newEvent.endTime = endTime; newEvent.grade = grade; newEvent.attachments = attachments; - newEvent.value = value; - newEvent.units = units; newEvent.users = users; - newEvent.location = location; + newEvent.ownerId = parentUser._id; //this.setLocalData(newEvent); if(updateServer) newEvent = await this.updateServerData([newEvent])[0]; @@ -1132,12 +1046,12 @@ export class StructFrontend extends Service { parentUser:Partial, authorId='', message='', - attachments:string|Data[]=undefined, - users:{[key:string]:true}=undefined, + attachments:string|Data[]=[], + users:{}={}, updateServer=true ) => { if(!parentUser) return undefined; - if(users && Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); //adds the peer ids if none other provided + if(Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); //adds the peer ids if none other provided let newChatroom = this.createStruct('chatroom',undefined,parentUser as any); newChatroom.message = message; @@ -1146,6 +1060,8 @@ export class StructFrontend extends Service { newChatroom.users = users; newChatroom.replies = []; newChatroom.comments = []; + newChatroom.ownerId = parentUser._id; + let update = [newChatroom]; if(updateServer) newChatroom = await this.updateServerData(update)[0]; @@ -1166,7 +1082,7 @@ export class StructFrontend extends Service { }, authorId='', message='', - attachments:string|Data[]=undefined, + attachments:string|Data[]=[], updateServer=true ) => { if(!roomStruct) return undefined; @@ -1180,6 +1096,7 @@ export class StructFrontend extends Service { newComment.attachments = attachments; newComment.users = roomStruct?.users; newComment.replies = []; + newComment.ownerId = parentUser._id; if (!updateServer) replyTo?.replies.push(newComment._id); //keep a local reference @@ -1204,5 +1121,6 @@ export class StructFrontend extends Service { if(updatedComment) return updatedComment as CommentStruct; return res as Array; } -} + +} diff --git a/src/extras/struct/datastructures/DataStructures.ts b/src/extras/struct/datastructures/DataStructures.ts index dcdb635b..9274b7b5 100644 --- a/src/extras/struct/datastructures/DataStructures.ts +++ b/src/extras/struct/datastructures/DataStructures.ts @@ -20,7 +20,7 @@ export function Struct( structType: structType, //this is how you will look it up by type in the server ownerId: (parentUser as types.ProfileStruct)?._id, //owner user timestamp: Date.now(), //date of creation - parent: {structType:parentStruct?.structType, _id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) + parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) } if(!struct.ownerId) delete struct.ownerId; @@ -429,13 +429,10 @@ export function ProfileStruct( sex: '', birthday: '', type: '', - pictureUrl:'', userRoles: {}, socials: {}, data: {}, //arbitrary stuff - hidden: false, - accessToken:'', //for security - refreshToken:'', //for security + id: '' //references the token id which is behind a collection permission }; let struct = Struct('profile',props,parentUser,parentStruct); @@ -532,10 +529,7 @@ export function EventStruct( author:"", // startTime:"", //event began endTime:"", //event ended - grade:undefined, //severity - value:undefined, - units:undefined, - location:undefined, + grade:0, //severity notes:"", //additional details attachments:new Array(), users:{}, //users to be informed (i.e. peers) diff --git a/src/extras/struct/datastructures/bson.cjs b/src/extras/struct/datastructures/bson.cjs deleted file mode 100644 index fb846640..00000000 --- a/src/extras/struct/datastructures/bson.cjs +++ /dev/null @@ -1,4095 +0,0 @@ -'use strict'; - -const BSON_MAJOR_VERSION = 5; -const BSON_INT32_MAX = 0x7fffffff; -const BSON_INT32_MIN = -0x80000000; -const BSON_INT64_MAX = Math.pow(2, 63) - 1; -const BSON_INT64_MIN = -Math.pow(2, 63); -const JS_INT_MAX = Math.pow(2, 53); -const JS_INT_MIN = -Math.pow(2, 53); -const BSON_DATA_NUMBER = 1; -const BSON_DATA_STRING = 2; -const BSON_DATA_OBJECT = 3; -const BSON_DATA_ARRAY = 4; -const BSON_DATA_BINARY = 5; -const BSON_DATA_UNDEFINED = 6; -const BSON_DATA_OID = 7; -const BSON_DATA_BOOLEAN = 8; -const BSON_DATA_DATE = 9; -const BSON_DATA_NULL = 10; -const BSON_DATA_REGEXP = 11; -const BSON_DATA_DBPOINTER = 12; -const BSON_DATA_CODE = 13; -const BSON_DATA_SYMBOL = 14; -const BSON_DATA_CODE_W_SCOPE = 15; -const BSON_DATA_INT = 16; -const BSON_DATA_TIMESTAMP = 17; -const BSON_DATA_LONG = 18; -const BSON_DATA_DECIMAL128 = 19; -const BSON_DATA_MIN_KEY = 0xff; -const BSON_DATA_MAX_KEY = 0x7f; -const BSON_BINARY_SUBTYPE_DEFAULT = 0; -const BSON_BINARY_SUBTYPE_UUID_NEW = 4; -const BSONType = Object.freeze({ - double: 1, - string: 2, - object: 3, - array: 4, - binData: 5, - undefined: 6, - objectId: 7, - bool: 8, - date: 9, - null: 10, - regex: 11, - dbPointer: 12, - javascript: 13, - symbol: 14, - javascriptWithScope: 15, - int: 16, - timestamp: 17, - long: 18, - decimal: 19, - minKey: -1, - maxKey: 127 -}); - -class BSONError extends Error { - get bsonError() { - return true; - } - get name() { - return 'BSONError'; - } - constructor(message) { - super(message); - } - static isBSONError(value) { - return (value != null && - typeof value === 'object' && - 'bsonError' in value && - value.bsonError === true && - 'name' in value && - 'message' in value && - 'stack' in value); - } -} -class BSONVersionError extends BSONError { - get name() { - return 'BSONVersionError'; - } - constructor() { - super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); - } -} -class BSONRuntimeError extends BSONError { - get name() { - return 'BSONRuntimeError'; - } - constructor(message) { - super(message); - } -} - -function nodejsMathRandomBytes(byteLength) { - return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); -} -const nodejsRandomBytes = (() => { - try { - return require('crypto').randomBytes; - } - catch { - return nodejsMathRandomBytes; - } -})(); -const nodeJsByteUtils = { - toLocalBufferType(potentialBuffer) { - if (Buffer.isBuffer(potentialBuffer)) { - return potentialBuffer; - } - if (ArrayBuffer.isView(potentialBuffer)) { - return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); - if (stringTag === 'ArrayBuffer' || - stringTag === 'SharedArrayBuffer' || - stringTag === '[object ArrayBuffer]' || - stringTag === '[object SharedArrayBuffer]') { - return Buffer.from(potentialBuffer); - } - throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); - }, - allocate(size) { - return Buffer.alloc(size); - }, - equals(a, b) { - return nodeJsByteUtils.toLocalBufferType(a).equals(b); - }, - fromNumberArray(array) { - return Buffer.from(array); - }, - fromBase64(base64) { - return Buffer.from(base64, 'base64'); - }, - toBase64(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); - }, - fromISO88591(codePoints) { - return Buffer.from(codePoints, 'binary'); - }, - toISO88591(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); - }, - fromHex(hex) { - return Buffer.from(hex, 'hex'); - }, - toHex(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); - }, - fromUTF8(text) { - return Buffer.from(text, 'utf8'); - }, - toUTF8(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); - }, - utf8ByteLength(input) { - return Buffer.byteLength(input, 'utf8'); - }, - encodeUTF8Into(buffer, source, byteOffset) { - return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); - }, - randomBytes: nodejsRandomBytes -}; - -function isReactNative() { - const { navigator } = globalThis; - return typeof navigator === 'object' && navigator.product === 'ReactNative'; -} -function webMathRandomBytes(byteLength) { - if (byteLength < 0) { - throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); - } - return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); -} -const webRandomBytes = (() => { - const { crypto } = globalThis; - if (crypto != null && typeof crypto.getRandomValues === 'function') { - return (byteLength) => { - return crypto.getRandomValues(webByteUtils.allocate(byteLength)); - }; - } - else { - if (isReactNative()) { - const { console } = globalThis; - console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); - } - return webMathRandomBytes; - } -})(); -const HEX_DIGIT = /(\d|[a-f])/i; -const webByteUtils = { - toLocalBufferType(potentialUint8array) { - const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? - Object.prototype.toString.call(potentialUint8array); - if (stringTag === 'Uint8Array') { - return potentialUint8array; - } - if (ArrayBuffer.isView(potentialUint8array)) { - return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); - } - if (stringTag === 'ArrayBuffer' || - stringTag === 'SharedArrayBuffer' || - stringTag === '[object ArrayBuffer]' || - stringTag === '[object SharedArrayBuffer]') { - return new Uint8Array(potentialUint8array); - } - throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); - }, - allocate(size) { - if (typeof size !== 'number') { - throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); - } - return new Uint8Array(size); - }, - equals(a, b) { - if (a.byteLength !== b.byteLength) { - return false; - } - for (let i = 0; i < a.byteLength; i++) { - if (a[i] !== b[i]) { - return false; - } - } - return true; - }, - fromNumberArray(array) { - return Uint8Array.from(array); - }, - fromBase64(base64) { - return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); - }, - toBase64(uint8array) { - return btoa(webByteUtils.toISO88591(uint8array)); - }, - fromISO88591(codePoints) { - return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); - }, - toISO88591(uint8array) { - return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); - }, - fromHex(hex) { - const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); - const buffer = []; - for (let i = 0; i < evenLengthHex.length; i += 2) { - const firstDigit = evenLengthHex[i]; - const secondDigit = evenLengthHex[i + 1]; - if (!HEX_DIGIT.test(firstDigit)) { - break; - } - if (!HEX_DIGIT.test(secondDigit)) { - break; - } - const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); - buffer.push(hexDigit); - } - return Uint8Array.from(buffer); - }, - toHex(uint8array) { - return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); - }, - fromUTF8(text) { - return new TextEncoder().encode(text); - }, - toUTF8(uint8array) { - return new TextDecoder('utf8', { fatal: false }).decode(uint8array); - }, - utf8ByteLength(input) { - return webByteUtils.fromUTF8(input).byteLength; - }, - encodeUTF8Into(buffer, source, byteOffset) { - const bytes = webByteUtils.fromUTF8(source); - buffer.set(bytes, byteOffset); - return bytes.byteLength; - }, - randomBytes: webRandomBytes -}; - -const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; -const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; -class BSONDataView extends DataView { - static fromUint8Array(input) { - return new DataView(input.buffer, input.byteOffset, input.byteLength); - } -} - -const VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; -const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); -const uuidHexStringToBuffer = (hexString) => { - if (!uuidValidateString(hexString)) { - throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); - } - const sanitizedHexString = hexString.replace(/-/g, ''); - return ByteUtils.fromHex(sanitizedHexString); -}; -function bufferToUuidHexString(buffer, includeDashes = true) { - if (includeDashes) { - return [ - ByteUtils.toHex(buffer.subarray(0, 4)), - ByteUtils.toHex(buffer.subarray(4, 6)), - ByteUtils.toHex(buffer.subarray(6, 8)), - ByteUtils.toHex(buffer.subarray(8, 10)), - ByteUtils.toHex(buffer.subarray(10, 16)) - ].join('-'); - } - return ByteUtils.toHex(buffer); -} - -function isAnyArrayBuffer(value) { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); -} -function isUint8Array(value) { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; -} -function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} -function isMap(d) { - return Object.prototype.toString.call(d) === '[object Map]'; -} -function isDate(d) { - return Object.prototype.toString.call(d) === '[object Date]'; -} - -class BSONValue { - get [Symbol.for('@@mdb.bson.version')]() { - return BSON_MAJOR_VERSION; - } -} - -class Binary extends BSONValue { - get _bsontype() { - return 'Binary'; - } - constructor(buffer, subType) { - super(); - if (!(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer)) { - throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); - } - this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer == null) { - this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); - this.position = 0; - } - else { - if (typeof buffer === 'string') { - this.buffer = ByteUtils.fromISO88591(buffer); - } - else if (Array.isArray(buffer)) { - this.buffer = ByteUtils.fromNumberArray(buffer); - } - else { - this.buffer = ByteUtils.toLocalBufferType(buffer); - } - this.position = this.buffer.byteLength; - } - } - put(byteValue) { - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new BSONError('only accepts single character String'); - } - else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new BSONError('only accepts single character Uint8Array or Array'); - let decodedByte; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } - else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } - else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONError('only accepts number in a valid unsigned byte range 0-255'); - } - if (this.buffer.byteLength > this.position) { - this.buffer[this.position++] = decodedByte; - } - else { - const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); - newSpace.set(this.buffer, 0); - this.buffer = newSpace; - this.buffer[this.position++] = decodedByte; - } - } - write(sequence, offset) { - offset = typeof offset === 'number' ? offset : this.position; - if (this.buffer.byteLength < offset + sequence.length) { - const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); - newSpace.set(this.buffer, 0); - this.buffer = newSpace; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } - else if (typeof sequence === 'string') { - const bytes = ByteUtils.fromISO88591(sequence); - this.buffer.set(bytes, offset); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - } - read(position, length) { - length = length && length > 0 ? length : this.position; - return this.buffer.slice(position, position + length); - } - value(asRaw) { - asRaw = !!asRaw; - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); - } - length() { - return this.position; - } - toJSON() { - return ByteUtils.toBase64(this.buffer); - } - toString(encoding) { - if (encoding === 'hex') - return ByteUtils.toHex(this.buffer); - if (encoding === 'base64') - return ByteUtils.toBase64(this.buffer); - if (encoding === 'utf8' || encoding === 'utf-8') - return ByteUtils.toUTF8(this.buffer); - return ByteUtils.toUTF8(this.buffer); - } - toExtendedJSON(options) { - options = options || {}; - const base64String = ByteUtils.toBase64(this.buffer); - const subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - } - toUUID() { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID(this.buffer.slice(0, this.position)); - } - throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); - } - static fromExtendedJSON(doc, options) { - options = options || {}; - let data; - let type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = ByteUtils.fromBase64(doc.$binary); - } - else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = ByteUtils.fromBase64(doc.$binary.base64); - } - } - } - else if ('$uuid' in doc) { - type = 4; - data = uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); - } - return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; - } -} -Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; -Binary.BUFFER_SIZE = 256; -Binary.SUBTYPE_DEFAULT = 0; -Binary.SUBTYPE_FUNCTION = 1; -Binary.SUBTYPE_BYTE_ARRAY = 2; -Binary.SUBTYPE_UUID_OLD = 3; -Binary.SUBTYPE_UUID = 4; -Binary.SUBTYPE_MD5 = 5; -Binary.SUBTYPE_ENCRYPTED = 6; -Binary.SUBTYPE_COLUMN = 7; -Binary.SUBTYPE_USER_DEFINED = 128; -const UUID_BYTE_LENGTH = 16; -class UUID extends Binary { - constructor(input) { - let bytes; - let hexStr; - if (input == null) { - bytes = UUID.generate(); - } - else if (input instanceof UUID) { - bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); - hexStr = input.__id; - } - else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { - bytes = ByteUtils.toLocalBufferType(input); - } - else if (typeof input === 'string') { - bytes = uuidHexStringToBuffer(input); - } - else { - throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); - } - super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); - this.__id = hexStr; - } - get id() { - return this.buffer; - } - set id(value) { - this.buffer = value; - if (UUID.cacheHexString) { - this.__id = bufferToUuidHexString(value); - } - } - toHexString(includeDashes = true) { - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - const uuidHexString = bufferToUuidHexString(this.id, includeDashes); - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - return uuidHexString; - } - toString(encoding) { - if (encoding === 'hex') - return ByteUtils.toHex(this.id); - if (encoding === 'base64') - return ByteUtils.toBase64(this.id); - return this.toHexString(); - } - toJSON() { - return this.toHexString(); - } - equals(otherId) { - if (!otherId) { - return false; - } - if (otherId instanceof UUID) { - return ByteUtils.equals(otherId.id, this.id); - } - try { - return ByteUtils.equals(new UUID(otherId).id, this.id); - } - catch { - return false; - } - } - toBinary() { - return new Binary(this.id, Binary.SUBTYPE_UUID); - } - static generate() { - const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - return bytes; - } - static isValid(input) { - if (!input) { - return false; - } - if (input instanceof UUID) { - return true; - } - if (typeof input === 'string') { - return uuidValidateString(input); - } - if (isUint8Array(input)) { - if (input.byteLength !== UUID_BYTE_LENGTH) { - return false; - } - return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; - } - return false; - } - static createFromHexString(hexString) { - const buffer = uuidHexStringToBuffer(hexString); - return new UUID(buffer); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new UUID("${this.toHexString()}")`; - } -} - -class Code extends BSONValue { - get _bsontype() { - return 'Code'; - } - constructor(code, scope) { - super(); - this.code = code.toString(); - this.scope = scope ?? null; - } - toJSON() { - if (this.scope != null) { - return { code: this.code, scope: this.scope }; - } - return { code: this.code }; - } - toExtendedJSON() { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - } - static fromExtendedJSON(doc) { - return new Code(doc.$code, doc.$scope); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - const codeJson = this.toJSON(); - return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; - } -} - -function isDBRefLike(value) { - return (value != null && - typeof value === 'object' && - '$id' in value && - value.$id != null && - '$ref' in value && - typeof value.$ref === 'string' && - (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); -} -class DBRef extends BSONValue { - get _bsontype() { - return 'DBRef'; - } - constructor(collection, oid, db, fields) { - super(); - const parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - get namespace() { - return this.collection; - } - set namespace(value) { - this.collection = value; - } - toJSON() { - const o = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o.$db = this.db; - return o; - } - toExtendedJSON(options) { - options = options || {}; - let o = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o; - } - if (this.db) - o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - } - static fromExtendedJSON(doc) { - const copy = Object.assign({}, doc); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - const oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db ? `, "${this.db}"` : ''})`; - } -} - -let wasm = undefined; -try { - wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; -} -catch { -} -const TWO_PWR_16_DBL = 1 << 16; -const TWO_PWR_24_DBL = 1 << 24; -const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; -const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; -const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; -const INT_CACHE = {}; -const UINT_CACHE = {}; -const MAX_INT64_STRING_LENGTH = 20; -const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; -class Long extends BSONValue { - get _bsontype() { - return 'Long'; - } - get __isLong__() { - return true; - } - constructor(low = 0, high, unsigned) { - super(); - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } - else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } - else { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - } - static fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } - static fromInt(value, unsigned) { - let obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } - else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - } - static fromNumber(value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } - else { - if (value <= -TWO_PWR_63_DBL) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; - } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - } - static fromBigInt(value, unsigned) { - return Long.fromString(value.toString(), unsigned); - } - static fromString(str, unsigned, radix) { - if (str.length === 0) - throw new BSONError('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - (radix = unsigned), (unsigned = false); - } - else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw new BSONError('radix'); - let p; - if ((p = str.indexOf('-')) > 0) - throw new BSONError('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - const radixToPower = Long.fromNumber(Math.pow(radix, 8)); - let result = Long.ZERO; - for (let i = 0; i < str.length; i += 8) { - const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - const power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } - else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - static fromBytes(bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - } - static fromBytesLE(bytes, unsigned) { - return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); - } - static fromBytesBE(bytes, unsigned) { - return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); - } - static isLong(value) { - return (value != null && - typeof value === 'object' && - '__isLong__' in value && - value.__isLong__ === true); - } - static fromValue(val, unsigned) { - if (typeof val === 'number') - return Long.fromNumber(val, unsigned); - if (typeof val === 'string') - return Long.fromString(val, unsigned); - return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); - } - add(addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - const a48 = this.high >>> 16; - const a32 = this.high & 0xffff; - const a16 = this.low >>> 16; - const a00 = this.low & 0xffff; - const b48 = addend.high >>> 16; - const b32 = addend.high & 0xffff; - const b16 = addend.low >>> 16; - const b00 = addend.low & 0xffff; - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - } - and(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - } - compare(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - const thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - } - comp(other) { - return this.compare(other); - } - divide(divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw new BSONError('division by zero'); - if (wasm) { - if (!this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1) { - return this; - } - const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - let approx, rem, res; - if (!this.unsigned) { - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - const halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } - else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } - else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } - else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } - else { - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - return Long.UONE; - res = Long.UZERO; - } - rem = this; - while (rem.gte(divisor)) { - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - const log2 = Math.ceil(Math.log(approx) / Math.LN2); - const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - let approxRes = Long.fromNumber(approx); - let approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - } - div(divisor) { - return this.divide(divisor); - } - equals(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - } - eq(other) { - return this.equals(other); - } - getHighBits() { - return this.high; - } - getHighBitsUnsigned() { - return this.high >>> 0; - } - getLowBits() { - return this.low; - } - getLowBitsUnsigned() { - return this.low >>> 0; - } - getNumBitsAbs() { - if (this.isNegative()) { - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - const val = this.high !== 0 ? this.high : this.low; - let bit; - for (bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - } - greaterThan(other) { - return this.comp(other) > 0; - } - gt(other) { - return this.greaterThan(other); - } - greaterThanOrEqual(other) { - return this.comp(other) >= 0; - } - gte(other) { - return this.greaterThanOrEqual(other); - } - ge(other) { - return this.greaterThanOrEqual(other); - } - isEven() { - return (this.low & 1) === 0; - } - isNegative() { - return !this.unsigned && this.high < 0; - } - isOdd() { - return (this.low & 1) === 1; - } - isPositive() { - return this.unsigned || this.high >= 0; - } - isZero() { - return this.high === 0 && this.low === 0; - } - lessThan(other) { - return this.comp(other) < 0; - } - lt(other) { - return this.lessThan(other); - } - lessThanOrEqual(other) { - return this.comp(other) <= 0; - } - lte(other) { - return this.lessThanOrEqual(other); - } - modulo(divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (wasm) { - const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - } - mod(divisor) { - return this.modulo(divisor); - } - rem(divisor) { - return this.modulo(divisor); - } - multiply(multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - if (wasm) { - const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } - else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - const a48 = this.high >>> 16; - const a32 = this.high & 0xffff; - const a16 = this.low >>> 16; - const a00 = this.low & 0xffff; - const b48 = multiplier.high >>> 16; - const b32 = multiplier.high & 0xffff; - const b16 = multiplier.low >>> 16; - const b00 = multiplier.low & 0xffff; - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - } - mul(multiplier) { - return this.multiply(multiplier); - } - negate() { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); - } - neg() { - return this.negate(); - } - not() { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - } - notEquals(other) { - return !this.equals(other); - } - neq(other) { - return this.notEquals(other); - } - ne(other) { - return this.notEquals(other); - } - or(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - } - shiftLeft(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - } - shl(numBits) { - return this.shiftLeft(numBits); - } - shiftRight(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - } - shr(numBits) { - return this.shiftRight(numBits); - } - shiftRightUnsigned(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - const high = this.high; - if (numBits < 32) { - const low = this.low; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } - else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - } - shr_u(numBits) { - return this.shiftRightUnsigned(numBits); - } - shru(numBits) { - return this.shiftRightUnsigned(numBits); - } - subtract(subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - } - sub(subtrahend) { - return this.subtract(subtrahend); - } - toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - } - toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - } - toBigInt() { - return BigInt(this.toString()); - } - toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - } - toBytesLE() { - const hi = this.high, lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - } - toBytesBE() { - const hi = this.high, lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - } - toSigned() { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); - } - toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw new BSONError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { - if (this.eq(Long.MIN_VALUE)) { - const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } - else - return '-' + this.neg().toString(radix); - } - const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - let rem = this; - let result = ''; - while (true) { - const remDiv = rem.div(radixToPower); - const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - let digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - } - toUnsigned() { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - } - xor(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - } - eqz() { - return this.isZero(); - } - le(other) { - return this.lessThanOrEqual(other); - } - toExtendedJSON(options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; - } - static fromExtendedJSON(doc, options) { - const { useBigInt64 = false, relaxed = true } = { ...options }; - if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { - throw new BSONError('$numberLong string is too long'); - } - if (!DECIMAL_REG_EX.test(doc.$numberLong)) { - throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); - } - if (useBigInt64) { - const bigIntResult = BigInt(doc.$numberLong); - return BigInt.asIntN(64, bigIntResult); - } - const longResult = Long.fromString(doc.$numberLong); - if (relaxed) { - return longResult.toNumber(); - } - return longResult; - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; - } -} -Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); -Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); -Long.ZERO = Long.fromInt(0); -Long.UZERO = Long.fromInt(0, true); -Long.ONE = Long.fromInt(1); -Long.UONE = Long.fromInt(1, true); -Long.NEG_ONE = Long.fromInt(-1); -Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - -const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; -const EXPONENT_MAX = 6111; -const EXPONENT_MIN = -6176; -const EXPONENT_BIAS = 6176; -const MAX_DIGITS = 34; -const NAN_BUFFER = ByteUtils.fromNumberArray([ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse()); -const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse()); -const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse()); -const EXPONENT_REGEX = /^([-+])?(\d+)?$/; -const COMBINATION_MASK = 0x1f; -const EXPONENT_MASK = 0x3fff; -const COMBINATION_INFINITY = 30; -const COMBINATION_NAN = 31; -function isDigit(value) { - return !isNaN(parseInt(value, 10)); -} -function divideu128(value) { - const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - let _rem = Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (let i = 0; i <= 3; i++) { - _rem = _rem.shiftLeft(32); - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - return { quotient: value, rem: _rem }; -} -function multiply64x2(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - const leftHigh = left.shiftRightUnsigned(32); - const leftLow = new Long(left.getLowBits(), 0); - const rightHigh = right.shiftRightUnsigned(32); - const rightLow = new Long(right.getLowBits(), 0); - let productHigh = leftHigh.multiply(rightHigh); - let productMid = leftHigh.multiply(rightLow); - const productMid2 = leftLow.multiply(rightHigh); - let productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - return { high: productHigh, low: productLow }; -} -function lessThan(left, right) { - const uhleft = left.high >>> 0; - const uhright = right.high >>> 0; - if (uhleft < uhright) { - return true; - } - else if (uhleft === uhright) { - const ulleft = left.low >>> 0; - const ulright = right.low >>> 0; - if (ulleft < ulright) - return true; - } - return false; -} -function invalidErr(string, message) { - throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); -} -class Decimal128 extends BSONValue { - get _bsontype() { - return 'Decimal128'; - } - constructor(bytes) { - super(); - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } - else if (isUint8Array(bytes)) { - if (bytes.byteLength !== 16) { - throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); - } - this.bytes = bytes; - } - else { - throw new BSONError('Decimal128 must take a Buffer or string'); - } - } - static fromString(representation) { - let isNegative = false; - let sawRadix = false; - let foundNonZero = false; - let significantDigits = 0; - let nDigitsRead = 0; - let nDigits = 0; - let radixPosition = 0; - let firstNonZero = 0; - const digits = [0]; - let nDigitsStored = 0; - let digitsInsert = 0; - let firstDigit = 0; - let lastDigit = 0; - let exponent = 0; - let i = 0; - let significandHigh = new Long(0, 0); - let significandLow = new Long(0, 0); - let biasedExponent = 0; - let index = 0; - if (representation.length >= 7000) { - throw new BSONError('' + representation + ' not a valid Decimal128 string'); - } - const stringMatch = representation.match(PARSE_STRING_REGEXP); - const infMatch = representation.match(PARSE_INF_REGEXP); - const nanMatch = representation.match(PARSE_NAN_REGEXP); - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new BSONError('' + representation + ' not a valid Decimal128 string'); - } - if (stringMatch) { - const unsignedNumber = stringMatch[2]; - const e = stringMatch[4]; - const expSign = stringMatch[5]; - const expNumber = stringMatch[6]; - if (e && expNumber === undefined) - invalidErr(representation, 'missing exponent power'); - if (e && unsignedNumber === undefined) - invalidErr(representation, 'missing exponent base'); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); - } - else if (representation[index] === 'N') { - return new Decimal128(NAN_BUFFER); - } - } - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) - invalidErr(representation, 'contains multiple periods'); - sawRadix = true; - index = index + 1; - continue; - } - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - if (sawRadix && !nDigitsRead) - throw new BSONError('' + representation + ' not a valid Decimal128 string'); - if (representation[index] === 'e' || representation[index] === 'E') { - const match = representation.substr(++index).match(EXPONENT_REGEX); - if (!match || !match[2]) - return new Decimal128(NAN_BUFFER); - exponent = parseInt(match[0], 10); - index = index + match[0].length; - } - if (representation[index]) - return new Decimal128(NAN_BUFFER); - firstDigit = 0; - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } - else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } - else { - exponent = exponent - radixPosition; - } - while (exponent > EXPONENT_MAX) { - lastDigit = lastDigit + 1; - if (lastDigit - firstDigit > MAX_DIGITS) { - const digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - nDigits = nDigits - 1; - } - else { - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } - else { - const digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - if (lastDigit - firstDigit + 1 < significantDigits) { - let endOfString = nDigitsRead; - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - let roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - let dIdx = lastDigit; - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } - else { - return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); - } - } - } - } - } - } - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } - else if (lastDigit - firstDigit < 17) { - let dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - else { - let dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - significandLow = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - biasedExponent = exponent + EXPONENT_BIAS; - const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } - else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - dec.low = significand.low; - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - const buffer = ByteUtils.allocate(16); - index = 0; - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - return new Decimal128(buffer); - } - toString() { - let biased_exponent; - let significand_digits = 0; - const significand = new Array(36); - for (let i = 0; i < significand.length; i++) - significand[i] = 0; - let index = 0; - let is_zero = false; - let significand_msb; - let significand128 = { parts: [0, 0, 0, 0] }; - let j, k; - const string = []; - index = 0; - const buffer = this.bytes; - const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - index = 0; - const dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - const combination = (high >> 26) & COMBINATION_MASK; - if (combination >> 3 === 3) { - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } - else if (combination === COMBINATION_NAN) { - return 'NaN'; - } - else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } - else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - const exponent = biased_exponent - EXPONENT_BIAS; - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0) { - is_zero = true; - } - else { - for (k = 3; k >= 0; k--) { - let least_digits = 0; - const result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - if (!least_digits) - continue; - for (j = 8; j >= 0; j--) { - significand[k * 9 + j] = least_digits % 10; - least_digits = Math.floor(least_digits / 10); - } - } - } - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } - else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - const scientific_exponent = significand_digits - 1 + exponent; - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - if (significand_digits > 34) { - string.push(`${0}`); - if (exponent > 0) - string.push(`E+${exponent}`); - else if (exponent < 0) - string.push(`E${exponent}`); - return string.join(''); - } - string.push(`${significand[index++]}`); - significand_digits = significand_digits - 1; - if (significand_digits) { - string.push('.'); - } - for (let i = 0; i < significand_digits; i++) { - string.push(`${significand[index++]}`); - } - string.push('E'); - if (scientific_exponent > 0) { - string.push(`+${scientific_exponent}`); - } - else { - string.push(`${scientific_exponent}`); - } - } - else { - if (exponent >= 0) { - for (let i = 0; i < significand_digits; i++) { - string.push(`${significand[index++]}`); - } - } - else { - let radix_position = significand_digits + exponent; - if (radix_position > 0) { - for (let i = 0; i < radix_position; i++) { - string.push(`${significand[index++]}`); - } - } - else { - string.push('0'); - } - string.push('.'); - while (radix_position++ < 0) { - string.push('0'); - } - for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(`${significand[index++]}`); - } - } - } - return string.join(''); - } - toJSON() { - return { $numberDecimal: this.toString() }; - } - toExtendedJSON() { - return { $numberDecimal: this.toString() }; - } - static fromExtendedJSON(doc) { - return Decimal128.fromString(doc.$numberDecimal); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Decimal128("${this.toString()}")`; - } -} - -class Double extends BSONValue { - get _bsontype() { - return 'Double'; - } - constructor(value) { - super(); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; - } - valueOf() { - return this.value; - } - toJSON() { - return this.value; - } - toString(radix) { - return this.value.toString(radix); - } - toExtendedJSON(options) { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: '-0.0' }; - } - return { - $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() - }; - } - static fromExtendedJSON(doc, options) { - const doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - const eJSON = this.toExtendedJSON(); - return `new Double(${eJSON.$numberDouble})`; - } -} - -class Int32 extends BSONValue { - get _bsontype() { - return 'Int32'; - } - constructor(value) { - super(); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value | 0; - } - valueOf() { - return this.value; - } - toString(radix) { - return this.value.toString(radix); - } - toJSON() { - return this.value; - } - toExtendedJSON(options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; - } - static fromExtendedJSON(doc, options) { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Int32(${this.valueOf()})`; - } -} - -class MaxKey extends BSONValue { - get _bsontype() { - return 'MaxKey'; - } - toExtendedJSON() { - return { $maxKey: 1 }; - } - static fromExtendedJSON() { - return new MaxKey(); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return 'new MaxKey()'; - } -} - -class MinKey extends BSONValue { - get _bsontype() { - return 'MinKey'; - } - toExtendedJSON() { - return { $minKey: 1 }; - } - static fromExtendedJSON() { - return new MinKey(); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return 'new MinKey()'; - } -} - -const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); -let PROCESS_UNIQUE = null; -const kId = Symbol('id'); -class ObjectId extends BSONValue { - get _bsontype() { - return 'ObjectId'; - } - constructor(inputId) { - super(); - let workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = ByteUtils.fromHex(inputId.toHexString()); - } - else { - workingId = inputId.id; - } - } - else { - workingId = inputId; - } - if (workingId == null || typeof workingId === 'number') { - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } - else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ByteUtils.toLocalBufferType(workingId); - } - else if (typeof workingId === 'string') { - if (workingId.length === 12) { - const bytes = ByteUtils.fromUTF8(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } - else { - throw new BSONError('Argument passed in must be a string of 12 bytes'); - } - } - else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = ByteUtils.fromHex(workingId); - } - else { - throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); - } - } - else { - throw new BSONError('Argument passed in does not match the accepted types'); - } - if (ObjectId.cacheHexString) { - this.__id = ByteUtils.toHex(this.id); - } - } - get id() { - return this[kId]; - } - set id(value) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = ByteUtils.toHex(value); - } - } - toHexString() { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - const hexString = ByteUtils.toHex(this.id); - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - return hexString; - } - static getInc() { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - } - static generate(time) { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - const inc = ObjectId.getInc(); - const buffer = ByteUtils.allocate(12); - BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = ByteUtils.randomBytes(5); - } - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - return buffer; - } - toString(encoding) { - if (encoding === 'base64') - return ByteUtils.toBase64(this.id); - if (encoding === 'hex') - return this.toHexString(); - return this.toHexString(); - } - toJSON() { - return this.toHexString(); - } - equals(otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (otherId instanceof ObjectId) { - return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); - } - if (typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - isUint8Array(this.id)) { - return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return ByteUtils.equals(ByteUtils.fromUTF8(otherId), this.id); - } - if (typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function') { - const otherIdString = otherId.toHexString(); - const thisIdString = this.toHexString().toLowerCase(); - return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; - } - return false; - } - getTimestamp() { - const timestamp = new Date(); - const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - } - static createPk() { - return new ObjectId(); - } - static createFromTime(time) { - const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); - return new ObjectId(buffer); - } - static createFromHexString(hexString) { - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - return new ObjectId(ByteUtils.fromHex(hexString)); - } - static isValid(id) { - if (id == null) - return false; - try { - new ObjectId(id); - return true; - } - catch { - return false; - } - } - toExtendedJSON() { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - } - static fromExtendedJSON(doc) { - return new ObjectId(doc.$oid); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new ObjectId("${this.toHexString()}")`; - } -} -ObjectId.index = Math.floor(Math.random() * 0xffffff); - -function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { - let totalLength = 4 + 1; - if (Array.isArray(object)) { - for (let i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } - else { - if (typeof object?.toBSON === 'function') { - object = object.toBSON(); - } - for (const key of Object.keys(object)) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - return totalLength; -} -function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - switch (typeof value) { - case 'string': - return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; - case 'number': - if (Math.floor(value) === value && - value >= JS_INT_MIN && - value <= JS_INT_MAX) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); - } - else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - } - else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); - case 'object': - if (value != null && - typeof value._bsontype === 'string' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; - } - else if (value._bsontype === 'ObjectId') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); - } - else if (value instanceof Date || isDate(value)) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - else if (ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - isAnyArrayBuffer(value)) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); - } - else if (value._bsontype === 'Long' || - value._bsontype === 'Double' || - value._bsontype === 'Timestamp') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - else if (value._bsontype === 'Decimal128') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); - } - else if (value._bsontype === 'Code') { - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - 4 + - 4 + - ByteUtils.utf8ByteLength(value.code.toString()) + - 1 + - internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); - } - else { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - 4 + - ByteUtils.utf8ByteLength(value.code.toString()) + - 1); - } - } - else if (value._bsontype === 'Binary') { - const binary = value; - if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - (binary.position + 1 + 4 + 1 + 4)); - } - else { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); - } - } - else if (value._bsontype === 'Symbol') { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - ByteUtils.utf8ByteLength(value.value) + - 4 + - 1 + - 1); - } - else if (value._bsontype === 'DBRef') { - const ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - if (value.db != null) { - ordered_values['$db'] = value.db; - } - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); - } - else if (value instanceof RegExp || isRegExp(value)) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - ByteUtils.utf8ByteLength(value.source) + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else if (value._bsontype === 'BSONRegExp') { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - ByteUtils.utf8ByteLength(value.pattern) + - 1 + - ByteUtils.utf8ByteLength(value.options) + - 1); - } - else { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1); - } - case 'function': - if (serializeFunctions) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - 4 + - ByteUtils.utf8ByteLength(value.toString()) + - 1); - } - } - return 0; -} - -function alphabetize(str) { - return str.split('').sort().join(''); -} -class BSONRegExp extends BSONValue { - get _bsontype() { - return 'BSONRegExp'; - } - constructor(pattern, options) { - super(); - this.pattern = pattern; - this.options = alphabetize(options ?? ''); - if (this.pattern.indexOf('\x00') !== -1) { - throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); - } - if (this.options.indexOf('\x00') !== -1) { - throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); - } - for (let i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u')) { - throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); - } - } - } - static parseOptions(options) { - return options ? options.split('').sort().join('') : ''; - } - toExtendedJSON(options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - } - static fromExtendedJSON(doc) { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc; - } - } - else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); - } - throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; - } -} - -class BSONSymbol extends BSONValue { - get _bsontype() { - return 'BSONSymbol'; - } - constructor(value) { - super(); - this.value = value; - } - valueOf() { - return this.value; - } - toString() { - return this.value; - } - inspect() { - return `new BSONSymbol("${this.value}")`; - } - toJSON() { - return this.value; - } - toExtendedJSON() { - return { $symbol: this.value }; - } - static fromExtendedJSON(doc) { - return new BSONSymbol(doc.$symbol); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } -} - -const LongWithoutOverridesClass = Long; -class Timestamp extends LongWithoutOverridesClass { - get _bsontype() { - return 'Timestamp'; - } - constructor(low) { - if (low == null) { - super(0, 0, true); - } - else if (typeof low === 'bigint') { - super(low, true); - } - else if (Long.isLong(low)) { - super(low.low, low.high, true); - } - else if (typeof low === 'object' && 't' in low && 'i' in low) { - if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { - throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); - } - if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { - throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); - } - if (low.t < 0) { - throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); - } - if (low.i < 0) { - throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); - } - if (low.t > 4294967295) { - throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); - } - if (low.i > 4294967295) { - throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); - } - super(low.i.valueOf(), low.t.valueOf(), true); - } - else { - throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); - } - } - toJSON() { - return { - $timestamp: this.toString() - }; - } - static fromInt(value) { - return new Timestamp(Long.fromInt(value, true)); - } - static fromNumber(value) { - return new Timestamp(Long.fromNumber(value, true)); - } - static fromBits(lowBits, highBits) { - return new Timestamp({ i: lowBits, t: highBits }); - } - static fromString(str, optRadix) { - return new Timestamp(Long.fromString(str, true, optRadix)); - } - toExtendedJSON() { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - } - static fromExtendedJSON(doc) { - const i = Long.isLong(doc.$timestamp.i) - ? doc.$timestamp.i.getLowBitsUnsigned() - : doc.$timestamp.i; - const t = Long.isLong(doc.$timestamp.t) - ? doc.$timestamp.t.getLowBitsUnsigned() - : doc.$timestamp.t; - return new Timestamp({ t, i }); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; - } -} -Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - -const FIRST_BIT = 0x80; -const FIRST_TWO_BITS = 0xc0; -const FIRST_THREE_BITS = 0xe0; -const FIRST_FOUR_BITS = 0xf0; -const FIRST_FIVE_BITS = 0xf8; -const TWO_BIT_CHAR = 0xc0; -const THREE_BIT_CHAR = 0xe0; -const FOUR_BIT_CHAR = 0xf0; -const CONTINUING_CHAR = 0x80; -function validateUtf8(bytes, start, end) { - let continuation = 0; - for (let i = start; i < end; i += 1) { - const byte = bytes[i]; - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } - else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } - else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } - else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } - else { - return false; - } - } - } - return !continuation; -} - -const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); -const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); -function internalDeserialize(buffer, options, isArray) { - options = options == null ? {} : options; - const index = options && options.index ? options.index : 0; - const size = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (size < 5) { - throw new BSONError(`bson size must be >= 5, is ${size}`); - } - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); - } - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); - } - if (size + index > buffer.byteLength) { - throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`); - } - if (buffer[index + size - 1] !== 0) { - throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - return deserializeObject(buffer, index, options, isArray); -} -const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; -function deserializeObject(buffer, index, options, isArray = false) { - const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - const raw = options['raw'] == null ? false : options['raw']; - const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - const promoteBuffers = options.promoteBuffers ?? false; - const promoteLongs = options.promoteLongs ?? true; - const promoteValues = options.promoteValues ?? true; - const useBigInt64 = options.useBigInt64 ?? false; - if (useBigInt64 && !promoteValues) { - throw new BSONError('Must either request bigint or Long for int64 deserialization'); - } - if (useBigInt64 && !promoteLongs) { - throw new BSONError('Must either request bigint or Long for int64 deserialization'); - } - const validation = options.validation == null ? { utf8: true } : options.validation; - let globalUTFValidation = true; - let validationSetting; - const utf8KeysSet = new Set(); - const utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } - else { - globalUTFValidation = false; - const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - if (!utf8ValidationValues.every(item => item === validationSetting)) { - throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - if (!globalUTFValidation) { - for (const key of Object.keys(utf8ValidatedKeys)) { - utf8KeysSet.add(key); - } - } - const startIndex = index; - if (buffer.length < 5) - throw new BSONError('corrupt bson message < 5 bytes long'); - const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - if (size < 5 || size > buffer.length) - throw new BSONError('corrupt bson message'); - const object = isArray ? [] : {}; - let arrayIndex = 0; - const done = false; - let isPossibleDBRef = isArray ? false : null; - const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); - while (!done) { - const elementType = buffer[index++]; - if (elementType === 0) - break; - let i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.byteLength) - throw new BSONError('Bad BSON Document: illegal CString'); - const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); - let shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } - else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - let value; - index = i + 1; - if (elementType === BSON_DATA_STRING) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } - else if (elementType === BSON_DATA_OID) { - const oid = ByteUtils.allocate(12); - oid.set(buffer.subarray(index, index + 12)); - value = new ObjectId(oid); - index = index + 12; - } - else if (elementType === BSON_DATA_INT && promoteValues === false) { - value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); - } - else if (elementType === BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } - else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { - value = new Double(dataview.getFloat64(index, true)); - index = index + 8; - } - else if (elementType === BSON_DATA_NUMBER) { - value = dataview.getFloat64(index, true); - index = index + 8; - } - else if (elementType === BSON_DATA_DATE) { - const lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new Long(lowBits, highBits).toNumber()); - } - else if (elementType === BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } - else if (elementType === BSON_DATA_OBJECT) { - const _index = index; - const objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new BSONError('bad embedded document length in bson'); - if (raw) { - value = buffer.slice(index, index + objectSize); - } - else { - let objectOptions = options; - if (!globalUTFValidation) { - objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - index = index + objectSize; - } - else if (elementType === BSON_DATA_ARRAY) { - const _index = index; - const objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - let arrayOptions = options; - const stopIndex = index + objectSize; - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = { ...options, raw: true }; - } - if (!globalUTFValidation) { - arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - if (buffer[index - 1] !== 0) - throw new BSONError('invalid array terminator byte'); - if (index !== stopIndex) - throw new BSONError('corrupted array bson'); - } - else if (elementType === BSON_DATA_UNDEFINED) { - value = undefined; - } - else if (elementType === BSON_DATA_NULL) { - value = null; - } - else if (elementType === BSON_DATA_LONG) { - const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); - const lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const long = new Long(lowBits, highBits); - if (useBigInt64) { - value = dataview.getBigInt64(0, true); - } - else if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } - else { - value = long; - } - } - else if (elementType === BSON_DATA_DECIMAL128) { - const bytes = ByteUtils.allocate(16); - bytes.set(buffer.subarray(index, index + 16), 0); - index = index + 16; - value = new Decimal128(bytes); - } - else if (elementType === BSON_DATA_BINARY) { - let binarySize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const totalBinarySize = binarySize; - const subType = buffer[index++]; - if (binarySize < 0) - throw new BSONError('Negative binary type element size found'); - if (binarySize > buffer.byteLength) - throw new BSONError('Binary type size larger than document size'); - if (buffer['slice'] != null) { - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - if (promoteBuffers && promoteValues) { - value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { - value = value.toUUID(); - } - } - } - else { - const _buffer = ByteUtils.allocate(binarySize); - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - if (promoteBuffers && promoteValues) { - value = _buffer; - } - else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { - value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - } - } - index = index + binarySize; - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const source = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - const optionsArray = new Array(regExpOptions.length); - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - value = new RegExp(source, optionsArray.join('')); - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const source = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - value = new BSONRegExp(source, regExpOptions); - } - else if (elementType === BSON_DATA_SYMBOL) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - const symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new BSONSymbol(symbol); - index = index + stringSize; - } - else if (elementType === BSON_DATA_TIMESTAMP) { - const i = buffer[index++] + - buffer[index++] * (1 << 8) + - buffer[index++] * (1 << 16) + - buffer[index++] * (1 << 24); - const t = buffer[index++] + - buffer[index++] * (1 << 8) + - buffer[index++] * (1 << 16) + - buffer[index++] * (1 << 24); - value = new Timestamp({ i, t }); - } - else if (elementType === BSON_DATA_MIN_KEY) { - value = new MinKey(); - } - else if (elementType === BSON_DATA_MAX_KEY) { - value = new MaxKey(); - } - else if (elementType === BSON_DATA_CODE) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = new Code(functionString); - index = index + stringSize; - } - else if (elementType === BSON_DATA_CODE_W_SCOPE) { - const totalSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError('code_w_scope total size shorter minimum expected length'); - } - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - const _index = index; - const objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - const scopeObject = deserializeObject(buffer, _index, options, false); - index = index + objectSize; - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too short, truncating scope'); - } - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too long, clips outer document'); - } - value = new Code(functionString, scopeObject); - } - else if (elementType === BSON_DATA_DBPOINTER) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) - throw new BSONError('bad string length in bson'); - if (validation != null && validation.utf8) { - if (!validateUtf8(buffer, index, index + stringSize - 1)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - } - const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); - index = index + stringSize; - const oidBuffer = ByteUtils.allocate(12); - oidBuffer.set(buffer.subarray(index, index + 12), 0); - const oid = new ObjectId(oidBuffer); - index = index + 12; - value = new DBRef(namespace, oid); - } - else { - throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - object[name] = value; - } - } - if (size !== index - startIndex) { - if (isArray) - throw new BSONError('corrupt array bson'); - throw new BSONError('corrupt object bson'); - } - if (!isPossibleDBRef) - return object; - if (isDBRefLike(object)) { - const copy = Object.assign({}, object); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object.$ref, object.$id, object.$db, copy); - } - return object; -} -function getValidatedString(buffer, start, end, shouldValidateUtf8) { - const value = ByteUtils.toUTF8(buffer.subarray(start, end)); - if (shouldValidateUtf8) { - for (let i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validateUtf8(buffer, start, end)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; -} - -const regexp = /\x00/; -const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); -function serializeString(buffer, key, value, index) { - buffer[index++] = BSON_DATA_STRING; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - index = index + 4 + size; - buffer[index++] = 0; - return index; -} -const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); -const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); -const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); -function serializeNumber(buffer, key, value, index) { - const isNegativeZero = Object.is(value, -0); - const type = !isNegativeZero && - Number.isSafeInteger(value) && - value <= BSON_INT32_MAX && - value >= BSON_INT32_MIN - ? BSON_DATA_INT - : BSON_DATA_NUMBER; - if (type === BSON_DATA_INT) { - NUMBER_SPACE.setInt32(0, value, true); - } - else { - NUMBER_SPACE.setFloat64(0, value, true); - } - const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; - buffer[index++] = type; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0x00; - buffer.set(bytes, index); - index += bytes.byteLength; - return index; -} -function serializeBigInt(buffer, key, value, index) { - buffer[index++] = BSON_DATA_LONG; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index += numberOfWrittenBytes; - buffer[index++] = 0; - NUMBER_SPACE.setBigInt64(0, value, true); - buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); - index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; - return index; -} -function serializeNull(buffer, key, _, index) { - buffer[index++] = BSON_DATA_NULL; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeBoolean(buffer, key, value, index) { - buffer[index++] = BSON_DATA_BOOLEAN; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - buffer[index++] = value ? 1 : 0; - return index; -} -function serializeDate(buffer, key, value, index) { - buffer[index++] = BSON_DATA_DATE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const dateInMilis = Long.fromNumber(value.getTime()); - const lowBits = dateInMilis.getLowBits(); - const highBits = dateInMilis.getHighBits(); - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeRegExp(buffer, key, value, index) { - buffer[index++] = BSON_DATA_REGEXP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw new BSONError('value ' + value.source + ' must not contain null bytes'); - } - index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); - buffer[index++] = 0x00; - if (value.ignoreCase) - buffer[index++] = 0x69; - if (value.global) - buffer[index++] = 0x73; - if (value.multiline) - buffer[index++] = 0x6d; - buffer[index++] = 0x00; - return index; -} -function serializeBSONRegExp(buffer, key, value, index) { - buffer[index++] = BSON_DATA_REGEXP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.pattern.match(regexp) != null) { - throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); - } - index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); - buffer[index++] = 0x00; - const sortedOptions = value.options.split('').sort().join(''); - index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); - buffer[index++] = 0x00; - return index; -} -function serializeMinMax(buffer, key, value, index) { - if (value === null) { - buffer[index++] = BSON_DATA_NULL; - } - else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON_DATA_MIN_KEY; - } - else { - buffer[index++] = BSON_DATA_MAX_KEY; - } - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeObjectId(buffer, key, value, index) { - buffer[index++] = BSON_DATA_OID; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (isUint8Array(value.id)) { - buffer.set(value.id.subarray(0, 12), index); - } - else { - throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - return index + 12; -} -function serializeBuffer(buffer, key, value, index) { - buffer[index++] = BSON_DATA_BINARY; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const size = value.length; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; - buffer.set(value, index); - index = index + size; - return index; -} -function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { - if (path.has(value)) { - throw new BSONError('Cannot convert circular structure to BSON'); - } - path.add(value); - buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - path.delete(value); - return endIndex; -} -function serializeDecimal128(buffer, key, value, index) { - buffer[index++] = BSON_DATA_DECIMAL128; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; -} -function serializeLong(buffer, key, value, index) { - buffer[index++] = - value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const lowBits = value.getLowBits(); - const highBits = value.getHighBits(); - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeInt32(buffer, key, value, index) { - value = value.valueOf(); - buffer[index++] = BSON_DATA_INT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -} -function serializeDouble(buffer, key, value, index) { - buffer[index++] = BSON_DATA_NUMBER; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - NUMBER_SPACE.setFloat64(0, value.value, true); - buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); - index = index + 8; - return index; -} -function serializeFunction(buffer, key, value, index) { - buffer[index++] = BSON_DATA_CODE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const functionString = value.toString(); - const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - index = index + 4 + size - 1; - buffer[index++] = 0; - return index; -} -function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { - if (value.scope && typeof value.scope === 'object') { - buffer[index++] = BSON_DATA_CODE_W_SCOPE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - let startIndex = index; - const functionString = value.code; - index = index + 4; - const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - buffer[index + 4 + codeSize - 1] = 0; - index = index + codeSize + 4; - const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - index = endIndex - 1; - const totalSize = endIndex - startIndex; - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - buffer[index++] = 0; - } - else { - buffer[index++] = BSON_DATA_CODE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const functionString = value.code.toString(); - const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - index = index + 4 + size - 1; - buffer[index++] = 0; - } - return index; -} -function serializeBinary(buffer, key, value, index) { - buffer[index++] = BSON_DATA_BINARY; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const data = value.buffer; - let size = value.position; - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - buffer[index++] = value.sub_type; - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - buffer.set(data, index); - index = index + value.position; - return index; -} -function serializeSymbol(buffer, key, value, index) { - buffer[index++] = BSON_DATA_SYMBOL; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - index = index + 4 + size - 1; - buffer[index++] = 0x00; - return index; -} -function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { - buffer[index++] = BSON_DATA_OBJECT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - let startIndex = index; - let output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; - } - output = Object.assign(output, value.fields); - const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path); - const size = endIndex - startIndex; - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - return endIndex; -} -function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - if (path == null) { - if (object == null) { - buffer[0] = 0x05; - buffer[1] = 0x00; - buffer[2] = 0x00; - buffer[3] = 0x00; - buffer[4] = 0x00; - return 5; - } - if (Array.isArray(object)) { - throw new BSONError('serialize does not support an array as the root input'); - } - if (typeof object !== 'object') { - throw new BSONError('serialize does not support non-object as the root input'); - } - else if ('_bsontype' in object && typeof object._bsontype === 'string') { - throw new BSONError(`BSON types cannot be serialized as a document`); - } - else if (isDate(object) || - isRegExp(object) || - isUint8Array(object) || - isAnyArrayBuffer(object)) { - throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); - } - path = new Set(); - } - path.add(object); - let index = startingIndex + 4; - if (Array.isArray(object)) { - for (let i = 0; i < object.length; i++) { - const key = `${i}`; - let value = object[i]; - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (typeof value === 'bigint') { - index = serializeBigInt(buffer, key, value, index); - } - else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (typeof value === 'object' && value._bsontype == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'object' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value._bsontype === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } - else if (value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value._bsontype === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index); - } - else if (value._bsontype === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (value._bsontype === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value._bsontype === 'BSONSymbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value._bsontype === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); - } - else if (value._bsontype === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value._bsontype === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value._bsontype !== 'undefined') { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } - } - else if (object instanceof Map || isMap(object)) { - const iterator = object.entries(); - let done = false; - while (!done) { - const entry = iterator.next(); - done = !!entry.done; - if (done) - continue; - const key = entry.value[0]; - let value = entry.value[1]; - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - const type = typeof value; - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - throw new BSONError('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw new BSONError('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw new BSONError('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - index = serializeBigInt(buffer, key, value, index); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'object' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value._bsontype === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value._bsontype === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value._bsontype === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index); - } - else if (value._bsontype === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value._bsontype === 'BSONSymbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value._bsontype === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); - } - else if (value._bsontype === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value._bsontype === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value._bsontype !== 'undefined') { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } - } - else { - if (typeof object?.toBSON === 'function') { - object = object.toBSON(); - if (object != null && typeof object !== 'object') { - throw new BSONError('toBSON function did not return an object'); - } - } - for (const key of Object.keys(object)) { - let value = object[key]; - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - const type = typeof value; - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - throw new BSONError('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw new BSONError('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw new BSONError('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - index = serializeBigInt(buffer, key, value, index); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - if (ignoreUndefined === false) - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'object' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value._bsontype === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value._bsontype === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value._bsontype === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index); - } - else if (value._bsontype === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value._bsontype === 'BSONSymbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value._bsontype === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); - } - else if (value._bsontype === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value._bsontype === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value._bsontype !== 'undefined') { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } - } - path.delete(object); - buffer[index++] = 0x00; - const size = index - startingIndex; - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -function isBSONType(value) { - return (value != null && - typeof value === 'object' && - '_bsontype' in value && - typeof value._bsontype === 'string'); -} -const keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp -}; -function deserializeValue(value, options = {}) { - if (typeof value === 'number') { - const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; - const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; - if (options.relaxed || options.legacy) { - return value; - } - if (Number.isInteger(value) && !Object.is(value, -0)) { - if (in32BitRange) { - return new Int32(value); - } - if (in64BitRange) { - if (options.useBigInt64) { - return BigInt(value); - } - return Long.fromNumber(value); - } - } - return new Double(value); - } - if (value == null || typeof value !== 'object') - return value; - if (value.$undefined) - return null; - const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); - for (let i = 0; i < keys.length; i++) { - const c = keysToCodecs[keys[i]]; - if (c) - return c.fromExtendedJSON(value, options); - } - if (value.$date != null) { - const d = value.$date; - const date = new Date(); - if (options.legacy) { - if (typeof d === 'number') - date.setTime(d); - else if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (typeof d === 'bigint') - date.setTime(Number(d)); - else - throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); - } - else { - if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (Long.isLong(d)) - date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) - date.setTime(d); - else if (typeof d === 'bigint') - date.setTime(Number(d)); - else - throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); - } - return date; - } - if (value.$code != null) { - const copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return Code.fromExtendedJSON(value); - } - if (isDBRefLike(value) || value.$dbPointer) { - const v = value.$ref ? value : value.$dbPointer; - if (v instanceof DBRef) - return v; - const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); - let valid = true; - dollarKeys.forEach(k => { - if (['$ref', '$id', '$db'].indexOf(k) === -1) - valid = false; - }); - if (valid) - return DBRef.fromExtendedJSON(v); - } - return value; -} -function serializeArray(array, options) { - return array.map((v, index) => { - options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); - try { - return serializeValue(v, options); - } - finally { - options.seenObjects.pop(); - } - }); -} -function getISOString(date) { - const isoStr = date.toISOString(); - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; -} -function serializeValue(value, options) { - if (value instanceof Map || isMap(value)) { - const obj = Object.create(null); - for (const [k, v] of value) { - if (typeof k !== 'string') { - throw new BSONError('Can only serialize maps with string keys'); - } - obj[k] = v; - } - return serializeValue(obj, options); - } - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - const index = options.seenObjects.findIndex(entry => entry.obj === value); - if (index !== -1) { - const props = options.seenObjects.map(entry => entry.propertyName); - const leadingPart = props - .slice(0, index) - .map(prop => `${prop} -> `) - .join(''); - const alreadySeen = props[index]; - const circularPart = ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(prop => `${prop} -> `) - .join(''); - const current = props[props.length - 1]; - const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new BSONError('Converting circular structure to EJSON:\n' + - ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + - ` ${leadingSpace}\\${dashes}/`); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || isDate(value)) { - const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - if (Number.isInteger(value) && !Object.is(value, -0)) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - return { $numberInt: value.toString() }; - } - if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { - return { $numberLong: value.toString() }; - } - } - return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; - } - if (typeof value === 'bigint') { - if (!options.relaxed) { - return { $numberLong: BigInt.asIntN(64, value).toString() }; - } - return Number(BigInt.asIntN(64, value)); - } - if (value instanceof RegExp || isRegExp(value)) { - let flags = value.flags; - if (flags === undefined) { - const match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - const rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - if (value != null && typeof value === 'object') - return serializeDocument(value, options); - return value; -} -const BSON_TYPE_MAPPINGS = { - Binary: (o) => new Binary(o.value(), o.sub_type), - Code: (o) => new Code(o.code, o.scope), - DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), - Decimal128: (o) => new Decimal128(o.bytes), - Double: (o) => new Double(o.value), - Int32: (o) => new Int32(o.value), - Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), - MaxKey: () => new MaxKey(), - MinKey: () => new MinKey(), - ObjectId: (o) => new ObjectId(o), - BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), - BSONSymbol: (o) => new BSONSymbol(o.value), - Timestamp: (o) => Timestamp.fromBits(o.low, o.high) -}; -function serializeDocument(doc, options) { - if (doc == null || typeof doc !== 'object') - throw new BSONError('not an object instance'); - const bsontype = doc._bsontype; - if (typeof bsontype === 'undefined') { - const _doc = {}; - for (const name of Object.keys(doc)) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - const value = serializeValue(doc[name], options); - if (name === '__proto__') { - Object.defineProperty(_doc, name, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - _doc[name] = value; - } - } - finally { - options.seenObjects.pop(); - } - } - return _doc; - } - else if (doc != null && - typeof doc === 'object' && - typeof doc._bsontype === 'string' && - doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (isBSONType(doc)) { - let outDoc = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } - else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); - } - return outDoc.toExtendedJSON(options); - } - else { - throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } -} -function parse(text, options) { - const ejsonOptions = { - useBigInt64: options?.useBigInt64 ?? false, - relaxed: options?.relaxed ?? true, - legacy: options?.legacy ?? false - }; - return JSON.parse(text, (key, value) => { - if (key.indexOf('\x00') !== -1) { - throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); - } - return deserializeValue(value, ejsonOptions); - }); -} -function stringify(value, replacer, space, options) { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - const doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer, space); -} -function EJSONserialize(value, options) { - options = options || {}; - return JSON.parse(stringify(value, options)); -} -function EJSONdeserialize(ejson, options) { - options = options || {}; - return parse(JSON.stringify(ejson), options); -} -const EJSON = Object.create(null); -EJSON.parse = parse; -EJSON.stringify = stringify; -EJSON.serialize = EJSONserialize; -EJSON.deserialize = EJSONdeserialize; -Object.freeze(EJSON); - -const MAXSIZE = 1024 * 1024 * 17; -let buffer = ByteUtils.allocate(MAXSIZE); -function setInternalBufferSize(size) { - if (buffer.length < size) { - buffer = ByteUtils.allocate(size); - } -} -function serialize(object, options = {}) { - const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - if (buffer.length < minInternalBufferSize) { - buffer = ByteUtils.allocate(minInternalBufferSize); - } - const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); - const finishedBuffer = ByteUtils.allocate(serializationIndex); - finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); - return finishedBuffer; -} -function serializeWithBufferAndIndex(object, finalBuffer, options = {}) { - const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - const startIndex = typeof options.index === 'number' ? options.index : 0; - const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); - finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); - return startIndex + serializationIndex - 1; -} -function deserialize(buffer, options = {}) { - return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); -} -function calculateObjectSize(object, options = {}) { - options = options || {}; - const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); -} -function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - const bufferData = ByteUtils.toLocalBufferType(data); - let index = startIndex; - for (let i = 0; i < numberOfDocuments; i++) { - const size = bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - internalOptions.index = index; - documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); - index = index + size; - } - return index; -} - -var bson = /*#__PURE__*/Object.freeze({ - __proto__: null, - Code: Code, - BSONSymbol: BSONSymbol, - DBRef: DBRef, - Binary: Binary, - ObjectId: ObjectId, - UUID: UUID, - Long: Long, - Timestamp: Timestamp, - Double: Double, - Int32: Int32, - MinKey: MinKey, - MaxKey: MaxKey, - BSONRegExp: BSONRegExp, - Decimal128: Decimal128, - setInternalBufferSize: setInternalBufferSize, - serialize: serialize, - serializeWithBufferAndIndex: serializeWithBufferAndIndex, - deserialize: deserialize, - calculateObjectSize: calculateObjectSize, - deserializeStream: deserializeStream, - BSONValue: BSONValue, - BSONError: BSONError, - BSONVersionError: BSONVersionError, - BSONRuntimeError: BSONRuntimeError, - BSONType: BSONType, - EJSON: EJSON -}); - -exports.BSON = bson; -exports.BSONError = BSONError; -exports.BSONRegExp = BSONRegExp; -exports.BSONRuntimeError = BSONRuntimeError; -exports.BSONSymbol = BSONSymbol; -exports.BSONType = BSONType; -exports.BSONValue = BSONValue; -exports.BSONVersionError = BSONVersionError; -exports.Binary = Binary; -exports.Code = Code; -exports.DBRef = DBRef; -exports.Decimal128 = Decimal128; -exports.Double = Double; -exports.EJSON = EJSON; -exports.Int32 = Int32; -exports.Long = Long; -exports.MaxKey = MaxKey; -exports.MinKey = MinKey; -exports.ObjectId = ObjectId; -exports.Timestamp = Timestamp; -exports.UUID = UUID; -exports.calculateObjectSize = calculateObjectSize; -exports.deserialize = deserialize; -exports.deserializeStream = deserializeStream; -exports.serialize = serialize; -exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; -exports.setInternalBufferSize = setInternalBufferSize; -//# sourceMappingURL=bson.cjs.map diff --git a/src/extras/struct/datastructures/types.ts b/src/extras/struct/datastructures/types.ts index c16eb314..7e096035 100644 --- a/src/extras/struct/datastructures/types.ts +++ b/src/extras/struct/datastructures/types.ts @@ -6,8 +6,7 @@ export type Struct = { structType?:string|number, timestamp?:string|number, ownerId?:string|number, - parent?:{structType:string,_id:string|number}, - [key:string]:any + parent?:{structType:string,_id:string|number} } export type DataTypes = 'byTime' | 'notes' | 'events' | 'sleep' | 'food' | 'rx' | 'hr' | 'ppg' | 'hrv' | 'ecg' | 'emg' | 'eeg' | 'fnirs' | string | number | undefined @@ -34,14 +33,11 @@ export type EventStruct = { event:string, //event type e.g. relapse, hospitalization author:string, startTime:string, //event began - endTime?:string, //event ended - grade?:string|number, //severity - value?:any, //e.g. heart rate, distance - units?:string, //e.g. bpm, millimeteres - notes?:string, //additional details - location?:any, - attachments?:Data|string|number[], //can be data or struct Ids - users?:{[key:string]:true}, //users to be informed (i.e. peers) + endTime:string, //event ended + grade:string|number, //severity + notes:string, //additional details + attachments:Data|string|number[], //can be data or struct Ids + users:{}, //users to be informed (i.e. peers) tag?:string|number } & Struct @@ -52,7 +48,7 @@ export type ChatroomStruct = { attachments: Data|string|number[], comments: string[], //all comment struct Ids replies: string[], //first level reply comment struct Ids - users: {[key:string]:true}, //user Ids + users: {}, //user Ids audioChatActive: boolean, videoChatActive: boolean, tag?:string|number @@ -63,7 +59,7 @@ export type CommentStruct = { replyTo:string, attachments: Data|string|number[], replies: string[], //struct Ids - users:{[key:string]:true}, //user Ids + users: {}, //user Ids tag?:string|number } & Struct @@ -90,11 +86,10 @@ export type DateStruct = { } & Struct export type ProfileStruct = { - username?: string, + username: string, name?: string, firstName?: string, lastName?: string, - fullName?: string, email?: string, phone?: string, sex?: string, @@ -103,11 +98,8 @@ export type ProfileStruct = { socials?: {}, data?: {}, type?: string, - hidden?: boolean, - pictureUrl: string, - accessToken?:string, - refreshToken?:string, - tag?:string|number + id?: string|number, + tag?:string|number } & Struct export type AuthorizationStruct = { diff --git a/src/extras/struct/genTimestamps.ts b/src/extras/struct/genTimestamps.ts deleted file mode 100644 index 38c74670..00000000 --- a/src/extras/struct/genTimestamps.ts +++ /dev/null @@ -1,110 +0,0 @@ - -//thanks gpt -export type TimeUnit = - | 'second' - | 'minute' - | 'hour' - | 'day' - | 'week' - | 'month' - | 'year' - | 'decade' - | 'century' - | 'millennium' - | 'microsecond' - | 'nanosecond'; - -type Plural = `${T}s`; - -export type TimeSpecifier = `now` | `last ${string} ${Plural}` | `last ${TimeUnit}`; - -export let defaultSpecifiers = [ - 'now', - 'minute', - '5 minutes', - '30 minutes', - 'hour', - '6 hours', - '12 hours', - 'day', - '3 days', - 'week', - '2 weeks', - 'month', - '6 months', - 'year', - '5 years', - 'decade', -] as ('now'|TimeUnit)[]; - -export function genTimeSpecifiers( - specifiers = defaultSpecifiers as ('now'|TimeUnit)[] -) { - let result = ['now']; - specifiers.forEach((s) => { - if(s !== 'now') - result.push(`last ${s}`); - else result.push(s); - }); - - return result; -} - -export function genTimestampFromString(specifier: TimeSpecifier): number { - const now = new Date(); - - if(specifier === 'now') {} - else if (specifier === 'last minute') { - now.setMinutes(now.getMinutes() - 1); - } else if (specifier === 'last hour') { - now.setHours(now.getHours() - 1); - } else if (specifier === 'last day') { - now.setDate(now.getDate() - 1); - } else if (specifier === 'last week') { - now.setDate(now.getDate() - 7); - } else if (specifier === 'last month') { - now.setMonth(now.getMonth() - 1); - } else if (specifier === 'last year') { - now.setFullYear(now.getFullYear() - 1); - } else if (specifier === 'last decade') { - now.setFullYear(now.getFullYear() - 1 * 10); - } else if (specifier === 'last century') { - now.setFullYear(now.getFullYear() - 1 * 100); - } else if (specifier === 'last millennium') { - now.setFullYear(now.getFullYear() - 1 * 1000); - } else if (specifier === 'last microsecond') { - now.setMilliseconds(now.getMilliseconds() - 1); - } else if (specifier === 'last nanosecond') { - now.setMilliseconds(now.getMilliseconds() - 1 * 0.001); - } else if (specifier.startsWith('last')) { - const [, count, unit] = specifier.match(/last (\d+) (\w+)/) || []; - if (count && unit) { - const num = parseInt(count, 10); - if (unit.includes('minute')) { - now.setMinutes(now.getMinutes() - num); - } else if (unit.includes('hour')) { - now.setHours(now.getHours() - num); - } else if (unit.includes('day')) { - now.setDate(now.getDate() - num); - } else if (unit.includes('week')) { - now.setDate(now.getDate() - num * 7); - } else if (unit.includes('month')) { - now.setMonth(now.getMonth() - num); - } else if (unit.includes('year')) { - now.setFullYear(now.getFullYear() - num); - } else if (unit.includes('decade')) { - now.setFullYear(now.getFullYear() - num * 10); - } else if (unit.includes('century')) { - now.setFullYear(now.getFullYear() - num * 100); - } else if (unit.includes('millennium')) { - now.setFullYear(now.getFullYear() - num * 1000); - } else if (unit.includes('microsecond')) { - now.setMilliseconds(now.getMilliseconds() - num); - } else if (unit.includes('nanosecond')) { - now.setMilliseconds(now.getMilliseconds() - num * 0.001); - } - } - } - - return now.getTime(); - } \ No newline at end of file diff --git a/src/extras/todo.md b/src/extras/todo.md deleted file mode 100644 index df0255f6..00000000 --- a/src/extras/todo.md +++ /dev/null @@ -1 +0,0 @@ -Really need to fix the dist splitting types up \ No newline at end of file diff --git a/src/extras/tsconfig.json b/src/extras/tsconfig.json index 512d0007..3926fc9c 100644 --- a/src/extras/tsconfig.json +++ b/src/extras/tsconfig.json @@ -1,11 +1,11 @@ { - "include": ["index.services.ts"], + "include": ["build/services/index.services.ts"], "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, - "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + "target": "es2020" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "es2020" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, "declaration": true, /* Generates corresponding '.d.ts' file. */ "allowJs": true, /* Allow javascript files to be compiled. */ "skipLibCheck": true /* Skip type checking of declaration files. */, diff --git a/src/loaders/html/DOMElement.d.ts b/src/loaders/html/DOMElement.d.ts index 19fddeb3..538004c8 100644 --- a/src/loaders/html/DOMElement.d.ts +++ b/src/loaders/html/DOMElement.d.ts @@ -1,6 +1,5 @@ //todo: make this the permanent version so I can stop copying manually each build -export function html(strings,...args): any; export function addCustomElement(cls: any, tag: any, extend?: any): void; export function randomId(tag?: string): string; export function parseFunctionFromText(method: any): any; diff --git a/src/loaders/html/DOMElement.js b/src/loaders/html/DOMElement.js index b7761d33..e829101b 100644 --- a/src/loaders/html/DOMElement.js +++ b/src/loaders/html/DOMElement.js @@ -1,31 +1,41 @@ -import { html } from "./html"; -let dummy = html``; - -//from 'fragelement' on npm by Joshua Brewster (LGPL v3.0) +//from 'fragelement' on npm by Joshua Brewster (AGPL v3.0) export class DOMElement extends HTMLElement { - // template = function(self=this, props){ //return a string or html node - // return `
Custom Fragment Props: ${JSON.stringify(props)}
` - // }; //override the default template string by extending the class, or use options.template if calling the base class - // props = {}; + template = function(self=this, props){ //return a string or html node + return `
Custom Fragment Props: ${JSON.stringify(props)}
` + }; //override the default template string by extending the class, or use options.template if calling the base class + props = {}; useShadow = false; //can set to attach a shadow DOM instead (local styles) - // styles; //can set a style sheet which will toggle the shadow dom by default + styles; //can set a style sheet which will toggle the shadow dom by default // NOTE: Referencing this inside one of these events will give you the GraphNode - // oncreate; //(self,props) => {} fires on element creation (e.g. to set up logic) - // onresize; //(self,props) => {} fires on window resize - // ondelete; //(self,props) => {} fires after element is deleted - // onchanged; //(props) => {} fires when props change - //renderonchanged=false; //(self,props) => {} fires after rerendering on props change + oncreate; //(self,props) => {} fires on element creation (e.g. to set up logic) + onresize; //(self,props) => {} fires on window resize + ondelete; //(self,props) => {} fires after element is deleted + onchanged; //(props) => {} fires when props change + renderonchanged=false; //(self,props) => {} fires after rerendering on props change FRAGMENT; STYLE; attachedShadow = false; - static get tag(){return this.name.toLowerCase()+'-'} //tagName, default 'classname-'. Set as a static variable for the internal addElement to reference - obsAttributes=["props","options","onchanged","onresize","ondelete","oncreate","template"] - props = {}; + get observedAttributes() { + return this.obsAttributes; + } + + get obsAttributes() { + return this.obsAttributes; + } + + set obsAttributes(att) { + if(typeof att === 'string') { + this.obsAttributes.push(att); + } else if (Array.isArray(att)) this.obsAttributes=att; + } + + static get tag(){return this.name.toLowerCase()+'-'} //tagName, default 'classname-'. Set as a static variable for the internal addElement to reference + //add self or a specified class to the window which can be used via html like //will default be the classname with a '-' at the end if no tag supplied static addElement(tag=this.tag,cls=this,extend=undefined) { @@ -237,28 +247,20 @@ export class DOMElement extends HTMLElement { render = (props=this.props) => { - const t = document.createElement('template'); - - let usingHTMLFunction = this.template.prototype?.constructor?.name == dummy.prototype.constructor.name; - if(typeof this.template === 'function') { - if(usingHTMLFunction) { //html function - this.template(t.content); - } - else this.templateResult = this.template(this, props); - } //can pass a function + if(typeof this.template === 'function') this.templateResult = this.template(this, props); //can pass a function else this.templateResult = this.template; if(this.styles) this.templateResult = `${this.templateResult}`; //this.innerHTML = this.templateResult; - if(!usingHTMLFunction) { - if(typeof this.templateResult === 'string') t.innerHTML = this.templateResult; - else if(this.templateResult instanceof HTMLElement || this.templateResult instanceof DocumentFragment) { - if(this.templateResult.parentNode) { - this.templateResult.parentNode.removeChild(this.templateResult); //swap to the new component - } - t.content.appendChild(this.templateResult); + const t = document.createElement('template'); + + if(typeof this.templateResult === 'string') t.innerHTML = this.templateResult; + else if(this.templateResult instanceof HTMLElement) { + if(this.templateResult.parentNode) { + this.templateResult.parentNode.removeChild(this.templateResult); //swap to the new component } + t.appendChild(this.templateResult); } const fragment = t.content; @@ -357,6 +359,95 @@ export class DOMElement extends HTMLElement { } } + get props() { + return this.props; + } + + set props(newProps={}) { + this.setAttribute('props',newProps); + } + + get template() { + return this.template; + } + + set template(template) { + this.setAttribute('template',template); + } + + get render() { + return this.render; + } + + get delete() { + return this.delete; + } + + get state() { + return this.state; + } + + //past tense just so it can't conflict with onchange + get onchanged() { + return this.onchanged; + } + + set onchanged(onchanged) { + this.setAttribute('onchanged',onchanged); + } + + get styles() { + return this.styles + } + + set styles(templateStr) { + + this.styles = templateStr; + + if(this.querySelector('style')) { //get the top style + // if(!this.useShadow) { + // this.useShadow = true; + // this.render() + // } else + this.querySelector('style').innerHTML = templateStr; + + } else { + //this.useShadow = true; + this.render(); + } + } + + get renderonchanged() { + return this.renderonchanged; + } + + set renderonchanged(onchanged) { + this.setAttribute('renderonchanged',onchanged); + } + + get onresize() { + return this.props; + } + + set onresize(onresize) { + this.setAttribute('onresize',onresize); + } + + get ondelete() { + return this.props; + } + + set ondelete(ondelete) { + this.setAttribute('ondelete',ondelete); + } + + get oncreate() { + return this.oncreate; + } + + set oncreate(oncreate) { + this.setAttribute('oncreated',oncreate); + } } //extend the DOMElement class with an new name, this name determines the element name (always lower case in the html regardless of class name cases) diff --git a/src/loaders/html/html.loader.ts b/src/loaders/html/html.loader.ts index 9cc7fb3a..ece82843 100644 --- a/src/loaders/html/html.loader.ts +++ b/src/loaders/html/html.loader.ts @@ -7,10 +7,10 @@ export type HTMLNodeProperties = GraphNodeProperties & { __onremove?:(elm:HTMLElement) => void, __onrender?:(elm:HTMLElement) => void, tagName?:string, //can provide this instead of an element or html template string - parentNode?:string|HTMLElement, //can define a specific parentNode, else a parent graph node with an HTMLElement as __props will be selected, else graph.parentNode if defined, else document.body + parentNode?:string, //can define a specific parentNode, else a parent graph node with an HTMLElement as __props will be selected, else graph.parentNode if defined, else document.body style?:Partial, //supply an object with style properties for this element's inline styles - //applies to custom webcomponent only (wchtmlloader): - __template?:string|((...args:any[]) => string), + //applies to custom webcomponent only: + __template?:string, __renderonchanged?:(elm:HTMLElement) => void, useShadow?:boolean, __css?:string, //stylesheet template string for use with web components (just prepends a `; delete node.__css; + node.__template = ``; delete node.__css; } + + if (node.__template) { - - const registerElement = (node, tagNameOverride?:string) => { - if (isNativeClass(node)) node = new node(); - else if (typeof node === 'function' && !node.__node) node = node(); + if(typeof node.__renderonchanged === 'function') { + let renderonchanged = node.__renderonchanged; + node.__renderonchanged = (element:DOMElement) => { + renderonchanged.call((element as any).node, element); + } + } class CustomElement extends DOMElement { props = node.props; @@ -64,137 +76,57 @@ export const wchtmlloader = ( renderonchanged = node.__renderonchanged as any; } - if (tagNameOverride?.includes('-')) node.tagName = tagNameOverride - else if(node.__element) node.tagName = node.__element; - + if(node.__element) node.tagName = node.__element; if(!node.tagName) node.tagName = `element${Math.floor(Math.random()*1000000000000000)}-`; CustomElement.addElement(node.tagName); - } - - if ('__components' in node) { - if (Array.isArray(node.__components)) node.__components.forEach(c => registerElement(c)) - else Object.entries(node.__components).forEach(([k, c]) => registerElement(c, k.includes('-') ? k : undefined)) - } - - if ('__template' in node) { - - if(typeof node.__renderonchanged === 'function') { - let renderonchanged = node.__renderonchanged; - node.__renderonchanged = (element:DOMElement) => { - renderonchanged.call((element as any).node, element); - } - } - - registerElement(node); node.__props = document.createElement(node.tagName); - - let cpy = Object.assign({},node); - let keys = Object.getOwnPropertyNames(cpy); - for(const k of keys) { - if(k === 'style' && typeof node[k] === 'object') {Object.assign(node.__props.style,cpy[k]);} - else if (k === 'className') node.__props.setAttribute('class', cpy[k]); - else if (!k.includes('outer')) node.__props[k] = cpy[k]; - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(k === 'style' && typeof node.__attributes[k] === 'object') {Object.assign(node.__props.style,node.__attributes[k]);} - else if (k === 'className') node.__props.setAttribute('class', node.__attributes[k]); - else if (!k.includes('outer')) node.__props[k] = node.__attributes[k]; - } - } - node.__proxyObject(node.__props); - - //fix for event listeners - for(const k of keys) { - if(typeof cpy[k] === 'function') { - let fn = cpy[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - } - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(typeof cpy[k] === 'function') { - let fn = node.__attributes[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - } - } - } - /// + node.__props.node = node; + entries.forEach(([k,v]) => { + if(k === 'style' && typeof v === 'object') {Object.assign(node.__props.style, v);} // Ensure all style properties are set + // else node.__props[k] = v; + }) } else if(node.__props instanceof HTMLElement) { - let cpy = Object.assign({},node); - let keys = Object.getOwnPropertyNames(cpy); - - for(const k of keys) { - if(k === 'style' && typeof node[k] === 'object') {Object.assign(node.__props.style,cpy[k]);} - else if (k === 'className') node.__props.setAttribute('class', cpy[k]); - else if (!k.includes('outer')) node.__props[k] = cpy[k]; - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(k === 'style' && typeof node.__attributes[k] === 'object') {Object.assign(node.__props.style,node.__attributes[k]);} - else if (k === 'className') node.__props.setAttribute('class', cpy[k]); - else if (!k.includes('outer')) node.__props[k] = node.__attributes[k]; - } - } - - node.__proxyObject(node.__props); - - //fix for event listeners - for(const k of keys) { - if(typeof cpy[k] === 'function') { - let fn = cpy[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - node[k] = node.__props[k]; - } - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(typeof cpy[k] === 'function') { - let fn = node.__attributes[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - node[k] = node.__props[k]; - } - } - } - /// if(node.__onresize) window.addEventListener('resize', node.__onresize as EventListener); + } + + if(node.__attributes && node.__props instanceof HTMLElement) { + for(const k in node.__attributes) { + if(k === 'style' && typeof node.__attribute[k] === 'object') {Object.assign(node.__props.style,node.__attribute[k]);} + node.__props[k] = node.__attributes[k]; + } } if(node.__props instanceof HTMLElement) { node.__props.id = key; - (node.__props as any).node = node; - - node.__addOnconnected((n) => { - if(!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement) && n.__props.parentNode) (n.__props as HTMLElement).remove(); - if(properties.parentNode) { - if(typeof properties.parentNode === 'string' && document.getElementById(properties.parentNode)) - document.getElementById(properties.parentNode)?.appendChild(n.__props); - else if (properties.parentNode instanceof HTMLElement) properties.parentNode.appendChild(n.__props); - } else if(parent?.__props instanceof HTMLElement) { + + const root = node.__node + + root.addOnConnected((n) => { + if(n.__props.parentNode) (n.__props as HTMLElement).remove(); + if(n.parentNode) { + if(typeof n.parentNode === 'string' && document.getElementById(n.parentNode)) + document.getElementById(n.parentNode)?.appendChild(n.__props); + else if (n.parentNode instanceof HTMLElement) n.parentNode.appendChild(n.__props); + } else if(parent.__props instanceof HTMLElement) { parent.__props.appendChild(node.__props); - } else if (typeof graph.parentNode === 'string' && document.getElementById(properties.parentNode)) { - document.getElementById(properties.parentNode)?.appendChild(graph.__props); + } else if (typeof graph.parentNode === 'string' && document.getElementById(n.parentNode)) { + document.getElementById(n.parentNode)?.appendChild(graph.__props); } else if(graph.parentNode instanceof HTMLElement) { graph.parentNode.appendChild(node.__props); - } else if(!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement)) - document.body.appendChild(node.__props); + } else if(!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement)) document.body.appendChild(node.__props); //add slight delay for sizing etc to kick in correctly - if(node.__onrender && !(node.__props instanceof DOMElement) && !node.__template) setTimeout(()=>{node.__onrender(node.__props)},0.01); + if(node.__onrender && !node.__template) setTimeout(()=>{node.__onrender(node.__props)},0.01); }); - node.__addOndisconnected((n) => { + root.addOnDisconnected((n) => { (n.__props as HTMLElement).remove(); if(typeof n.__onremove === 'function') { diff --git a/src/loaders/index.ts b/src/loaders/index.ts index 16b4a0c3..8be5c579 100644 --- a/src/loaders/index.ts +++ b/src/loaders/index.ts @@ -5,11 +5,14 @@ import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; /** * setting nodeA.__node.backward:true propagates operator results to parent */ -export const backprop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { +export const backprop = ( node:GraphNode ) => { + const root = node.__node + const parent = (node.__parent) ? node.__parent.__node.ref : null; + if(node.__node.backward && parent instanceof GraphNode) { - graph.setListeners({ + root.listeners.set({ [parent.__node.tag]:{ [node.__node.tag]:parent } @@ -34,34 +37,30 @@ export const backprop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { * * */ -export const loop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph)=>{ +export const loop = ( node:GraphNode )=>{ - if( - node.__operator - //&& !node.__node.looperSet //not using this allows multiple loops to run, just set looping=false and wait for all to finish otherwise - ) { - let loopId = Math.random(); - if(!node.__node.loops) node.__node.loops = {}; + if(node.__operator && !node.__node.looperSet) { + node.__node.looperSet = true; if(typeof node.__node.delay === 'number') { let fn = node.__operator; - node.__setOperator((...args:any[]) => { + node.__operator = (...args:any[]) => { return new Promise((res,rej) => { - node.__node.loops[loopId] = setTimeout(async ()=>{ + setTimeout(async ()=>{ res(await fn(...args));},node.__node.delay); }); - }); + }; } else if (node.__node.frame === true) { let fn = node.__operator; - node.__setOperator((...args:any[]) => { + node.__operator = (...args:any[]) => { return new Promise((res,rej) => { - node.__node.loops[loopId] = requestAnimationFrame(async ()=>{res(await fn(...args));}); + requestAnimationFrame(async ()=>{res(await fn(...args));}); }); - }); + }; } if(typeof node.__node.repeat === 'number' || typeof node.__node.recursive === 'number') { let fn = node.__operator; - node.__setOperator(async (...args:any[]) => { + node.__operator = async (...args:any[]) => { let i = node.__node.repeat ? node.__node.repeat : node.__node.recursive; let result; let repeater = async (tick,...inp:any[]) => { @@ -81,44 +80,34 @@ export const loop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph)=>{ } await repeater(i,...args); return result; - }); + }; } if(node.__node.loop && typeof node.__node.loop === 'number') { - //node.__node.looperSet = true; + const root = node.__node + let onstart + let fn = node.__operator; - let time = node.__node.loop; - node.__setOperator((...args) => { + node.__operator = (...args) => { if(!('looping' in node.__node)) node.__node.looping = true; if(node.__node.looping) { - let last = performance.now(); fn(...args); - node.__node.loops[loopId] = setTimeout( - ()=>{ - let now = performance.now(); - let overshoot = (now - last) - node.__node.loop; - if(overshoot > 0) time = node.__node.loop - overshoot; - else time = node.__node.loop; - if(time <= 0) time = node.__node.loop; - node.__operator(...args); - // - }, - time - ); + setTimeout(()=>{node.__operator(...args)},node.__node.loop); } - }); - if(node.__node.looping) node.__operator(); + }; + + if(node.__node.looping) onstart = () => node.__operator(); let ondelete = (node) => { if(node.__node.looping) node.__node.looping = false; - if(node.__node.loops[loopId]) { - clearTimeout(node.__node.loops[loopId]); - cancelAnimationFrame(node.__node.loops[loopId]); - } } - node.__addOndisconnected(ondelete); + root.addOnConnected(() => { + if(onstart) onstart(); + }) + + root.addOnDisconnected(ondelete); } } @@ -133,30 +122,37 @@ export const loop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph)=>{ * or node.__animation = (...args) => {} * */ -export const animate = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { +export const animate = ( node:GraphNode ) => { if(node.__node.animate === true || node.__animation) { - let fn = node.__operator; + let fn = node.__operator; + + let onstart; + node.__operator = (...args) => { + if(!('animating' in node.__node)) node.__node.animating = true; + if(node.__node.animating) { + if(typeof node.__animation === 'function') node.__animation(...args); + else fn(...args); - node.__setOperator((...args) => { - if(!('animating' in node.__node)) node.__node.animating = true; - if(node.__node.animating) { - if(typeof node.__animation === 'function') node.__animation(...args); - else fn(...args); - node.__node.animationFrame = requestAnimationFrame(()=>{node.__operator(...args);}); + onstart = () => requestAnimationFrame(()=>{node.__operator(...args);}); + } } - }); - if(node.__node.animating || ((!('animating' in node.__node) || node.__node.animating) && node.__animation)) - setTimeout(()=>{ - node.__node.animationFrame = requestAnimationFrame(node.__operator) - },10); - + + if(node.__node.animating || ((!('animating' in node.__node) || node.__node.animating) && node.__animation)) { + onstart = () => setTimeout(()=>{requestAnimationFrame(node.__operator)},10); + } + + + const root = node.__node + root.addOnConnected(() => { + onstart(); + }) + let ondelete = (node) => { if(node.__node.animating) node.__node.animating = false; - if(node.__node.animationFrame) cancelAnimationFrame(node.__node.animationFrame); } - node.__addOndisconnected(ondelete); + root.addOnDisconnected(ondelete); } } @@ -168,14 +164,11 @@ export const animate = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { * * nodeA.__listeners['nodeB.x'] = { * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } + * branch:{if:Function|any, then:Function|any|GraphNode} * } * */ -export const branching = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { +export const branching = ( node:GraphNode ) => { if(typeof node.__branch === 'object' && node.__operator && !node.__branchApplied) { let fn = node.__operator; node.__branchApplied = true; @@ -235,7 +228,7 @@ export const branching = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, oncreate:any } * */ -export const triggerListenerOncreate = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { +export const triggerListenerOncreate = ( node:GraphNode ) => { if(node.__listeners) { for(const key in node.__listeners) { if(typeof node.__listeners[key] === 'object') { @@ -247,12 +240,12 @@ export const triggerListenerOncreate = (node:GraphNode,parent:GraphNode|Graph,gr } } -/** Bind listeners to a specific object instead of the node that owns it +/** Trigger listeners oncreate with specific arguments * * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } * */ -export const bindListener = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { +export const bindListener = ( node:GraphNode ) => { if(node.__listeners) { for(const key in node.__listeners) { if(typeof node.__listeners[key] === 'object') { @@ -270,7 +263,7 @@ export const bindListener = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, transform:(result)=>any } * */ -export const transformListenerResult = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { +export const transformListenerResult = ( node:GraphNode ) => { if(node.__listeners) { for(const key in node.__listeners) { if(typeof node.__listeners[key] === 'object') { @@ -288,14 +281,15 @@ export const transformListenerResult = (node:GraphNode,parent:GraphNode|Graph,gr } -export const substitute__operator = (node:GraphNode & GraphNodeProperties, parent:GraphNode|Graph,graph:Graph) => { +export const substitute__operator = ( node:GraphNode & GraphNodeProperties ) => { //console.log('route', r) + const graph = node.__node.graph if(node.post && !node.__operator) { - node.__setOperator(node.post); + node.__operator = node.post; } else if (!node.__operator && typeof node.get == 'function') { - node.__setOperator(node.get); + node.__operator = node.get; } if(!node.get && node.__operator) { - //node.get = node.__operator; + node.get = node.__operator; } if(node.aliases) { node.aliases.forEach((a) => { graph.set(a,node); @@ -303,7 +297,8 @@ export const substitute__operator = (node:GraphNode & GraphNodeProperties, paren graph.__node.nodes.delete(a); } - node.__addOndisconnected(ondelete); + const root = node.__node + root.addOnDisconnected(ondelete); }) } if(typeof graph.__node.roots?.[node.__node.tag] === 'object' && node.get) graph.__node.roots[node.__node.tag].get = node.get; diff --git a/src/loaders/methodstrings.ts b/src/loaders/methodstrings.ts deleted file mode 100644 index f96e7677..00000000 --- a/src/loaders/methodstrings.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {parseFunctionFromText} from '../services/utils' - -export function methodstrings (node) { - if(typeof node.__methods === 'object') { - for(const key in node.__methods) { - let fstr = node.__methods[key]; - let fn = typeof fstr === 'function' ? fstr : parseFunctionFromText(fstr); - if(key === '__operator') { - node.__setOperator(fn as any); - } - else { - node[key] = fn.bind(node); - } - } - } -} \ No newline at end of file diff --git a/src/services/Service.ts b/src/services/Service.ts index bd4d7462..dc85fd0f 100644 --- a/src/services/Service.ts +++ b/src/services/Service.ts @@ -23,16 +23,13 @@ export type ServiceMessage = { export type ServiceOptions = GraphOptions & { - services?:{[key:string]:Service|Function|{[key:string]:any}}, - restrict?:{[key:string]:boolean} //only allow the receive() (and on some services the remote subscribe() calls) to run specific nodes + services?:{[key:string]:Service|Function|{[key:string]:any}} } export class Service extends Graph { name = `service${Math.floor(Math.random()*1000000000000000)}`; - restrict?:{[key:string]:boolean}; - constructor(options?:ServiceOptions) { super({ //assign properties to the graph ...options, @@ -41,7 +38,6 @@ export class Service extends Graph { }); if(options?.services) this.addServices(options.services); - if(options?.restrict) this.restrict = options.restrict; this.load(this); } @@ -58,10 +54,7 @@ export class Service extends Graph { } else this.set(s+'.'+tag,n); }); - this.__node.nodes.forEach((n,k) => { - if(!(services[s] as Service).__node.nodes.get(k)) - (services[s] as Graph).__node.nodes.set(k,n) - }) + this.__node.nodes.forEach((n,k) => { if(!(services[s] as Service).__node.nodes.get(k)) (services[s] as Graph).__node.nodes.set(k,n) }) let set = this.set; @@ -69,7 +62,7 @@ export class Service extends Graph { (services[s] as Graph).set(tag,node); return set(tag,node); } - + let del = this.delete; this.delete = (tag:string) => { @@ -96,17 +89,10 @@ export class Service extends Graph { } if(src?.[m]) { if(typeof src[m] !== 'function') { - if(args) { - if(Array.isArray(args) && args.length === 1) src[m] = args[0]; - else src[m] = args; - return; //set value, don't echo - } //if args were passed set the value + if(args) src[m] = args; //if args were passed set the value return src[m]; //could just be a stored local variable we are returning like a string or object } - else { - if(Array.isArray(args)) return src[m](...args); - else return src[m](args); - } + else return src[m](args); }//these could be any function or property call else return this.handleServiceMessage({route,args,method}) //process normally if the method doesn't return @@ -114,7 +100,6 @@ export class Service extends Graph { handleServiceMessage(message:ServiceMessage) { let call; - //console.log(message); if(typeof message === 'object') { if(message.route) call = message.route; else if (message.node) call = message.node; } @@ -139,59 +124,51 @@ export class Service extends Graph { ...args:[ServiceMessage|any,...any[]]|any[] ) => { if(typeof args[0] === 'object') { - const message = args[0]; - if(message.method) { //run a route method directly, results not linked to graph - return this.handleMethod(message.route, message.method, message.args); - } else if(message.route) { - return this.handleServiceMessage(message); - } else if (message.node){ - return this.handleGraphNodeCall(message.node, message.args); + if(args[0].method) { //run a route method directly, results not linked to graph + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if(args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node){ + return this.handleGraphNodeCall(args[0].node, args[0].args); } else if(this.__node.keepState) { - if(message.route) - this.setState({[message.route]:message.args}); - if(message.node) - this.setState({[message.node]:message.args}); + if(args[0].route) + this.setState({[args[0].route]:args[0].args}); + if(args[0].node) + this.setState({[args[0].node]:args[0].args}); } - return undefined; - } else return undefined; + return args; + } else return args; } //process http requests, socket messages, webrtc, osc, etc. with this customizable callback. This default still works in some scenarios receive:(...args)=>any|void = ( ...args:[ServiceMessage|any,...any[]]|any[] //generalized args for customizing, it looks weird I know ) => { - if(args[0]) { - let message = args[0]; - if(typeof message === 'string') { - let substr = message.substring(0,8); - if(substr.includes('{') || substr.includes('[')) { - if(substr.includes('\\')) message = message.replace(/\\/g,""); //double jsonified string - if(message[0] === '"') { message = message.substring(1,message.length-1)}; - //console.log(message) - message = JSON.parse(message); //parse stringified args - } + if(args[0]) if(typeof args[0] === 'string') { + let substr = args[0].substring(0,8); + if(substr.includes('{') || substr.includes('[')) { + if(substr.includes('\\')) args[0] = args[0].replace(/\\/g,""); //double jsonified string + if(args[0][0] === '"') { args[0] = args[0].substring(1,args[0].length-1)}; + //console.log(args[0]) + args[0] = JSON.parse(args[0]); //parse stringified args } + } - if(typeof message === 'object') { - if(message.method) { //run a route method directly, results not linked to graph - if(this.restrict?.[message.route]) return undefined; - return this.handleMethod(message.route, message.method, message.args); - } else if(message.route) { - if(this.restrict?.[message.route]) return undefined; - return this.handleServiceMessage(message); - } else if (message.node){ - if(typeof message.node === 'string' && this.restrict?.[message.node]) return undefined; - return this.handleGraphNodeCall(message.node, message.args); - } else if(this.__node.keepState) { - if(message.route) - this.setState({[message.route]:message.args}); - if(message.node) - this.setState({[message.node]:message.args}); - } - return undefined; + if(typeof args[0] === 'object') { + if(args[0].method) { //run a route method directly, results not linked to graph + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if(args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node){ + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if(this.__node.keepState) { + if(args[0].route) + this.setState({[args[0].route]:args[0].args}); + if(args[0].node) + this.setState({[args[0].node]:args[0].args}); } - } - return undefined; + return args; + } else return args; }//these are fairly identical on the base template plus json parsing on the receive end //we may want to auto pipe outputs from a node through our frontend<-->backend service protocol @@ -252,14 +229,6 @@ export class Service extends Graph { this.transmit(...args); return args; } - log = (...args:any)=>{ - console.log(...args); - return true; - } - error = (...args:any) => { - console.error(...args); - return true; - } } @@ -270,8 +239,8 @@ export function isTypedArray(x:any) { //https://stackoverflow.com/a/40319428 export const recursivelyAssign = (target,obj) => { for(const key in obj) { - if(obj[key]?.constructor.name === 'Object' && !Array.isArray(obj[key])) { - if(target[key]?.constructor.name === 'Object' && !Array.isArray(target[key])) recursivelyAssign(target[key], obj[key]); + if(typeof obj[key] === 'object' && !Array.isArray(obj[key])) { + if(typeof target[key] === 'object' && !Array.isArray(target[key])) recursivelyAssign(target[key], obj[key]); else target[key] = recursivelyAssign({},obj[key]); } else target[key] = obj[key]; } diff --git a/src/services/cmd/CMD.node.ts b/src/services/cmd/CMD.node.ts index a9d4bf1b..71afc52c 100644 --- a/src/services/cmd/CMD.node.ts +++ b/src/services/cmd/CMD.node.ts @@ -27,7 +27,7 @@ export type CMDInfo = { request:(message:ServiceMessage|any,method?:string) => Promise, post:(route:string, args:any, method?:string) => boolean, run:(route:any, args?:any, method?:string) => Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean) => number, + subscribe:(route:any, callback?:((res:any)=>void)|string) => number, unsubscribe:(route:any, sub:number) => Promise } & CMDRoute @@ -152,8 +152,8 @@ export class CMDService extends Service { } - newprocess.subscribe = (route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean) => { - return this.subscribeToProcess(route, newprocess._id, callback, args, key, subInput); + newprocess.subscribe = (route:any, callback?:((res:any)=>void)|string) => { + return this.subscribeToProcess(route, newprocess._id, callback); } newprocess.unsubscribe = (route:any, sub:number) => { @@ -226,8 +226,7 @@ export class CMDService extends Service { return res; } - subscribeProcess(route:string, childprocess:ChildProcess|string, args?:any[], key?:string, subInput?:boolean) { - if(this.restrict?.[route]) return undefined; + subscribeProcess(route:string, childprocess:ChildProcess|string,key?:string, subInput?:boolean) { if(typeof childprocess === 'string' && this.processes[childprocess]) { childprocess = this.processes[childprocess].process; } @@ -240,10 +239,10 @@ export class CMDService extends Service { } else { (childprocess as ChildProcess).send(JSON.stringify({args:res, callbackId:route})); } - },args,key,subInput); + },key,subInput); } - subscribeToProcess(route:string, processId:string, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean) { + subscribeToProcess(route:string, processId:string, callback?:((res:any)=>void)|string, key?:string, subInput?:boolean) { if(typeof processId === 'string' && this.processes[processId]) { this.__node.state.subscribeEvent(processId, (res) => { if(res?.callbackId === route) { @@ -254,7 +253,7 @@ export class CMDService extends Service { else callback(res.args); } }); - return this.processes[processId].request(JSON.stringify({route:'subscribeSocket', args:[route,processId,args,key,subInput]})); + return this.processes[processId].request(JSON.stringify({route:'subscribeSocket', args:[route,processId,key,subInput]})); } } diff --git a/src/services/cmd/childprocess.js b/src/services/cmd/childprocess.js index 3f346950..8f19efe6 100644 --- a/src/services/cmd/childprocess.js +++ b/src/services/cmd/childprocess.js @@ -1,10 +1,10 @@ //stock child process that runs services import { CMDService } from "./CMD.node"; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; const service = new CMDService({ - routes:[remoteGraphRoutes] + routes:[unsafeRoutes] }); //now we can send/receive messages console.log("Child process listening...") \ No newline at end of file diff --git a/src/services/http/HTTP.browser.ts b/src/services/http/HTTP.browser.ts index 3c30c76d..e55e529e 100644 --- a/src/services/http/HTTP.browser.ts +++ b/src/services/http/HTTP.browser.ts @@ -87,7 +87,7 @@ export class HTTPfrontend extends Service { type:XMLHttpRequestResponseType='', mimeType?:string|undefined ) => { - if(typeof message === 'object' && !message.byteLength && (type === 'json' || type === 'text' || !type)) { + if(typeof message === 'object' && (type === 'json' || type === 'text' || !type)) { message = JSON.stringify(message); } @@ -118,7 +118,7 @@ export class HTTPfrontend extends Service { url:string|URL ) => { let obj = message; - if(typeof obj === 'object' && !obj.byteLength) { + if(typeof obj === 'object') { message = JSON.stringify(obj); } if(obj?.method?.toLowerCase() == 'get' || message?.toLowerCase() === 'get') return this.GET(url); diff --git a/src/services/http/HTTP.node.ts b/src/services/http/HTTP.node.ts index 210e579f..72d4b662 100644 --- a/src/services/http/HTTP.node.ts +++ b/src/services/http/HTTP.node.ts @@ -4,9 +4,7 @@ import * as https from 'https' import * as fs from 'fs' import * as path from 'path' import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -import { defaultManifest, defaultServiceWorker } from "./boilerplate/index"; -export * from './boilerplate/index' export type ServerProps = { host:string, @@ -18,23 +16,18 @@ export type ServerProps = { errpage?:string, pages?:{ [key:'all'|string]:string|{ //objects get loaded as nodes which you can modify props on - headers?:{[key:string]:any}, //page specific headers to assign on page response template?:string, onrequest?:GraphNode|string|((self:HTTPbackend, node:GraphNode, request:http.IncomingMessage, response:http.ServerResponse)=>void), //run a function or node? the template, request and response are passed as arguments, you can write custom node logic within this function to customize inputs etc. redirect?:string, // can redirect the url to call a different route instead, e.g. '/':{redirect:'home'} sets the route passed to the receiver as 'home' - inject?:{[key:string]:any}|any[]|string| ((...args:any)=>any) //append html + inject?:{[key:string]:{}|null}|string[]|string| ((...args:any)=>any) //append html } & GraphNodeProperties }, protocol?:'http'|'https', type?:'httpserver'|string, keepState?:boolean, //setState whenever a route is run? State will be available at the address (same key of the object storing it here) onopen?:(served:ServerInfo)=>void, //onopen callback - onerror?:(er:Error,served:ServerInfo)=>void, onclose?:(served:ServerInfo)=>void, //server close callback - onupgrade?:(request, socket, head, served:ServerInfo)=>void, - timeout?:number, //request timeout, default is 1 second _id?:string, - debug?:boolean, [key:string]:any } @@ -88,14 +81,16 @@ export class HTTPbackend extends Service { constructor( options?:ServiceOptions, - settings?:ServerProps + settings?:{ host?:string, port?:number, protocol?:'http'|'https', certpath?:string, keypath?:string } ) { super(options); this.load(this); //console.log(settings); if(settings) { - this.setupServer(settings); + if(settings.protocol === 'https') { + this.setupHTTPSserver( settings as any ) + } else this.setupHTTPserver( settings as any); } } @@ -106,7 +101,7 @@ export class HTTPbackend extends Service { ${protocol}://${host}:${port}/` ); } - + setupServer = ( options:ServerProps={ protocol:'http', @@ -121,30 +116,28 @@ export class HTTPbackend extends Service { if(options.pages) { for(const key in options.pages) { if (typeof options.pages[key] === 'string') { - this.addPage(`${options.port}/${key}`, options.pages[key] as string) - } else if (typeof options.pages[key] === 'object' || typeof options.pages[key] === 'function') { + this.addPage(`${options.port}/${key}`,options.pages[key] as string) + } else if (typeof options.pages[key] === 'object') { if((options.pages[key] as any).template) { (options.pages[key] as any).get = (options.pages[key] as any).template; } - let rt = `${options.port}/${key}`; - if(key !== '_all') this.load({[rt]:options.pages[key]}); + if(key !== '_all') this.load({[`${options.port}/${key}`]:options.pages[key]}); } } } - //create http or https server - this.setupHTTPserver(options, requestListener, onStarted); + if(options.protocol === 'https') { + return this.setupHTTPSserver(options as any, requestListener, onStarted); + } + else + return this.setupHTTPserver(options, requestListener, onStarted); } open = this.setupServer; - //Define the server via http or https + //insecure server setupHTTPserver = ( - options:(ServerProps & { - certpath?:string, - keypath?:string, - passphrase?:string - })={ + options:ServerProps={ host:'localhost' as string, port:8080 as number, startpage:'index.html', @@ -154,8 +147,9 @@ export class HTTPbackend extends Service { onStarted:()=>void = ()=>{this.onStarted('http',options.host,options.port)} ) => { - const host = options.host ? options.host : 'localhost'; - const port = options.port ? options.port : 8000; + const host = options.host; + const port = options.port; + options.protocol = 'http'; if(!host || !port) return; @@ -172,12 +166,7 @@ export class HTTPbackend extends Service { ...options } as ServerInfo - //default requestListener propagates to graphscript - if(!requestListener) - requestListener = ( - request:http.IncomingMessage, - response:http.ServerResponse - ) => { + if(!requestListener) requestListener = (request:http.IncomingMessage,response:http.ServerResponse) => { let received:any = { args:{request, response}, @@ -188,51 +177,34 @@ export class HTTPbackend extends Service { let url = (request as any).url.slice(1); if(!url) url = '/'; //console.log(options) - - if(options.debug) { - let time = getHoursAndMinutes(new Date()); - console.log( - time, ' | ', - 'From: ', request.socket?.remoteAddress, - 'For: ', request.url, ' | ', request.method - ); - } - if(options.pages) { - getPageOptions.call(this, url, received, options.pages, request, response, options.port); - } else received.route = url; - + if(typeof options.pages[url] === 'object') { + if((options.pages[url] as any).onrequest) { + if(typeof (options.pages[url] as any).onrequest === 'string') { + (options.pages[url] as any).onrequest = this.__node.nodes.get((url).onrequest); + } + if(typeof (options.pages[url] as any).onrequest === 'object') { + if((options.pages[url] as any).onrequest.__operator) { + ((options.pages[url] as any).onrequest as GraphNode).__operator(options.pages[url], request, response); + } + } else if(typeof (options.pages[url] as any).onrequest === 'function') { + (options.pages[url] as any).onrequest(this, this.__node.nodes.get(options.port + '/' + url), request, response); + } + } + if((options.pages[url] as any).redirect) { + url = (options.pages[url] as any).redirect; + received.redirect = url; + } + } + } + received.route = url; this.receive(received); } //default requestListener //var http = require('http'); - let server:http.Server|https.Server = undefined as any; - if(options.protocol === 'http') - server = http.createServer( + const server = http.createServer( requestListener ); - else { - let opts; - if(options.keypath && options.certpath) { - opts = { - key: fs.readFileSync(options.keypath), - cert: fs.readFileSync(options.certpath), - passphrase:options.passphrase - } - server = https.createServer( - opts, - requestListener - ) - } else - console.error('Error, key and/or cert .pem SSL files not provided. See OpenSSL certbot for more info on how to create free SSL certifications, or create your own self-signed one for local development.') - - - } - - if(!server) { - console.error("Server not successfully created."); - return undefined; - } served.server = server; served.terminate = () => { @@ -247,45 +219,135 @@ export class HTTPbackend extends Service { this.servers[address] = served; served._id = options._id ? options._id : address; - - //SITE AVAILABLE ON PORT: return new Promise((resolve,reject) => { - let resolved; - // server.on('connection',(socket) => { - // //DDOS protection? - // //Rate limiting? - // }); server.on('error',(err)=>{ - if(served.onerror) served.onerror(err, served); - else console.error('Server error:', err.toString()); - if(!resolved) reject(err); - }); - server.on('clientError',(err, socket:http.IncomingMessage["socket"]) =>{ - if(served.onerror) served.onerror(err, served); - else console.error(getHoursAndMinutes(new Date()), ' | Server clientError:', err.toString(), ' | From: ', socket.remoteAddress); - if(socket) socket.destroy(); - }); - server.on('tlsClientError',(err, socket:http.IncomingMessage["socket"]) =>{ - if(served.onerror) served.onerror(err, served); - else console.error(getHoursAndMinutes(new Date()), ' | Server tlsClientError: ', err.toString(), ' | From: ', socket.remoteAddress); - if(socket) socket.destroy(); - }); - server.on('upgrade',(request, socket, head) => { - if(served.onupgrade) served.onupgrade(request,socket,head,served); + console.error('Server error:', err.toString()); + reject(err); }); server.listen( - port, host, + port,host, ()=>{ onStarted(); if(served.onopen) served.onopen(served); - resolved = true; resolve(served); } ); }) as Promise ; } + //secure server + setupHTTPSserver = ( + options:ServerProps = { + host:'localhost' as string, + port:8080 as number, + startpage:'index.html', + certpath:'cert.pem' as string, + keypath:'key.pem' as string, + passphrase:'encryption' as string, + errpage:undefined as undefined|string + }, + requestListener?:http.RequestListener, + onStarted:()=>void = ()=>{this.onStarted('https',options.host,options.port)} + ) => { + + const host = options.host; + const port = options.port; + options.protocol = 'https'; + + if(!host || !port || !options.certpath || !options.keypath) return; + + if(this.servers[`${host}:${port}`]) this.terminate(this.servers[`${host}:${port}`]) + + var opts = { + key: fs.readFileSync(options.keypath), + cert: fs.readFileSync(options.certpath), + passphrase:options.passphrase + }; + + if(!('keepState' in options)) options.keepState = true; //default true + + const address = `${host}:${port}`; + + const served = { + server:undefined as any, + type:'httpserver', + address, + ...options + } as ServerInfo; + + //default requestListener + if(!requestListener) requestListener = (request:http.IncomingMessage,response:http.ServerResponse) => { + + let received:any = { + args:{request, response}, + method:request.method, + served + } + + let url = (request as any).url.slice(1); + if(!url) url = '/'; + if(options.pages) { + if(typeof options.pages[url] === 'object') { + if((options.pages[url] as any).redirect) { + url = (options.pages[url] as any).redirect; + received.redirect = url; + } + if((options.pages[url] as any).onrequest) { + if(typeof (options.pages[url] as any).onrequest === 'string') { + (options.pages[url] as any).onrequest = this.__node.nodes.get((options.pages[url] as any).onrequest); + } + if(typeof (options.pages[url] as any).onrequest === 'object') { + if((options.pages[url] as any).onrequest.__operator) { + ((options.pages[url] as any).onrequest as GraphNode).__operator(options.pages[url], request, response); + } + } else if(typeof (options.pages[url] as any).onrequest === 'function') { + (options.pages[url] as any).onrequest(this,options.pages[url], request, response); + } + } + } + } + received.route = url; + this.receive(received); + } //default requestListener + + + //var http = require('http'); + const server = https.createServer( + opts, + requestListener + ); + + served.server = server; + served.terminate = () => { + this.terminate(served); + } + served.service = this; + + // server.on('upgrade', (request, socket, head) => { + // this.onUpgrade(request, socket, head); + // }); + + this.servers[address] = served; + served._id = options._id ? options._id : address; + + //SITE AVAILABLE ON PORT: + return new Promise((resolve,reject) => { + server.on('error',(err)=>{ + console.error('Server error:', err.toString()); + reject(err); + }) + server.listen( + port,host, + ()=>{ + onStarted(); + if(served.onopen) served.onopen(served); + resolve(served); + } + ); + }) as Promise; + } + transmit = ( //generalized http request. The default will try to post back to the first server in the list message:any | ServiceMessage, options:string|{ @@ -305,7 +367,7 @@ export class HTTPbackend extends Service { ) => { let input = message; - if(typeof input === 'object' && !input.byteLength) input = JSON.stringify(input); + if(typeof input === 'object') input = JSON.stringify(input); if(typeof options === 'string' && message) return this.POST(options,message); else if(typeof options === 'string') return this.GET(options); @@ -348,8 +410,6 @@ export class HTTPbackend extends Service { let mimeType = 'text/plain'; - let head = {} as any; - if(typeof result === 'string') { let extname = path.extname(result); @@ -357,21 +417,17 @@ export class HTTPbackend extends Service { mimeType = this.mimeTypes[extname] || 'application/octet-stream'; result = fs.readFileSync(path.join(process.cwd(),result)); + if(mimeType === 'text/html' && (message.served?.pages?._all || message.served?.pages?.[message.route])) { - let { templateString, headers } = this.injectPageCode(result.toString(),message.route,message.served as any) as any; - result = templateString; - Object.assign(head, headers); + result = this.injectPageCode(result.toString(),message.route,message.served as any) as any; } } - else if(typeof result === 'string' && result.includes('<') && result.includes('>') && (result.indexOf('<') < result.indexOf('>'))) //probably an html template + if(typeof result === 'string' && result.includes('<') && result.includes('>') && (result.indexOf('<') < result.indexOf('>'))) //probably an html template { - head['Content-Type'] = 'text/html'; if(message?.served?.pages?._all || message?.served?.pages?.[message.route]) { - let { templateString, headers } = this.injectPageCode(result,message.route,message.served) as any; - result = templateString; - Object.assign(head, headers); + result = this.injectPageCode(result,message.route,message.served) as any; } - response.writeHead(200,head); + response.writeHead(200,{'Content-Type':'text/html'}); response.end(result,'utf-8'); return; } @@ -379,11 +435,9 @@ export class HTTPbackend extends Service { result = JSON.stringify(result); mimeType = 'application/json' } - head['Content-Type'] = mimeType; - response.writeHead(200,head); + + response.writeHead(200,{'Content-Type':mimeType}); response.end(result,'utf-8'); - } else { - try {response.destroy();} catch {} } } @@ -391,7 +445,8 @@ export class HTTPbackend extends Service { templateString:string, url:string, served:ServerInfo - ):{templateString:string,headers:{[key:string]:any}} => { + ) => { + if ((served?.pages?.[url] as any)?.inject) { //inject per url if(typeof (served as any).pages[url].inject === 'object') templateString = this.buildPage((served as any).pages[url].inject as any, templateString); @@ -408,16 +463,8 @@ export class HTTPbackend extends Service { else if (typeof (served as any).pages._all.inject === 'string' || typeof (served as any).pages._all.inject === 'number') templateString += (served as any).pages._all.inject; } - - let headers = {}; - if((served as any).pages._all.headers) - Object.assign(headers,(served as any).pages._all.headers); - - if((served as any).pages[url].headers) - Object.assign(headers,(served as any).pages[url].headers); - - return {templateString, headers}; + return templateString; } receive = ( //our fancy request response handler @@ -430,303 +477,236 @@ export class HTTPbackend extends Service { redirect?:string //if we redirected the route according to page options } ) => { - if(this.debug) console.log(message.args.request.method, message.args.request.url); + const request = message.args.request; + const response = message.args.response; + const method = message.method; + const served = message.served; + + if(this.debug) console.log(request.method, request.url); //console.log(request); //debug let result = new Promise((resolve,reject) => { - this.responsePromiseHandler(resolve, reject, message, message.args.request, message.args.response, message.method as string, message.served as ServerInfo); - }).catch((er)=>{ console.error("Request Error:", er); }); - return result; - } - - //internal - responseOnErrorPromiseHandler = (response:http.ServerResponse, reject, err) => { - if(!response.writableEnded || !response.destroyed ) { - response.statusCode = 400; - response.end(undefined,undefined as any); - reject(err); - } else { - try {response.destroy();} catch {} - reject(err); - } - } - - //internal - getFailedPromiseHandler = (resolve, reject, requestURL, message, response:http.ServerResponse, served) => { - if(response.writableEnded || response.destroyed) reject(requestURL); - if(requestURL == './' || requestURL == served?.startpage) { - let template = `

Brains@Play Server

`; //start page dummy - if(served?.pages?._all || served?.pages?.error) { - let {templateString, headers} = this.injectPageCode(template,message.route,served) as any; - template = templateString; - } - response.writeHead(200, { 'Content-Type': 'text/html' }); - response.end(template,'utf-8'); //write some boilerplate server page, we should make this an interactive debug page - resolve(template); - if(served?.keepState) this.setState({[served.address]:template}); - return; - } - else if(this.debug) console.log(`File ${requestURL} does not exist on path!`); - - response.writeHead(500); //set response headers - response.end(undefined,undefined as any); - reject(requestURL); - - //return; - } - - //internal - handleBufferedPostBodyPromiseHandler = (resolve, body, message, response:http.ServerResponse, served) => { - - body = Buffer.concat(body).toString(); //now it's a string - - if(typeof body === 'string') { - let substr = body.substring(0,8); - if(substr.includes('{') || substr.includes('[')) { - if(substr.includes('\\')) body = body.replace(/\\/g,""); - if(body[0] === '"') { body = body.substring(1,body.length-1)}; - body = JSON.parse(body); //parse stringified args, this is safer in a step - } - } - - let route,method,args; - - if(body?.route){ //if arguments were posted - route = body.route; - method = body.method; - args = body.args; - if(!route) { - if(typeof body.route === 'string') if(body.route.includes('/') && body.route.length > 1) body.route = body.route.split('/').pop(); - route = body.route; - } - } - if(!route) { //body post did not provide argument so use the request route - if (message?.route) { - let route = message.route; - method = message.method; - args = message.args; - if(!route) { - if(typeof message.route === 'string') - if(message.route.includes('/') && message.route.length > 1) - message.route = message.route.split('/').pop() as string; - - route = message.route; - } - } - } - let res:any = body; - if(route) { - - if(this.restrict?.[route]) { - try {response.destroy();} catch {} - resolve(res); - } else { - if(body.method) { - res = this.handleMethod(route, method, args); - } - else if (body.node) { - res = this.handleGraphNodeCall(body.node, body.args); - } - else res = this.handleServiceMessage({route, args:args, method:method}); - - if(res instanceof Promise) { - res.then((r) => { - this.withResult(response,r,message); - if(served?.keepState) this.setState({[served.address]:res}); - resolve(res); + response.on('error', (err) => { + if(!response.writableEnded || !response.destroyed ) { + response.statusCode = 400; + response.end(undefined,undefined as any,()=>{ + reject(err); }); - } else { - this.withResult(response,res,message); - if(served?.keepState) this.setState({[served.address]:res}); - resolve(res); } - } - } - else if(!response.writableEnded || !response.destroyed) { - response.statusCode = 200; - response.end(undefined,undefined as any); //posts etc. shouldn't return anything but a 200 usually - resolve(res); - } else { - try {response.destroy();} catch {} - resolve(res); //get requests resolve first and return otherwise this will resolve - } - - } - - //internal - onRequestFileReadPromiseHandler = (error, content, resolve, reject, requestURL, response:http.ServerResponse, message, served:ServerInfo) => { - if (error) { - if(error.code == 'ENOENT') { //page not found: 404 - if(served?.errpage) { - fs.readFile(served.errpage, (er, content) => { - response.writeHead(404, { 'Content-Type': 'text/html' }); //set response headers - - - //add hot reload if specified - // if(process.env.HOTRELOAD && requestURL.endsWith('.html') && cfg.hotreload) { - // content = addHotReloadClient(content,`${cfg.socket_protocol}://${cfg.host}:${cfg.port}/hotreload`); - // } - - if(served.pages?._all || served.pages?.error) { - let {templateString, headers} = this.injectPageCode(content.toString(),message.route,served) as any; - content = templateString; - } + }); - response.end(content, 'utf-8'); //set response content - reject(content); - //console.log(content); //debug - }); - } - else { - response.writeHead(404, { 'Content-Type': 'text/html' }); - let content = `

Error: ${error.code}

` - if(served?.pages?._all || served?.pages?.[message.route]) { - let {templateString, headers} = this.injectPageCode(content.toString(),message.route,served as any) as any; - content = templateString; + let getFailed = () => { + if(response.writableEnded || response.destroyed) reject(requestURL); + if(requestURL == './' || requestURL == served?.startpage) { + let template = `

Brains@Play Server

`; //start page dummy + if(served?.pages?._all || served?.pages?.error) { + template = this.injectPageCode(template,message.route,served) as any; } - response.end(content,'utf-8'); - reject(error.code); + response.writeHead(200, { 'Content-Type': 'text/html' }); + response.end(template,'utf-8',() => { + resolve(template); + }); //write some boilerplate server page, we should make this an interactive debug page + if(served?.keepState) this.setState({[served.address]:template}); //return; } - } - else { //other error + else if(this.debug) console.log(`File ${requestURL} does not exist on path!`); response.writeHead(500); //set response headers - response.end('Something went wrong: '+error.code+' ..\n','utf-8'); //set response content - reject(error.code); + response.end(undefined,undefined as any,()=>{ + reject(requestURL); + }); + //return; - - } - } - else { //file read successfully, serve the content back - - //set content type based on file path extension for the browser to read it properly - var extname = String(path.extname(requestURL)).toLowerCase(); - - var contentType = this.mimeTypes[extname] || 'application/octet-stream'; - - let head = { 'Content-Type': contentType }; - - if(contentType === 'text/html' && (served?.pages?._all || served?.pages?.[message.route])) { - let {templateString, headers} = this.injectPageCode(content.toString(),message.route, served as any) as any; - Object.assign(head, headers); - content = templateString; } - response.writeHead(200, head); //set response headers - response.end(content, 'utf-8'); //set response content - resolve(content); - - //console.log(content); //debug - //return; - } - } - - //internal - responsePromiseHandler = (resolve, reject, message, request:http.IncomingMessage, response:http.ServerResponse, method:string, served:ServerInfo) => { - - response.on('error', (err) => { - if(served.debug) { - let time = getHoursAndMinutes(new Date()); - console.error(time,'| Response Error: ', err, ' From: ', request.socket?.remoteAddress, ' For: ', request.url, ' | ', request.method); - } - this.responseOnErrorPromiseHandler(response, reject, err); - request.destroy(); - request.socket?.destroy(); - }); - - if(method === 'GET' || method === 'get') { - //process the request, in this case simply reading a file based on the request url - var requestURL = '.' + request.url; - if(request.url && this.restrict?.[request.url]) reject(request.url); - - if (requestURL == './' && served?.startpage) { //root should point to start page - requestURL = served.startpage; //point to the start page - } - - //lets remove ? mark url extensions for now - if(requestURL.includes('?')) requestURL = requestURL.substring(0,requestURL.indexOf('?')); - - if((request.url !== '/' || served?.startpage) && fs.existsSync(path.join(process.cwd(),requestURL))) { - if(response.writableEnded || response.destroyed) reject(requestURL); - else { + if(method === 'GET' || method === 'get') { + //process the request, in this case simply reading a file based on the request url + var requestURL = '.' + request.url; + + if (requestURL == './' && served?.startpage) { //root should point to start page + requestURL = served.startpage; //point to the start page + } + + if((request.url !== '/' || served?.startpage) && fs.existsSync(path.join(process.cwd(),requestURL))) { + + if(response.writableEnded || response.destroyed) reject(requestURL); //read the file on the server fs.readFile(path.join(process.cwd(),requestURL), (error, content) => { - this.onRequestFileReadPromiseHandler(error, content, resolve, reject, requestURL, response, message, served); + if (error) { + if(error.code == 'ENOENT') { //page not found: 404 + if(served?.errpage) { + fs.readFile(served.errpage, (er, content) => { + response.writeHead(404, { 'Content-Type': 'text/html' }); //set response headers + + + //add hot reload if specified + // if(process.env.HOTRELOAD && requestURL.endsWith('.html') && cfg.hotreload) { + // content = addHotReloadClient(content,`${cfg.socket_protocol}://${cfg.host}:${cfg.port}/hotreload`); + // } + + if(served.pages?._all || served.pages?.error) { + content = this.injectPageCode(content.toString(),message.route,served) as any; + } + + response.end(content, 'utf-8'); //set response content + reject(content); + //console.log(content); //debug + }); + } + else { + response.writeHead(404, { 'Content-Type': 'text/html' }); + let content = `

Error: ${error.code}

` + if(served?.pages?._all || served?.pages?.[message.route]) { + content = this.injectPageCode(content.toString(),message.route,served as any) as any; + } + response.end(content,'utf-8', () => { + reject(error.code); + }); + //return; + } + } + else { //other error + response.writeHead(500); //set response headers + response.end('Something went wrong: '+error.code+' ..\n','utf-8', () => { + reject(error.code); + }); //set response content + //return; + } + } + else { //file read successfully, serve the content back + + //set content type based on file path extension for the browser to read it properly + var extname = String(path.extname(requestURL)).toLowerCase(); + + var contentType = this.mimeTypes[extname] || 'application/octet-stream'; + + if(contentType === 'text/html' && (served?.pages?._all || served?.pages?.[message.route])) { + content = this.injectPageCode(content.toString(),message.route,served as any) as any; + } + + response.writeHead(200, { 'Content-Type': contentType }); //set response headers + response.end(content, 'utf-8', () => { + //console.log(response,content,contentType); + resolve(content); + }); //set response content + + //console.log(content); //debug + //return; + } }); - } - } else if (message.route) { - let route; - if(served) { - let rt = `${served.port}/${message.route}`; - if(this.__node.nodes.get(rt)) route = rt - } - if(!route && this.__node.nodes.get(message.route)) route = message.route; - - if(route) { - let res:any; - if(message.method) { - res = this.handleMethod(route, message.method, undefined); //these methods are being passed request/response in the data here, post methods will parse the command objects instead while this can be used to get html templates or play with req/res custom callbakcs + } else if (message.route) { + let route; + if(served) { + let rt = `${served.port}/${message.route}`; + if(this.__node.nodes.get(rt)) route = rt } - else if (message.node) { - res = this.handleGraphNodeCall(message.node, undefined); + if(!route && this.__node.nodes.get(message.route)) route = message.route; + + if(route) { + let res:any; + if(message.method) { + res = this.handleMethod(route, message.method, undefined); //these methods are being passed request/response in the data here, post methods will parse the command objects instead while this can be used to get html templates or play with req/res custom callbakcs + } + else if (message.node) { + res = this.handleGraphNodeCall(message.node, undefined); + } + else res = this.handleServiceMessage({route,args:undefined,method:message.method}); + + if(res instanceof Promise) res.then((r) => { + if(served?.keepState) this.setState({[served.address]:res}); + this.withResult(response,r,message); + resolve(res); + + //return; + }) + else if(res) { + if(served?.keepState) this.setState({[served.address]:res}); + this.withResult(response,res,message); + resolve(res); + // return; + } //else we can move on to check the get post } - else res = this.handleServiceMessage({route,args:undefined,method:message.method}); - - if(res instanceof Promise) res.then((r) => { - if(served?.keepState) this.setState({[served.address]:res}); - this.withResult(response,r,message); - resolve(res); - - //return; - }) - else if(res) { - if(served?.keepState) this.setState({[served.address]:res}); - this.withResult(response,res,message); - resolve(res); - // return; - } //else we can move on to check the get post - } - else if (message.redirect) { - response.writeHead(301, {'Location':message.redirect}); - response.end(); - resolve(true); - } - else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served); - } else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served); - } else { - //get post/put/etc body if any - let requestBody; - let timedOut = true; - let timeout; - - request.on('data',(chunk)=>{ //https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ - if(!requestBody) requestBody = [] as any[]; - requestBody.push(chunk); - if(timedOut) { - timedOut = false; - if(timeout) clearTimeout(timeout); - } - }).on('end',() => { - this.handleBufferedPostBodyPromiseHandler(resolve,requestBody,message,response,served); - }); + else if (message.redirect) { + response.writeHead(301, {'Location':message.redirect}); + response.end(); + resolve(true); + } + else getFailed(); + } else getFailed(); + } else { + //get post/put/etc body if any + let body:any = []; + request.on('data',(chunk)=>{ //https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ + body.push(chunk); + }).on('end',() => { + body = Buffer.concat(body).toString(); //now it's a string + + if(typeof body === 'string') { + let substr = body.substring(0,8); + if(substr.includes('{') || substr.includes('[')) { + if(substr.includes('\\')) body = body.replace(/\\/g,""); + if(body[0] === '"') { body = body.substring(1,body.length-1)}; + body = JSON.parse(body); //parse stringified args, this is safer in a step + } + } + + let route,method,args; + if(body?.route){ //if arguments were posted + route = this.__node.roots?.[body.route]; + method = body.method; + args = body.args; + if(!route) { + if(typeof body.route === 'string') if(body.route.includes('/') && body.route.length > 1) body.route = body.route.split('/').pop(); + route = this.__node.roots?.[body.route]; + } + } + if(!route) { //body post did not provide argument so use the request route + if (message?.route) { + let route = this.__node.roots?.[message.route]; + method = message.method; + args = message.args; + if(!route) { + if(typeof message.route === 'string') if(message.route.includes('/') && message.route.length > 1) message.route = message.route.split('/').pop() as string; + route = this.__node.roots?.[message.route]; + } + } + } + let res:any = body; + if(route) { + if(body.method) { + res = this.handleMethod(route, method, args); + } + else if (body.node) { + res = this.handleGraphNodeCall(body.node, body.args); + } + else res = this.handleServiceMessage({route, args:args, method:method}); - //timeout posts/puts/etc if no body - timeout = setTimeout(() => { - if(timedOut) { - let errMessage = new Error(`Request timed out from | ${request.socket?.remoteAddress} | For: ${request.url} | ${request.method}`); - request.destroy(errMessage); - served.server.emit('clientError', errMessage, request.socket); - if(served.debug) { - console.error(errMessage); + if(res instanceof Promise) { + res.then((r) => { + this.withResult(response,r,message); + if(served?.keepState) this.setState({[served.address]:res}); + resolve(res); + }); + } else { + this.withResult(response,res,message); + if(served?.keepState) this.setState({[served.address]:res}); + resolve(res); + } } - reject(errMessage); - } - }, served.timeout ? served.timeout : 1000); //most likely an unhandled method + else if(!response.writableEnded || !response.destroyed) { + response.statusCode = 200; + response.end(undefined,undefined as any, () => { + resolve(res); + }); //posts etc. shouldn't return anything but a 200 usually + } else resolve(res); //get requests resolve first and return otherwise this will resolve + }); - } + } + + }).catch((er)=>{ console.error("Request Error:", er); }); + return result; } request = ( @@ -850,9 +830,7 @@ export class HTTPbackend extends Service { }).on('end',() => { resolve(Buffer.concat(chunks)); }).on('error',(er)=>{ - let errMessage = new Error(`Request timed out from | ${req.socket?.remoteAddress} | For: ${req.url} | ${req.method}`); - req.destroy(errMessage); - reject(errMessage); + reject(er); }) }); } @@ -901,29 +879,25 @@ export class HTTPbackend extends Service { buildPage = (pageStructure:{[key:string]:{}|null|any} | string[] | string | ((...args:any)=>any), baseTemplate:string) => { //construct a page from available components, child component templates will be inserted before the last '<' symbol or at end of the previous string depending let result = ``; if(baseTemplate) result += baseTemplate; let appendTemplate = (obj:{[key:string]:{}|null|any}|string[],r:string|any, res:string) => { - if(!Array.isArray(obj[r]) && typeof obj[r] === 'object') { + if(typeof obj[r] === 'object') { for(const key in obj) { - appendTemplate(obj, key, res); //recursive append - } - } else if(this.__node.nodes.get(r)?.get) { - let toAdd = this.__node.nodes.get(r)?.get; - if(typeof toAdd === 'function') { - if(Array.isArray(obj[r])) { - toAdd = toAdd(...obj[r]); - } - else toAdd = toAdd(obj[r]); + appendTemplate(obj,key,res); //recursive append } + } else if(this.__node.roots?.[r]?.get) { + let toAdd = this.__node.roots[r]?.get; + if(typeof toAdd === 'function') toAdd = toAdd(obj[r]); if(typeof toAdd === 'string') { let lastDiv = res.lastIndexOf('<'); if(lastDiv > 0) { let end = res.substring(lastDiv) res = res.substring(0,lastDiv) + toAdd + end; - } else res += toAdd; + } res += toAdd; } - } else if (this.__node.nodes.get(r)?.__operator) { + } else if (typeof this.__node.roots?.[r] === 'function' || this.__node.roots?.[r]?.__operator) { let routeresult; - if(this.__node.nodes.get(r)?.__operator) routeresult = this.__node.nodes.get(r).__operator(obj[r]); + if(this.__node.roots[r]?.__operator) routeresult = this.__node.roots[r].__operator(obj[r]); + else routeresult = (this.__node.roots[r] as Function)(obj[r]); //template function, pass props if(typeof routeresult === 'string') { let lastDiv = res.lastIndexOf('<'); if(lastDiv > 0) { @@ -933,106 +907,32 @@ export class HTTPbackend extends Service { else res += routeresult; //console.log(lastDiv, res, routeresult) } - } else if (typeof this.__node.nodes.get(r) === 'string') res += this.__node.nodes.get(r); + } else if (typeof this.__node.roots?.[r] === 'string') res += this.__node.roots[r]; return res; } if(Array.isArray(pageStructure)) { pageStructure.forEach((r)=>{ - result = appendTemplate(pageStructure, r, result); + result = appendTemplate(pageStructure,r,result); }) } else if (typeof pageStructure === 'object') { for(const r in pageStructure) { - result = appendTemplate(pageStructure, r, result); + result = appendTemplate(pageStructure,r,result); } } else if (typeof pageStructure === 'string') result += pageStructure; else if (typeof pageStructure === 'function') result += pageStructure(); + //console.log(result,pageStructure,this.routes) return result; } - hotreload = (socketURL:string|URL=`http://localhost:8080/wss`, esbuild_cssFileName?:string) => { + hotreload = (socketURL:string|URL=`http://localhost:8080/wss`) => { + if(socketURL instanceof URL) socketURL = socketURL.toString(); - - const HotReloadClient = (socketUrl, esbuild_cssFileName) => { + const HotReloadClient = (url=`http://localhost:8080/wss`) => { //hot reload code injected from backend //const socketUrl = `ws://${cfg.host}:${cfg.hotreload}`; - let socket = new WebSocket(socketUrl); - - - function reloadLink(file?) { - - let split = file.includes('/') ? file.split('/') : file.split('\\'); - let fname = split[split.length-1]; - - var links = document.getElementsByTagName("link") as any as HTMLLinkElement; - for (var cl in links) - { - var link = links[cl]; - - if(!file || link.href?.includes(fname)) { - let href = link.getAttribute('href') - .split('?')[0]; - - let newHref = href += ""; - - link.setAttribute('href', newHref); - - } - } - } - - - function reloadAsset(file, reloadscripts?, isJs?) { //reloads src tag elements - let split = file.includes('/') ? file.split('/') : file.split('\\'); - let fname = split[split.length-1]; - let elements = document.querySelectorAll('[src]') as any as HTMLScriptElement[]; - let found = false; - for(const s of elements) { - if(s.src.includes(fname)) { //esbuild compiles entire file so just reload app - if(s.tagName === 'SCRIPT' && !reloadscripts) {//&& s.tagName === 'SCRIPT' - window.location.reload(); - return; - } else { - let placeholder = document.createElement('object'); - s.insertAdjacentElement('afterend', placeholder); - s.remove(); - let elm = s.cloneNode(true) as HTMLElement; - placeholder.insertAdjacentElement('beforebegin',elm); - placeholder.remove(); - found = true; - } - } - } - if(!found) window.location.reload(); - } - - - socket.addEventListener('message',(ev) => { - let message = ev.data; - - if(typeof message === 'string' && message.startsWith('{')) { - message = JSON.parse(message); - } - if(message.file) { - let f = message.file; - let rs = message.reloadscripts; - if(f.endsWith('html') || f.endsWith('xml') || f.endsWith('wasm')) { //could add other formats - window.location.reload(); - } else if(f.endsWith('css')) { - if(!esbuild_cssFileName.endsWith('css')) esbuild_cssFileName += '.css'; - reloadLink(esbuild_cssFileName); //reload all css since esbuild typically bundles one file same name as the dist file - } else if (f.endsWith('js') || f.endsWith('ts') || f.endsWith('jsx') || f.endsWith('tsx') || f.endsWith('vue')) { //IDK what other third party formats would be nice to haves - reloadAsset(f, rs); - } else { - //could be an href or src - reloadLink(f); - reloadAsset(f); - } - } - }); - - + let socket = new WebSocket(url); socket.addEventListener('close',()=>{ // Then the server has been turned off, // either due to file-change-triggered reboot, @@ -1051,7 +951,7 @@ export class HTTPbackend extends Service { console.error("Could not reconnect to dev server."); return; } - socket = new WebSocket(socketUrl); + socket = new WebSocket(url); socket.onerror = (er) => { console.error(`Hot reload port disconnected, will reload on reconnected. Attempt ${attempts} of ${maxAttempts}`); } @@ -1069,200 +969,9 @@ export class HTTPbackend extends Service { return ` - `; - } - - pwa = (pwaName = "PWA", cacheExpirationDays=4/24, serviceWorkerUrl="service-worker.js") => { - - //check for serviceWorkerUrl, if none install the default template - if(!fs.existsSync(serviceWorkerUrl)) { - fs.writeFileSync(path.join(process.cwd(),serviceWorkerUrl), defaultServiceWorker(cacheExpirationDays)); - } - if(!fs.existsSync('manifest.webmanifest')) { - fs.writeFileSync(path.join(process.cwd(),'/manifest.webmanifest'), defaultManifest(pwaName)); - } - - function ServiceWorkerInstaller(serviceWorkerUrl) { - // Check that service workers are supported - - if(!Array.from(document.head.querySelectorAll('link')).find((elm:HTMLLinkElement) => { - if(elm.href.includes('manifest')) return true; - })) { - document.head.insertAdjacentHTML('beforeend',``) - } - - const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.1/8 is considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) - ); - - function registerSW() { - navigator.serviceWorker - .register(serviceWorkerUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated pre-cached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all tabs for this page are closed.' - ); - - } else { - // At this point, everything has been pre-cached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); - } - - if ("serviceWorker" in navigator) addEventListener('load', () => { - if(isLocalhost) { - // Add some additional logging to localhost, pointing developers to the - - // Check if the service worker can be found. If it can't reload the page. - fetch(serviceWorkerUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerSW(); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); - - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log('This web app is being served cache-first by a service worker.'); - }); - } - else { - registerSW(); - } - }); - } - - return ` - - `; + ` } -} - - - -function getPageOptions(url, received, pages, request, response, port) { - let pageOptions = pages[url]; - let key = url; - //check alternative page definition keys - if(!pageOptions) { - let url2 = '/'+url; // e.g. '/home' - pageOptions = pages[url2]; - key = url2; - if(!pageOptions && !path.extname(url)) { - let split = url.split('/'); - key = split[0]+'/*'; - if(pages[key]) { // e.g. /* or home/* - pageOptions = pages[key]; - received.route = key; - request.url = key; - } else { - // e.g. /home with /* specified, or /home/* etc. - let spl = url2.split('/'); //split the modified string so the beginning is a blank string - spl[spl.length-1] = ''; //replace with empty string e.g. /home -> ['',''] - key = spl.join('/')+'*'; //now merge url - if(pages[key]) { - pageOptions = pages[key]; - received.route = key; - request.url = key; - } - } - } else { - received.route = url2; - request.url = url2; - - } - } else { - received.route = url; - request.url = url; - } - if(typeof pageOptions === 'object') { - if((pageOptions as any).redirect) { - url = (pageOptions as any).redirect; - received.redirect = url; - received.route = url; - } - if((pageOptions as any).onrequest) { - if(typeof (pageOptions as any).onrequest === 'string') { - (pageOptions as any).onrequest = this.__node.nodes.get((pageOptions as any).onrequest); - } - if(typeof (pageOptions as any).onrequest === 'object') { - if((pageOptions as any).onrequest.__operator) { - ((pageOptions as any).onrequest as GraphNode).__operator(pageOptions, request, response); - } - } else if(typeof (pageOptions as any).onrequest === 'function') { - (pageOptions as any).onrequest( - this, - this.__node.nodes.get(`${port}/${key}`), - request, - response - ); - } - } - } - - return pageOptions; -} - - - - -function getHoursAndMinutes(date) { - let hours = date.getHours(); - let minutes = date.getMinutes(); - - // Convert the hours and minutes to two digits - hours = hours < 10 ? '0' + hours : hours; - minutes = minutes < 10 ? '0' + minutes : minutes; - - return `${hours}:${minutes}`; -} +} \ No newline at end of file diff --git a/src/services/http/boilerplate/index.ts b/src/services/http/boilerplate/index.ts index 40fd5c34..14dc6f16 100644 --- a/src/services/http/boilerplate/index.ts +++ b/src/services/http/boilerplate/index.ts @@ -26,108 +26,3 @@ export function scriptBoilerPlate(scripts:string|string[]) { } - -export const defaultServiceWorker = function (cacheExpirationDays=4/24) { //service-worker.js template for PWA - return `//https://github.com/ibrahima92/pwa-with-vanilla-js - -//https://github.com/ibrahima92/pwa-with-vanilla-js -let cacheName = 'pwa-assets'; -const assets = [ - "/", - "/index.html", - "/dist/index.css", //alt default paths - "/dist/index.js", - '/favicon.ico' -]; - -let cacheExpiration = 1000 * 60 * //seconds - 60 * //minutes - 24 * //hours - ${cacheExpirationDays}; //days - -let isValid = function (response) { - if (!response) return false; - var fetched = response.headers.get('sw-fetched-on'); - if (fetched && (!navigator.onLine || (parseFloat(fetched) + (cacheExpiration)) > new Date().getTime())) - return true; - return false; -}; - -self.addEventListener("install", installEvent => { - installEvent.waitUntil( - caches.open(cacheName).then(cache => { - cache.addAll(assets); - }) - ); -}); - -self.addEventListener("fetch", fetchEvent => { //https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/ - fetchEvent.respondWith( - caches.match(fetchEvent.request).then(function (response) { - - // If there's a cached API and it's still valid, use it - if (isValid(response)) { - return response; - } - - // Otherwise, make a fresh API call - if(response && !assets.includes(fetchEvent.request.url)) return response; - // Otherwise, make a fresh API call - else return fetch(fetchEvent.request).then(function (response) { - - // Cache for offline access - if(assets.includes(fetchEvent.request.url)){ - var copy = response.clone(); - fetchEvent.waitUntil(caches.open(cacheName).then(function (cache) { - var headers = new Headers(copy.headers); - headers.append('sw-fetched-on', new Date().getTime()); - return copy.blob().then(function (body) { - return cache.put(fetchEvent.request, new Response(body, { - status: copy.status ? copy.status : 200, - statusText: copy.statusText, - headers: headers - })); - }); - })); - } - - // Return the requested file - return response; - - }) - // .catch(function (error) { - // return caches.match(request).then(function (response) { //fallback to offline cache - // return response || caches.match('/offline.json'); //todo: figure out what is supposed to go in offline.json (https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/) - // }); - // }); - })); -}); - -`; -} - -//todo: make this even more customizable, just being lazy for now -export const defaultManifest = (pwaName = "PWA") => { - return `{ - "short_name": "${pwaName}", - "name": "${pwaName}", - "start_url": "/", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "description": "${pwaName} Test", - "lang": "en-US", - "permissions": [ - "storage" - ], - "icons":[{ - "src": "./assets/logo196.png", - "sizes": "196x196" - }, - { - "src": "./assets/logo512.png", - "sizes": "512x512" - }] -}` //images are REQUIRED for PWA to work -} - diff --git a/src/services/http/boilerplate/pwa/README.md b/src/services/http/boilerplate/pwa/README.md deleted file mode 100644 index febdc916..00000000 --- a/src/services/http/boilerplate/pwa/README.md +++ /dev/null @@ -1,26 +0,0 @@ -## [Instructions](https://dev.to/digitalplayer1125/custom-service-worker-in-any-app-with-esbuild-3020) - - -### Compile & inject: - -Copy manifest.webmanifest to main folder of your app and customize. - -Code to paste or inject into html pages (our server does this if you specify the service-worker path in the server_settings.js file): -```html - - - - - - - -``` \ No newline at end of file diff --git a/src/services/http/boilerplate/pwa/manifest.webmanifest b/src/services/http/boilerplate/pwa/manifest.webmanifest deleted file mode 100644 index 0111fba1..00000000 --- a/src/services/http/boilerplate/pwa/manifest.webmanifest +++ /dev/null @@ -1,22 +0,0 @@ -{ - "short_name": "PWA", - "name": "PWA", - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "description": "PWA Test", - "lang": "en-US", - "permissions": [ - "storage" - ], - "icons":[{ - "src": "./assets/logo196.png", - "sizes": "196x196" - }, - { - "src": "./assets/logo512.png", - "sizes": "512x512" - } - ] - } \ No newline at end of file diff --git a/src/services/http/boilerplate/pwa/service-worker-complex.js b/src/services/http/boilerplate/pwa/service-worker-complex.js deleted file mode 100644 index 4e841407..00000000 --- a/src/services/http/boilerplate/pwa/service-worker-complex.js +++ /dev/null @@ -1,120 +0,0 @@ -// This optional code is used to register a service worker. -// register() is not called by default. - -// This lets the app load faster on subsequent visits in production, and gives -// it offline capabilities. However, it also means that developers (and users) -// will only see deployed updates on subsequent visits to a page, after all the -// existing tabs open on the page have been closed, since previously cached -// resources are updated in the background. - -const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.1/8 is considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) -); - -export function register(config) { - if ('serviceWorker' in navigator) { - window.addEventListener('load', () => { - const swUrl = "service-worker.js"; - - if (isLocalhost) { - // This is running on localhost. Let's check if a service worker still exists or not. - checkValidServiceWorker(swUrl, config); - - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log('This web app is being served cache-first by a service worker.'); - }); - } else { - // Is not localhost. Just register service worker - registerValidSW(swUrl, config); - } - }); - } -} - -function registerValidSW(swUrl, config) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated pre-cached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all ' + - 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' - ); - - // Execute callback - if (config && config.onUpdate) { - config.onUpdate(registration); - } - } else { - // At this point, everything has been pre-cached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - - // Execute callback - if (config && config.onSuccess) { - config.onSuccess(registration); - } - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); -} - -function checkValidServiceWorker(swUrl, config) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); -} - -export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { - registration.unregister(); - }); - } -} diff --git a/src/services/http/boilerplate/pwa/service-worker.js b/src/services/http/boilerplate/pwa/service-worker.js deleted file mode 100644 index 5aad496f..00000000 --- a/src/services/http/boilerplate/pwa/service-worker.js +++ /dev/null @@ -1,81 +0,0 @@ - -//https://github.com/ibrahima92/pwa-with-vanilla-js -const version = '1.0'; // Increment this version to update all caches -const cacheNamePrefix = 'pwa-assets-'; -const cacheName = `${cacheNamePrefix}${version}`; -const assets = [ - "/", - "/index.html", - "/dist/index.css", //alt default paths - "/dist/index.js", - '/favicon.ico' -]; - -let cacheExpiration = 1000 * 60 * //seconds - 60 * //minutes - 24 * //hours - (4/24); //days (4 hours in this case) - -// Function to check if a cache name represents an expired cache -let isValidCacheName = function(cacheName) { - const cacheTimestamp = parseInt(cacheName.split('-').pop()); - const currentTime = new Date().getTime(); - return currentTime < cacheTimestamp + cacheExpiration; -}; - -self.addEventListener('fetch', event => { - event.respondWith( - caches.match(event.request).then(cachedResponse => { - - // Check if online; if not, return cached response immediately - if (!navigator.onLine) { - return cachedResponse; - } - - // Serve from cache if valid, otherwise fetch from network - return caches.keys().then(cacheNames => { - const relevantCacheName = cacheNames.find(name => name.startsWith(cacheNamePrefix)); - if (relevantCacheName && isValidCacheName(relevantCacheName)) { - return cachedResponse || fetchAndUpdateCache(event.request, relevantCacheName); - } else { - return fetchAndUpdateCache(event.request, cacheName); - } - }); - }) - ); -}); - -function fetchAndUpdateCache(request, cacheName) { - return fetch(request).then(response => { - // Only cache GET requests to whitelisted assets - if (request.method === 'GET' && assets.includes(new URL(request.url).pathname)) { - const responseToCache = response.clone(); - caches.open(cacheName).then(cache => { - cache.put(request, responseToCache); - }); - } - return response; - }).catch(() => { - // Attempt to serve from cache if the network request fails - return caches.match(request); - }); -} - -self.addEventListener('activate', event => { - event.waitUntil( - caches.keys().then(cacheNames => { - return Promise.all( - cacheNames.filter(name => name.startsWith(cacheNamePrefix) && !isValidCacheName(name)) - .map(invalidCacheName => caches.delete(invalidCacheName)) - ); - }).then(() => self.clients.claim()) - ); -}); - -self.addEventListener('install', event => { - event.waitUntil( - caches.open(cacheName) - .then(cache => cache.addAll(assets)) - .then(() => self.skipWaiting()) - ); -}); diff --git a/src/services/remote/remote.routes.ts b/src/services/remote/remote.routes.ts deleted file mode 100644 index e7f98bc7..00000000 --- a/src/services/remote/remote.routes.ts +++ /dev/null @@ -1,427 +0,0 @@ -import { getFnParamNames, getFunctionHead, parseFunctionFromText, recursivelyStringifyFunctions, stringifyWithCircularRefs, stringifyWithFunctionsAndCircularRefs } from "../utils" -import { Graph, GraphNodeProperties, Listener } from "../../core/Graph" -import { methodstrings } from "../../loaders/methodstrings"; -import { recursivelyAssign } from "../Service"; - -export const nodeTemplates = {}; - -//Contains evals and other things you probably don't want wide open on an API, for running graphs over remote contexts -export const remoteGraphRoutes = { - - transferNode: ( - properties:Function|(GraphNodeProperties & { __methods?:{[key:string]:Function|string} })|string, - connection:any | Worker | WebSocket, //put any info connection template in with - name?:string - ) => { - let str; - if(typeof properties === 'object') { - if(!properties.__node) { properties.__node = {}; } - if(name) properties.__node.tag = name; - - for(const key in properties) { - if(typeof properties[key] === 'function') { - if(!properties.__methods) properties.__methods = {}; - properties.__methods[key] = properties[key].toString(); - } - } - - str = recursivelyStringifyFunctions(properties); - - } else if (typeof properties === 'function') str = properties.toString(); - else if (typeof properties === 'string') str = properties; - if(str) { - - if((connection as any).run) - return (connection as any).run('setNode',[str]); - else if ((connection as Worker).postMessage) { - (connection as Worker).postMessage({route:'setNode', args:str},undefined); - return new Promise ((r) => r(name)); - } else if ((connection as WebSocket).send) { - (connection as WebSocket).send(JSON.stringify({route:'setNode', args:str})); - return new Promise ((r) => r(name)); - } - } - - }, - - setNode:function ( - properties:string|((...args:[])=>any)|(GraphNodeProperties & { __methods?:{[key:string]:Function|string} }), name?:string - ) { - //console.log('setting node', properties); - if(typeof properties === 'object') { - if(properties.__methods) { //stringified methods - if(!this.__node.graph.__node.loaders.methodstrings) { - this.__node.graph.__node.loaders.methodstrings = methodstrings; - } - } - } - if(typeof properties === 'string') { - let f = parseFunctionFromText(properties); - if(typeof f === 'function') properties = {__operator:f, __node:{tag:name ? name : f.name}}; - else { - f = JSON.parse(properties); - if(typeof f === 'object') properties = f; - } - } - if(typeof properties === 'object' || typeof properties === 'function') { - let template = {} as GraphNodeProperties; - if(typeof properties === 'object') Object.assign(template,properties); - else template.__operator = properties; - let node = this.__node.graph.add(template); - if(node) { - nodeTemplates[node.__node.tag] = template; //can just instantiate this again later - return node.__node?.tag; - } else return false; - } else return false; - }, - - makeNodeTransferrable:function ( - properties:GraphNodeProperties, - name?:string - ) { - if(!properties.__node) { properties.__node = {}; } - if(name) properties.__node.tag = name; - - for(const key in properties) { - if(typeof properties[key] === 'function') { - if(!properties.__methods) properties.__methods = {}; - properties.__methods[key] = properties[key].toString(); - } - } - - const str = recursivelyStringifyFunctions(properties); - - return str; - }, - - - getListenerJSON: function () { //reproducible json prototype, apply as __listeners in graph.load({__listeners:{...}}) - const triggers = this.__node.state.triggers; - let result = {} as any; - for(const key in triggers) { - triggers[key].forEach((trigger) => { - let t = trigger as any as Listener; - if(!result[t.target]) result[t.target] = {}; - let l = t.source + (t.key ? '.' + t.key : ''); - result[t.target][l] = { - __callback:t.__callback - } - if(t.__args) result[t.target][l].__args = t.__args; - if(t.subInput) result[t.target][l].subInput = t.subInput; - - }) - } - return result; - }, - - makeRootTransferrable: function () { - let roots = {}; - for(const r in this.__node.graph.__node.roots) { - let properties = this.__node.graph.__node.roots[r]; - if(typeof properties === 'function') { - roots[r] = properties.toString(); - } else if (typeof properties !== 'object') { - roots[r] = properties; - } else { - roots[r] = {}; - let keys = Object.getOwnPropertyNames(properties).filter((v) => !objProps.includes(v)); - //console.log([...keys]); - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter((v) => !objProps.includes(v)); - keys.push(...nonArrowFunctions); //this is weird but it works - for(const key of keys) { - if(typeof properties[key] === 'function') { - roots[r][key] = properties[key].toString(); - } else if(typeof properties[key] === 'object') - roots[r][key] = stringifyWithFunctionsAndCircularRefs(properties[key]); - else roots[r][key] = properties[key]; - } - } - } - - return roots; - }, - - setTemplate:function( - properties:string|((...args:[])=>any)|(GraphNodeProperties & { __methods?:{[key:string]:Function|string} }), - name?:string - ) { - if(typeof properties === 'object') { - if(properties.__methods) { //stringified methods - if(!this.__node.graph.__node.loaders.methodstrings) { - this.__node.graph.__node.loaders.methodstrings = methodstrings; - } - } - } - if(typeof properties === 'string') { - let f = parseFunctionFromText(properties); - if(typeof f === 'function') { - if(!name) name = f.name; - properties = {__operator:f, __node:{tag:name}}; - } - else { - f = JSON.parse(properties); - if(typeof f === 'object') { - properties = f; - if(!name && f.__node?.tag) name = f.__node.tag; - } - } - } - if(!name) name = `node${Math.floor(Math.random()*1000000000000000)}` - if(typeof properties === 'object' || typeof properties === 'function') { - nodeTemplates[name] = properties; - return name; - } else return false; - }, - - loadFromTemplate:function( - templateName:string, - name?:string, - properties?:{[key:string]:any} - ) { - if(nodeTemplates[templateName]) { - let cpy = recursivelyAssign({},nodeTemplates[templateName]); - if(name) { - if(!cpy.__node) cpy.__node = {}; - cpy.__node.tag = name; - } - if(properties) Object.assign(cpy,properties); - let node = this.__node.graph.add(cpy); - return node.__node.tag; - } - }, - - setMethod:function( - nodeTag:string, - fn:string|((...args:[])=>any), - methodKey?:string - ){ //set a method on a route - //console.log(fn, fnName) - if(typeof fn === 'string') { - let f = parseFunctionFromText(fn); - if(typeof f === 'function') fn = f; - } - //console.log(fn); - if(!methodKey && typeof fn === 'function') methodKey = fn.name; - if(this.__node.graph.get(nodeTag)) { - this.__node.graph.get(nodeTag)[methodKey] = fn; //overwrite method - } - else (this.__node.graph as Graph).add({__node:{tag:methodKey,[methodKey]:fn}}); - //console.log(this) - return true; - }, - - assignNode:function(nodeTag:string,source:{[key:string]:any}) { //set values on a node - //console.log(fn, fnName) - if(this.__node.graph.get(nodeTag) && typeof source === 'object') { - Object.assign(this.__node.graph.get(nodeTag),source); - } - }, - - getNodeProperties:function(nodeTag:string) { - let node = this.__node.graph.get(nodeTag); - if(node) { - let properties = Object.getOwnPropertyNames(node); - let result = {}; - for(const key of properties) { - if(typeof node[key] === 'function') { - let str = node[key].toString() as string; - let isNative = str.indexOf('[native code]') > -1; - result[key] = { type:'function', args:getFnParamNames(node[key]), native:isNative} - } - else result[key] = typeof node[key]; - } - return result; - } return undefined; - }, - - proxyRemoteNode : function ( - name:string, - connection:any, //put any info connection template in with a .run function, does not work with base workers/sockets etc as it relies on our promise system - ):Promise { - - return new Promise((res,rej) => { - connection.run('getNodeProperties',name).then((props:any)=>{ - let proxy = {}; - if(typeof props === 'object') { - for(const key in props) { - if(props[key]?.type === 'function') { - if(props[key].native || props[key].args) { - proxy[key] = (...args:any[]) => { - return new Promise((r) => { - connection.run( - name, - args, - key - ).then(r); - }); - } - } - //else if(props[key].args) { //not easy to set arguments from remote, anonymous bound functions are unparseable - // let scope = { - // connection - // } as any; - // proxy[key] = new Function( - // ...props[key].args,//...args:any[]) => { //no way to transfer args to this function? - // `return new Promise((r) => { - // this.connection.run( - // ${name}, - // [${props[key].args.join(',')}], - // ${key} - // ).then(r); - // });` - // ).bind(scope); //will show up as "bound anonymous" but the arguments are parseable - // //console.log(getFunctionHead(proxy[key].toString()).split('(')[1].split(')')[0]); - //} - else { - proxy[key] = () => { - return new Promise((r) => { - connection.run( - name, - undefined, - key - ).then(r); - }); - } - } - } else { - Object.defineProperty( - proxy, - key, - { - get:()=>{ - return new Promise((r)=>{ - connection.run( - name, - undefined, - key - ).then((r)) - }); - }, - set:(value) => { - connection.post( - name, - value, - key - ) - }, - configurable:true, - enumerable:true - } - ) - } - } - } - - res(proxy); - - }); - }); - }, - - transferClass:( - classObj:any, - connection:any | Worker | WebSocket, - className?:string - )=>{ //send a class over a remote service - if(typeof classObj === 'object') { - let str = classObj.toString();//needs to be a class prototype - let message = {route:'receiveClass',args:[str,className]}; - if((connection as any).run) - return (connection as any).run('receiveClass',[str,className]); - else if ((connection as Worker).postMessage) { - (connection as Worker).postMessage({route:'receiveClass', args:[str,className]},undefined); - return new Promise ((r) => r(name)); - } else if ((connection as WebSocket).send) { - (connection as WebSocket).send(JSON.stringify({route:'receiveClass', args:[str,className]})); - return new Promise ((r) => r(name)); - } - return message; - } - return false; - }, - - receiveClass:function(stringified:string, className?:string){ //eval a class string and set it as a key on the local graph by class name, so this.__node.graph.method exists - if(typeof stringified === 'string') { - //console.log(stringified) - if(stringified.indexOf('class') === 0) { - let cls = (0,eval)('('+stringified+')'); - let name = className; - - if(!name) - name = cls.name; //get classname - this.__node.graph[name] = cls; - - return true; - } - } - return false; - }, - - //requires unsafe service to load on other end - transferFunction: (fn:Function, connection:any | Worker | WebSocket, fnName?:string) => { - if(!fnName) fnName = fn.name; - let str = fn.toString();//needs to be a class prototype - let message = {route:'setNode',args:[str,fnName]}; - if((connection as any).run) - return (connection as any).run('setNode',[str,fnName]); - else if ((connection as Worker).postMessage) { - (connection as Worker).postMessage({route:'setNode', args:[str,fnName]},undefined); - return new Promise ((r) => r(fnName)); - } else if ((connection as WebSocket).send) { - (connection as WebSocket).send(JSON.stringify({route:'setNode', args:[str,fnName]})); - return new Promise ((r) => r(fnName)); - } - return message; - }, - - setGlobal:(key:string, value:any) => { //set a value on the globalThis scope - globalThis[key] = value; - return true; - }, - - assignGlobalObject:(target:string, source:{[key:string]:any}) => { //assign a value on an object on the globalThis scope - if(!globalThis[target]) return false; - if(typeof source === 'object') Object.assign(globalThis[target],source); - return true; - }, - - setValue:function(key:string, value:any) { //set a value on the graph scope - this.__node.graph[key] = value; - return true; - }, - - assignObject:function(target:string, source:{[key:string]:any}){ //assign a value on an object on the globalThis scope - if(!this.__node.graph[target]) return false; - if(typeof source === 'object') Object.assign( this.__node.graph[target],source); - return true; - }, - - setGlobalFunction:(fn:any, fnName?:string) => { //set a value on the globalThis scope - if(typeof fn === 'string') fn = parseFunctionFromText(fn); - //console.log(fn); - if(typeof fn === 'function') { - if(!fnName) fnName = fn.name; - globalThis[fnName] = fn; - //console.log(this) - return true; - } - return false; - }, - - setGraphFunction:function(fn:any, fnName?:string){ //set a value on the graph scope - if(typeof fn === 'string') fn = parseFunctionFromText(fn); - //console.log(fn); - if(typeof fn === 'function') { - if(!fnName) fnName = fn.name; - this.__node.graph[fnName] = fn; - //console.log(this) - return true; - } - return false; - } - -} - -let objProps = Object.getOwnPropertyNames(Object.getPrototypeOf({})); - -//console.log(objProps); \ No newline at end of file diff --git a/src/services/router/Router.ts b/src/services/router/Router.ts index 5f112e49..862fca7a 100644 --- a/src/services/router/Router.ts +++ b/src/services/router/Router.ts @@ -18,38 +18,17 @@ Frontend 1 Frontend 2 */ -//TODO: -//Make this simpler or maybe rethink some of the base organization in the Service to accomodate more of this level of functionality. - - export type User = { //users have macros to call grouped connections generically, based on what's available _id:string, - - //work with available connections, you can set the preferred order (e.g. sse, websockets, http) send:(...args:any[])=>any, request:(...args:any[])=>Promise|Promise[]|undefined, post:(...args:any[])=>void, run:(...args:any[])=>Promise|Promise[]|undefined, subscribe:(...args:any[])=>Promise|Promise[]|undefined, unsubscribe:(...args:any[])=>Promise|Promise[]|undefined, - - //can work with all of the connections associated with a user if you use the Router's connection management system - sendAll?:(...args:any[])=>any, - requestAll?:(...args:any[])=>Promise|undefined, - postAll?:(...args:any[])=>void, - runAll?:(...args:any[])=>Promise|undefined, - subscribeAll?:(...args:any[])=>Promise|undefined, - unsubscribeAll?:(...args:any[])=>Promise|undefined, - terminate:(...args:any[]) => boolean, - - //specific to a service connection if we wrap a sub-service connection instead of going thru Router - onmessage?:(...args:any[])=>void, - onerror?:(...args:any[])=>void, - //You can set a new onclose function specific to router scope - onclose?:((user:User)=>void)|((...args:any[])=>void), - - [key:string]:any //w/e else, it's just a data structure for general use with some methods + onclose?:(user:User)=>void, + [key:string]:any } @@ -94,7 +73,6 @@ export type RouterOptions = { }, //configure new connections after adding the relevant services? } //can be a service constructor } - timeout?:number, //timeout for user connections order?:string[], [key:string]:any } & ServiceOptions @@ -104,7 +82,7 @@ export class Router extends Service { name = 'router' //we need to store connection settings and available endpoints - connections:{ //this is a flattened reference with ALL active connections from each respective service + connections:{ [key:string]:ConnectionInfo //the services/graphs/nodes and connections by which to send on, these will be the corresponding info objects and the create/terminate functions for the appropriate services }={} @@ -124,8 +102,6 @@ export class Router extends Service { users:{[key:string]:User} = {}; //jsonifiable information - userTimeout = 10000; - order:string[]; //execute connections in preferred order constructor(options?:RouterOptions){ @@ -133,7 +109,6 @@ export class Router extends Service { this.load(this); if(options) { if(options.order) this.order = options.order; - if(options.timeout) this.userTimeout = options.timeout; if(options.graph) { for(const key in options.graph) { @@ -191,16 +166,11 @@ export class Router extends Service { }, //configure new connections after adding the relevant services? receiving?:boolean //is this the receiving router? ) => { - - let user:User if(!info._id) { info._id = `user${Math.floor(Math.random()*1000000000000000)}`; - } - if(this.users[info._id]) { - user = this.users[info._id]; //existing user - } else { - user = Object.assign({}, info) as any;//Profile(info._id,info) as User; } + + let user:User = Object.assign({},info) as any;//Profile(info._id,info) as User; if(connections){ for(const key in connections) { @@ -210,7 +180,7 @@ export class Router extends Service { let start = performance.now(); let checker = () => { if(!(connections[key] as any).connection._id) { - if(performance.now() - start > this.userTimeout) { + if(performance.now() - start > 3000) { delete connections[key]; rej(false); } else { @@ -235,9 +205,6 @@ export class Router extends Service { connections[key] = this.addConnection(connections[key], user._id) as any; } } - - - if(config) { for(const c in config) { this.openConnection( @@ -249,106 +216,50 @@ export class Router extends Service { } } + let send = (message:any, ...a:any[]) => { + let connection = this.getConnection(user._id, 'send'); + if(connection?.send) return connection.send(message, ...a); + } - if(!this.users[info._id]) { - let send = (message:any, ...a:any[]) => { - let connection = this.getConnection(user._id, 'send'); - if(connection?.send) return connection.send(message, ...a); - } - - let sendAll = (message:any, ...a:any[]) => { - let connections = this.getConnections(user._id, 'send'); - for(const key in connections) - if(connections[key]?.send) return connections[key].send(message, ...a); - } - - let request = (message:any, method?:any, ...a:any[]) => { - let connection = this.getConnection(user._id, 'request'); - if(connection?.request) return connection.request(message, method, ...a); - } - - let requestAll = (message:any, method?:any, ...a:any[]) => { - let connections = this.getConnections(user._id, 'request'); - let results = []; - for(const key in connections) - if(connections[key]?.request) results.push(connections[key].request(message, method, ...a)); - return Promise.all(results); - } - - let post = (route:any, args?:any, method?:string, ...a:any[]) => { - let connection = this.getConnection(user._id, 'post'); - if(connection?.post) return connection.post(route, args, method, ...a); - } - - let postAll = (route:any, args?:any, method?:string, ...a:any[]) => { - let connections = this.getConnections(user._id, 'post'); - for(const key in connections) - if(connections[key]?.post) connections[key].post(route, args, method, ...a); - } - - let run = (route:any, args?:any, method?:string, ...a:any[]) => { - let connection = this.getConnection(user._id, 'run'); - if(connection?.run) return connection.run(route, args, method, ...a); - } + let request = (message:any, method?:any, ...a:any[]) => { + let connection = this.getConnection(user._id, 'request'); + if(connection?.request) return connection.request(message, method, ...a); + } - let runAll = (route:any, args?:any, method?:string, ...a:any[]) => { - let connections = this.getConnections(user._id, 'run'); - let results = []; - for(const key in connections) - if(connections[key]?.run) results.push(connections[key].run(route, args, method, ...a)); - return Promise.all(results); - } + let post = (route:any, args?:any, method?:string, ...a:any[]) => { + let connection = this.getConnection(user._id, 'post'); + if(connection?.post) return connection.post(route, args, method, ...a); + } - let subscribe = (route:any, callback?:((res:any)=>void)|string, ...a:any[]) => { - let connection = this.getConnection(user._id, 'subscribe'); - if(connection?.subscribe) return connection.subscribe(route, callback, ...a); - } + let run = (route:any, args?:any, method?:string, ...a:any[]) => { + let connection = this.getConnection(user._id, 'run'); + if(connection?.run) return connection.run(route, args, method, ...a); + } - let subscribeAll = (route:any, callback?:((res:any)=>void)|string, ...a:any[]) => { - let connections = this.getConnections(user._id, 'subscribe'); - let results = []; - for(const key in connections) - if(connections[key]?.post) results.push(connections[key].subscribe(route, callback, ...a)); - return Promise.all(results) as Promise; - } + let subscribe = (route:any, callback?:((res:any)=>void)|string,...a:any[]) => { + let connection = this.getConnection(user._id, 'subscribe'); + if(connection?.subscribe) return connection.subscribe(route, callback, ...a); + } - let unsubscribe = (route:any, sub:number, ...a:any[]) => { - let connection = this.getConnection(user._id, 'unsubscribe'); - if(connection?.unsubscribe) return connection.unsubscribe(route, sub, ...a); - } + let unsubscribe = (route:any, sub:number, ...a:any[]) => { + let connection = this.getConnection(user._id, 'unsubscribe'); + if(connection?.unsubscribe) return connection.unsubscribe(route, sub, ...a); + } - let unsubscribeAll = (route:any, subs?:{[key:string]:number}, ...a:any[]) => { - let connections = this.getConnections(user._id, 'unsubscribe'); - let results = []; - for(const key in connections) - if(connections[key]?.post && subs[key]) results.push(connections[key].unsubscribe(route, subs[key], ...a)); - return Promise.all(results) as Promise; - } + let terminate = () => { + return this.removeUser(user) + } - let terminate = () => { - return this.removeUser(user) - } + user.send = send; + user.request = request; + user.post = post; + user.run = run; + user.subscribe = subscribe; + user.unsubscribe = unsubscribe; + user.terminate = terminate; + //these are macros to get available connections - user.send = send; - user.request = request; - user.post = post; - user.run = run; - user.subscribe = subscribe; - user.unsubscribe = unsubscribe; - user.terminate = terminate; - - user.sendAll = sendAll; - user.requestAll = requestAll; - user.postAll = postAll; - user.runAll = runAll; - user.subscribeAll = subscribeAll; - user.unsubscribeAll = unsubscribeAll; - user.terminateAll = terminate; - //these are macros to get available connections - - - this.users[user._id] = user; - } + this.users[user._id] = user; if(connections && !receiving) { let connectionIds = {}; @@ -392,25 +303,10 @@ export class Router extends Service { } //pick the preferred connection by service name if passing a source, or pick the connection by id if not a source - getConnection = (sourceId:string, hasMethod?:string, connectionId?:string):User|ConnectionInfo|undefined => { - - if(this.connections[sourceId]) { - return this.connections[sourceId]; //regardless of method, as this is a direct connection reference - } - else if(this.sources[sourceId]) { + getConnection = (sourceId:string, hasMethod?:string):ConnectionInfo|undefined => { + if(this.sources[sourceId]) { //console.log(this.sources[sourceId]); - if(hasMethod?.includes('All')) return this.users[sourceId]; - - if(connectionId) { - if(hasMethod) { - if(this.sources[sourceId][connectionId]?.[hasMethod]) - return this.sources[sourceId][connectionId]; - } - else if(this.sources[sourceId][connectionId]) - return this.sources[sourceId][connectionId]; - else return undefined; - } - else if (this.order) { + if (this.order) { for(let i = 0; i < this.order.length; i++) { let k = this.order[i]; for(const key in this.sources[sourceId as string]) { @@ -423,22 +319,14 @@ export class Router extends Service { continue; } } - if(hasMethod) { - if(this.sources[sourceId as string][key][hasMethod]) - return this.sources[sourceId as string][key]; - } - else return this.sources[sourceId as string][key]; + return this.sources[sourceId as string][key]; } } else if (this.sources[sourceId as string][key].service === k) { if(this.sources[sourceId as string][key].connectionType && (this.sources[sourceId as string][key].service as any)?.name) { if(!this.serviceConnections[(this.sources[sourceId as string][key] as any).service.name]) this.removeConnection(this.sources[sourceId as string][key]); //some auto cleanup continue; } - if(hasMethod) { - if(this.sources[sourceId as string][key][hasMethod]) - return this.sources[sourceId as string][key]; - } - else return this.sources[sourceId as string][key]; + return this.sources[sourceId as string][key]; } } } @@ -453,9 +341,8 @@ export class Router extends Service { continue; } } - if(hasMethod) { - if(this.sources[sourceId as string][k][hasMethod]) - return this.sources[sourceId as string][k]; + if(hasMethod && this.sources[sourceId as string][k][hasMethod]) { + return this.sources[sourceId as string][k]; } else { return this.sources[sourceId as string][k]; @@ -463,7 +350,7 @@ export class Router extends Service { } } - } else if (this.order && !this.connections[sourceId]) { + } else if (this.order) { for(let i = 0; i < this.order.length; i++) { let k = this.order[i]; if(this.sources[k]?.[sourceId]) { @@ -473,8 +360,7 @@ export class Router extends Service { continue; } } - if(hasMethod) { - if(this.sources[k][sourceId][hasMethod]) + if(hasMethod && this.sources[k][sourceId as string]?.[hasMethod]) { return this.sources[k][sourceId as string]; } else { @@ -484,6 +370,9 @@ export class Router extends Service { } } + if(typeof sourceId === 'string' && this.connections[sourceId] && this.connections[sourceId].send) { + return this.connections[sourceId]; //regardless of method, as this is a direct connection reference + } } @@ -500,113 +389,59 @@ export class Router extends Service { if(typeof this.sources[sourceId][key][k] === 'object') { let pass = true; if(hasMethod && !this.sources[sourceId][key][k][hasMethod]) pass = false; - if(props) { - for(const p in props) { - if(typeof this.sources[sourceId][key][k][p] === 'object' && typeof props[p] === 'object') { - //check one level down - for(const pp in props[p]) { - if(props[p][pp] !== this.sources[sourceId][key][k][p][pp]) { - pass = false; - break; - } + for(const p in props) { + if(typeof this.sources[sourceId][key][k][p] === 'object' && typeof props[p] === 'object') { + //check one level down + for(const pp in props[p]) { + if(props[p][pp] !== this.sources[sourceId][key][k][p][pp]) { + pass = false; + break; } } - else if(this.sources[sourceId][key][k][p] !== props[p]) { - pass = false; - } else { - pass = false; - break; - } + } + else if(this.sources[sourceId][key][k][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; } } if(pass) { found[this.sources[sourceId][key][k]._id] = this.sources[sourceId][key][k]; - } + } } } } else { let pass = true; if(hasMethod && !this.sources[sourceId][key][hasMethod]) pass = false; - if(props) { - for(const p in props) { - if(typeof this.sources[sourceId][key][p] === 'object' && typeof props[p] === 'object') { - //check one level down - for(const pp in props[p]) { - if(props[p][pp] !== this.sources[sourceId][key][p][pp]) { - pass = false; - break; - } + for(const p in props) { + if(typeof this.sources[sourceId][key][p] === 'object' && typeof props[p] === 'object') { + //check one level down + for(const pp in props[p]) { + if(props[p][pp] !== this.sources[sourceId][key][p][pp]) { + pass = false; + break; } } - else if(this.sources[sourceId][key][p] !== props[p]) { - pass = false; - } else { - pass = false; - break; - } + } + else if(this.sources[sourceId][key][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; } } if(pass) { - found[this.sources[sourceId][key]._id] = this.sources[sourceId][key]; + if(this.getConnection(this.sources[sourceId][key] as any, hasMethod)) + found[this.sources[sourceId][key]._id] = this.sources[sourceId][key]; } } } } - return found; - } - } - - - //e.g. from a user endpoint, run 'runConnection' on another user Id to interact with them - runConnection = async ( - userId:string, - method:'run'|'post'|'subscribe'|'unsubscribe'|'terminate'|'send'|'request'| - 'runAll'|'postAll'|'subscribeAll'|'unsubscribeAll'|'sendAll'|'requestAll', - args:any[], - connectionId?:string - ) => { - let sendTo; - if(method.indexOf('All') > -1) { - sendTo = this.users[userId]; - } else { - sendTo = this.getConnection(userId, method, connectionId); - } - if(sendTo) { - let res = (sendTo[method] as Function)(...args); - res = await res; - return res; - } - } - - subscribeThroughConnection = ( - route:string, //the route on the endpoint we want to subscribe to outputs from - remoteRelay:string|ConnectionInfo, //the endpoint/user Id linking a router we are trying to relay messages through - remoteEndpoint:string, //the endpoint/user on the other router that we want to subscribe to through the router - callback:string|((res:any)=>void), - ...args:any[] - ) => { - if(typeof remoteRelay === 'string') { - remoteRelay = this.getConnection(remoteRelay, 'run') as ConnectionInfo; } - - if(typeof remoteRelay === 'object') - return new Promise((res,rej) => { - (remoteRelay as any).run('routeConnections',[route,remoteEndpoint,(remoteRelay as any)._id,...args]).then((sub) => { - this.__node.state.subscribeEvent(remoteEndpoint, (res) => { - if(res?.callbackId === route) { - if(!callback) this.setState({[remoteEndpoint]:res.args}); - else if(typeof callback === 'string') { //just set state - this.setState({[callback]:res.args}); - } - else callback(res.args); - } - }); - res(sub); - }).catch(rej); - }); } - addConnection = (options:ConnectionProps|ConnectionInfo|string,source?:string, autoRemove=true) => { + addConnection = (options:ConnectionProps|ConnectionInfo|string,source?:string) => { let settings:ConnectionInfo = {} as any; if(typeof options === 'string') { if (this.connections[options]) { @@ -627,7 +462,7 @@ export class Router extends Service { if(typeof options === 'string' && this.__node.nodes.get(options)) options = {connection:this.__node.nodes.get(options)}; } if(!options || typeof options === 'string') return undefined; - + if(source) settings.source = source; if(options.connection instanceof GraphNode) { @@ -684,10 +519,10 @@ export class Router extends Service { } settings.run = settings.post as any; settings.subscribe = async (callback:((res:any)=>void)) => { - return node.__subscribe(callback) as number; + return node.__node.listeners.subscribe(callback) as number; }; settings.unsubscribe = async (sub:number) => { - return node.__unsubscribe(sub) as boolean; + return node.__node.listeners.unsubscribe(sub) as boolean; } settings.terminate = () => { node.__node.graph.remove(node); @@ -695,7 +530,8 @@ export class Router extends Service { } settings.onclose = options.onclose; if(settings.onclose) { - node.__addOndisconnected((n:GraphNode) => { if(settings.onclose) settings.onclose(settings,n); }) + const root = node.__node + root.addOnDisconnected((n:GraphNode) => { if(settings.onclose) settings.onclose(settings,n); }) } } else if (options.connection instanceof Graph) { if(options.connection.__node.nodes.get('open')) @@ -780,7 +616,6 @@ export class Router extends Service { } if(typeof c !== 'object') return undefined; settings._id = c._id; - settings.connection = options.connection as any; settings.send = c.send; settings.request = c.request; settings.run = c.run; @@ -796,12 +631,7 @@ export class Router extends Service { let oldonclose = c.onclose; c.onclose = (...args:any[]) => { if(settings.onclose) settings.onclose(settings, ...args); - if( - autoRemove && - settings.source && - this.users[settings.source] && - Object.keys(this.sources[settings.source]).length === 0 - ) { + if(this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { this.removeUser(settings.source, false); } if(oldonclose) oldonclose(...args); @@ -811,12 +641,7 @@ export class Router extends Service { let oldonclose = c.onclose; c.onclose = (...args:any[]) => { this.removeConnection(settings); - if( - autoRemove && - settings.source && - this.users[settings.source] && - Object.keys(this.sources[settings.source]).length === 0 - ) { //automatically clear a user if all of their connections + if(this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { this.removeUser(settings.source, false); } if(oldonclose) oldonclose(...args); @@ -950,13 +775,50 @@ export class Router extends Service { if(connection instanceof Promise) { return connection.then(async (info) => { if(!info._id) { - await connectionHasId(info,this.userTimeout); + await new Promise((res,rej) => { + let start = performance.now(); + let checker = () => { + if(!info._id) { + if(performance.now() - start > 3000) { + rej(false); + } else { + setTimeout(()=>{ + checker(); + },100); //check every 100ms + } + } else { + res(true); + } + } + + checker(); + + }).catch((er) => {console.error('Connections timed out:', er); }); } if(info._id) this.addConnection({connection:info, service}, source); }) } else if(connection) { if(!connection._id) { - await connectionHasId(connection,this.userTimeout); + await new Promise((res,rej) => { + + let start = performance.now(); + let checker = () => { + if(!connection._id) { + if(performance.now() - start > 3000) { + rej(false); + } else { + setTimeout(()=>{ + checker(); + },100); //check every 100ms + } + } else { + res(true); + } + } + + checker(); + + }).catch((er) => {console.error('Connections timed out:', er); }); } if(connection._id) return this.addConnection({connection, service}, source); } @@ -968,6 +830,34 @@ export class Router extends Service { return connection.terminate(); } + subscribeThroughConnection = ( + route:string, //the route on the endpoint we want to subscribe to outputs from + relay:string|ConnectionInfo, //the router we are trying to relay messages through + endpoint:string, //the endpoint on the router that we want to subscribe to through the router + callback:string|((res:any)=>void), + ...args:any[] + ) => { + if(typeof relay === 'string') { + relay = this.getConnection(relay,'run') as ConnectionInfo; + } + + if(typeof relay === 'object') + return new Promise((res,rej) => { + (relay as any).run('routeConnections',[route,endpoint,(relay as any)._id,...args]).then((sub) => { + this.__node.state.subscribeEvent(endpoint, (res) => { + if(res?.callbackId === route) { + if(!callback) this.setState({[endpoint]:res.args}); + else if(typeof callback === 'string') { //just set state + this.setState({[callback]:res.args}); + } + else callback(res.args); + } + }); + res(sub); + }).catch(rej); + }); + } + //we will use the router to relay subscriptions between endpoints generically routeConnections = ( route:string, //the route on the endpoint we want to subscribe to outputs from @@ -1041,27 +931,5 @@ export class Router extends Service { } -} -//e.g. check if a websocket etc has the id so its ready for sending commands -export function connectionHasId(connection:{_id?:string, [key:string]:any}, timeout=10000) { - return new Promise((res,rej) => { - let start = performance.now(); - let checker = () => { - if(!connection._id) { - if(performance.now() - start > timeout) { - rej(false); - } else { - setTimeout(()=>{ - checker(); - },100); //check every 100ms - } - } else { - res(true); - } - } - - checker(); - }).catch((er) => {console.error('Connection timed out:', er); }) as Promise; - } \ No newline at end of file diff --git a/src/services/sessions/sessions.service.ts b/src/services/sessions/sessions.service.ts index 1861086f..f650dd88 100644 --- a/src/services/sessions/sessions.service.ts +++ b/src/services/sessions/sessions.service.ts @@ -3,22 +3,8 @@ import { Service, ServiceOptions } from "../Service"; import { User } from "../router/Router"; import { loaders } from "../../loaders/index"; -/** - * Sessions are a way to run a loop that monitors data structures to know procedurally when and what to update - * - * OneWaySession: source sends props to listener, define listener, source default is creating user - * SharedSession: two modes: - * Hosted: Host receives props from all users based on propnames, users receive hostprops - * Shared: All users receive the same props based on their own updates - * - * There's also these older stream API functions that are more pure for monitoring objects/arrays and updating new data e.g. out of a buffer. - * Need to esplain/demo all that too.... @@__@@ - */ - - //parse from this object/endpoint and send to that object/endpoint, e.g. single users -//todo: make this hurt brain less to reconstruct the usage -export type OneWaySessionProps = { +export type PrivateSessionProps = { _id?:string, settings?:{ listener:string, @@ -28,10 +14,9 @@ export type OneWaySessionProps = { moderators?:{[key:string]:boolean}, password?:string, ownerId?:string, - onopen?:(session:OneWaySessionProps)=>void, - onhasupdate?:(session:OneWaySessionProps, updated:any)=>void, //host-side - onmessage?:(session:OneWaySessionProps, updated:any)=>void, //user-side - onclose?:(session:OneWaySessionProps)=>void, + onopen?:(session:PrivateSessionProps)=>void, + onmessage?:(session:PrivateSessionProps)=>void, + onclose?:(session:PrivateSessionProps)=>void, [key:string]:any //arbitrary props e.g. settings, passwords }, data?:{ @@ -44,14 +29,8 @@ export type OneWaySessionProps = { export type SessionUser = { _id:string, //unique identifier for user, used as key in users object and in general sessions:{[key:string]:any}, - sessionSubs:{[key:string]:{ - onopenSub?:number, - onmessage?:(session:SharedSessionProps, update:any, user:SessionUser)=>void, - onopen?:(session:SharedSessionProps, user:SessionUser)=>void, - onclose?:(session:SharedSessionProps, user:SessionUser)=>void - }} [key:string]:any -} & User //extend base users on the router or just wrapping a connection from another service +} & Partial //sessions for shared user data and game/app logic for synchronous and asynchronous sessions to stream selected properties on user objects as they are updated export type SharedSessionProps = { @@ -60,18 +39,16 @@ export type SharedSessionProps = { name:string, propnames:{[key:string]:boolean}, users?:{[key:string]:boolean}, - host?:string, //if there is a host, all users only receive from the host's prop updates and vise versa + host?:string, //if there is a host, all users only receive from the host's prop updates hostprops?:{[key:string]:boolean}, - inheritHostData?:boolean, //new hosts adopt old host data? Default true admins?:{[key:string]:boolean}, moderators?:{[key:string]:boolean}, spectators?:{[key:string]:boolean}, banned?:{[key:string]:boolean}, password?:string, ownerId?:string, - onhasupdate?:(session:SharedSessionProps, updated:any)=>void, //host-side onopen?:(session:SharedSessionProps)=>void, - onmessage?:(session:SharedSessionProps, updated:any)=>void, + onmessage?:(session:SharedSessionProps)=>void, onclose?:(session:SharedSessionProps)=>void, [key:string]:any //arbitrary props e.g. settings, passwords }, @@ -81,7 +58,7 @@ export type SharedSessionProps = { [key:string]:any } }, - oneWay?:{ //host driven sessions will share only what the host shares to all users, while hosts will receive hidden data + private?:{ //host driven sessions will share only what the host shares to all users, while hosts will receive hidden data [key:string]:any }, [key:string]:any @@ -104,7 +81,6 @@ export type StreamInfo = { } } -//Todo: streamline, we don't *really* need 3 types of streaming data structures but on the other hand everything is sort of optimized so just keep it export class SessionsService extends Service { name='sessions'; @@ -113,23 +89,13 @@ export class SessionsService extends Service { //complex user sessions with some premade rulesets sessions:{ - oneWay:{[key:string]:OneWaySessionProps}, //sync user props <--> user props + private:{[key:string]:PrivateSessionProps}, //sync user props <--> user props shared:{[key:string]:SharedSessionProps}//sync user props <--> all other users props } = { - oneWay:{}, + private:{}, shared:{} } - invites:{ - [key:string]:{ //userId - [key:string]:{//session Id - session:OneWaySessionProps|SharedSessionProps|string, - endpoint?:string //userid to send joinSession call to - } //session options - } - } = {} - - constructor(options?:ServiceOptions, users?:{[key:string]:SessionUser}) { super(options); this.setLoaders(loaders); @@ -138,20 +104,20 @@ export class SessionsService extends Service { } getSessionInfo = ( - sessionIdOrName?:string, //id or name (on shared sessions) + sessionId?:string, //id or name (on shared sessions) userId?:string ) => { - if(!sessionIdOrName) { + if(!sessionId) { return this.sessions.shared; } else { - if(this.sessions.oneWay[sessionIdOrName]) { - let s = this.sessions.oneWay[sessionIdOrName]; + if(this.sessions.private[sessionId]) { + let s = this.sessions.private[sessionId]; if(s.settings) if(s.settings.source === userId || s.settings.listener === userId || s.settings.ownerId === userId || s.settings.admins?.[userId as string] || s.settings.moderators?.[userId as string]) - return {oneWay:{[sessionIdOrName]:s}}; - } else if(this.sessions.shared[sessionIdOrName]) { - return {shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}; + return {private:{[sessionId]:s}}; + } else if(this.sessions.shared[sessionId]) { + return {shared:{[sessionId]:this.sessions.shared[sessionId]}}; } else { let res = {}; for(const id in this.sessions.shared) { @@ -163,43 +129,31 @@ export class SessionsService extends Service { } } - openOneWaySession = ( - options:OneWaySessionProps={}, - sourceUserId?:string, - listenerUserId?:string + openPrivateSession = ( + options:PrivateSessionProps={}, + userId?:string ) => { if(!options._id) { - options._id = `oneWay${Math.floor(Math.random()*1000000000000000)}`; - if(this.sessions.oneWay[options._id]) { + options._id = `private${Math.floor(Math.random()*1000000000000000)}`; + if(this.sessions.private[options._id]) { delete options._id; - this.openOneWaySession(options,sourceUserId); //regen id + this.openPrivateSession(options,userId); //regen id } } - if(options._id && sourceUserId && this.users[sourceUserId]) { - if(sourceUserId){ - if(!options.settings) - options.settings = { - listener:sourceUserId, - source:sourceUserId, - propnames:{latency:true}, - admins:{[sourceUserId]:true}, - ownerId:sourceUserId - }; - if(!options.settings.listener) - options.settings.listener = listenerUserId ? listenerUserId : sourceUserId; - if(!options.settings.source) - options.settings.source = sourceUserId; - if(!this.users[sourceUserId].sessions) - this.users[sourceUserId].sessions = {}; - this.users[sourceUserId].sessions[options._id] = options; + if(options._id && userId && this.users[userId]) { + if(userId){ + if(!options.settings) options.settings = { listener:userId, source:userId, propnames:{latency:true}, admins:{[userId]:true}, ownerId:userId }; + if(!options.settings.listener) options.settings.listener = userId; + if(!options.settings.source) options.settings.source = userId; + if(!this.users[userId].sessions) this.users[userId].sessions = {}; + this.users[userId].sessions[options._id] = options; } if(!options.data) options.data = {}; - if(options.onopen) options.onopen(options); - if(this.sessions.oneWay[options._id]) { - return this.updateSession(options,sourceUserId); + if(this.sessions.private[options._id]) { + return this.updateSession(options,userId); } else if(options.settings?.listener && options.settings.source) - this.sessions.oneWay[options._id] = options; //need the bare min in here + this.sessions.private[options._id] = options; //need the bare min in here } return options; } @@ -212,41 +166,21 @@ export class SessionsService extends Service { options._id = `shared${Math.floor(Math.random()*1000000000000000)}`; if(this.sessions.shared[options._id]) { delete options._id; - return this.openSharedSession(options,userId); //regen id + this.openSharedSession(options,userId); //regen id } } if(options._id && userId && this.users[userId]){ if(typeof userId === 'string') { - if(!options.settings) - options.settings = { - name:'shared', - propnames:{latency:true}, - users:{[userId]:true}, - admins:{[userId]:true}, - ownerId:userId - }; + if(!options.settings) options.settings = { name:'shared', propnames:{latency:true}, users:{[userId]:true}, admins:{[userId]:true}, ownerId:userId }; - if(!options.settings.users) - options.settings.users = {[userId]:true}; - if(!options.settings.admins) - options.settings.admins = {[userId]:true}; - if(!options.settings.ownerId) - options.settings.ownerId = userId; - if(!this.users[userId].sessions) - this.users[userId].sessions = {}; + if(!options.settings.users) options.settings.users = {[userId]:true}; + if(!options.settings.admins) options.settings.admins = {[userId]:true}; + if(!options.settings.ownerId) options.settings.ownerId = userId; + if(!this.users[userId].sessions) this.users[userId].sessions = {}; this.users[userId].sessions[options._id] = options; - } - else if (!options.settings) - options.settings = { - name:'shared', - propnames:{latency:true}, - users:{} - }; - if(!options.data) - options.data = { oneWay:{}, shared:{} }; - if(!options.settings.name) - options.name = options.id; - if(options.onopen) options.onopen(options); + } else if (!options.settings) options.settings = {name:'shared', propnames:{latency:true}, users:{}}; + if(!options.data) options.data = { private:{}, shared:{} }; + if(!options.settings.name) options.name = options.id; if(this.sessions.shared[options._id]) { return this.updateSession(options,userId); } @@ -255,50 +189,37 @@ export class SessionsService extends Service { return options; } - open = (options:any,userId?:string) => { - if(options.listener) this.openOneWaySession(options,userId); - else this.openSharedSession(options,userId); - } - //update session properties, also invoke basic permissions checks for who is updating updateSession = ( - options:OneWaySessionProps | SharedSessionProps, + options:PrivateSessionProps | SharedSessionProps, userId?:string ) => { //add permissions checks based on which user ID is submitting the update let session:any; if(options._id){ - session = this.sessions.oneWay[options._id]; - if(!session) - session = this.sessions.shared[options._id]; - if(session && userId) { - if(session.settings && ( - session?.settings.source === userId || - session.settings.admins?.[userId] || - session.settings.moderators?.[userId] || - session.settings.ownerId === userId - )) { - return this.recursivelyAssign(session, options); + session = this.sessions.private[options._id]; + if(!session) session = this.sessions.shared[options._id]; + if(this.sessions.private[options._id] && userId) { + let sesh = this.sessions.shared[options._id]; + if(sesh.settings && (sesh?.settings.source === userId || sesh.settings.admins?.[userId] || sesh.settings.moderators?.[userId] || sesh.settings.ownerId === userId)) { + return Object.assign(this.sessions.shared[options._id],options); } } else if(options.settings?.source) { - return this.openOneWaySession(options as OneWaySessionProps,userId); + return this.openPrivateSession(options as PrivateSessionProps,userId); } else return this.openSharedSession(options as SharedSessionProps,userId); } return false; } - //add a user id to a session, Run this at the session host location and clientside if separate. remoteUser will take care of this on either endpoint for you - //supply options e.g. to make them a moderator or update properties to be streamed dynamically + //add a user id to a session, supply options e.g. to make them a moderator or update properties to be streamed dynamically joinSession = ( sessionId:string, userId:string, - options?:SharedSessionProps|OneWaySessionProps, - remoteUser:boolean=true //ignored if no endpoint on user object - ):SharedSessionProps|OneWaySessionProps|false => { + options?:SharedSessionProps|PrivateSessionProps + ) => { if(!userId && !this.users[userId]) return false; if(!this.users[userId].sessions) this.users[userId].sessions = {}; - let sesh = this.sessions.shared[sessionId] as SharedSessionProps|OneWaySessionProps; - if(!sesh) sesh = this.sessions.oneWay[sessionId]; + let sesh = this.sessions.shared[sessionId]; //console.log(sessionId,userId,sesh,this.sessions); if(sesh?.settings) { if(sesh.settings?.banned) { @@ -309,233 +230,70 @@ export class SessionsService extends Service { if(options.settings.password !== sesh.settings.password) return false } (sesh.settings.users as any)[userId] = true; - sesh.settings.newUser = true; this.users[userId].sessions[sessionId] = sesh; if(options) { return this.updateSession(options,userId); }; //console.log(sesh) - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'joinSession',args:[sessionId,userId,sesh]}); //callbacks on the sesh should disappear with json.stringify() in the send calls when necessary - } - return sesh; - } - else if (options?.source || options?.listener) { - sesh = this.openOneWaySession(options as OneWaySessionProps,userId); - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'joinSession',args:[sessionId,userId,sesh]}); - } - return sesh; - } - else if (options) { - sesh = this.openSharedSession(options as SharedSessionProps,userId); - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'joinSession',args:[sessionId,userId,sesh]}); - } return sesh; - } + } else if (options?.source || options?.listener) return this.openPrivateSession(options as PrivateSessionProps,userId); + else if (options) return this.openSharedSession(options as SharedSessionProps,userId); return false; } - inviteToSession = ( - session:OneWaySessionProps|SharedSessionProps|string, - userInvited:string, - inviteEndpoint?:string, //your user/this socket endpoint's ID as configured on router - remoteUser:boolean=true - ) => { - if(remoteUser && this.users[userInvited]?.send) { - this.users[userInvited]?.send({route:'receiveSessionInvite', args:[ - session, - userInvited, - inviteEndpoint - ]}); - } else { - this.receiveSessionInvite(session,userInvited,inviteEndpoint); - } - } - - //subscribe to this clientside to do stuff when getting notified - receiveSessionInvite = ( - session:OneWaySessionProps|SharedSessionProps|string, //this session - userInvited:string, //invite this user - endpoint?:string //is the session on another endpoint (user or other?)? - ) => { - if(!this.invites[userInvited]) this.invites[userInvited] = {}; - let id = typeof session === 'string' ? session : session._id; - this.invites[userInvited][id] = {session, endpoint}; - - return id; - } - - acceptInvite = ( //will wait for endpoint to come back if remote invitation - session:OneWaySessionProps|SharedSessionProps|string, //session id is minimum - userInvited:string, - remoteUser=true - ):Promise => { - let id = typeof session === 'string' ? session : session._id; - let invite = this.invites[userInvited]?.[id]; - let endpoint; - if(invite) { - session = invite.session; - endpoint = invite.endpoint; - delete this.invites[userInvited]?.[id]; - } - return new Promise((res,rej) => { - if(!id) res(false); - if(remoteUser && endpoint && this.users[endpoint]?.send) { - //wait for the remote joinSession call to come back - let resolved; - let timeout = setTimeout(()=>{ - if(!resolved) { - this.unsubscribe('joinSession',subbed); rej(new Error('Session join timed out')); - } - },10000); - let subbed = this.subscribe('joinSession', (result:SharedSessionProps|OneWaySessionProps|false)=>{ - if(typeof result === 'object' && result?._id === id) { - if(result.setting?.users?.includes(userInvited)) { - //we've joined the session - this.unsubscribe('joinSession', subbed); - resolved = true; - if(timeout) clearTimeout(timeout); - res(result); - } - } - }); - this.users[endpoint]?.send({route:'joinSession',args:[id,userInvited,undefined,true]}); - //10sec timeout - } else res(this.joinSession(id, userInvited, typeof session === 'object' ? session : undefined)); - }); - } - - rejectInvite = ( - session:OneWaySessionProps|SharedSessionProps|string, - userInvited:string, - remoteUser=true - ) => { - let id = typeof session === 'string' ? session : session._id; - if(this.invites[userInvited]?.[id]) { - let endpoint = this.invites[userInvited][id].endpoint; - delete this.invites[userInvited][id]; - if(remoteUser && endpoint && this.users[endpoint]?.send) { - this.users[endpoint].send({route:'rejectInvite',args:[id,userInvited]}); //listen on host end too to know if invite was rejected - } - return true; - } - } - - //Remove a user from a session. OneWay sessions will be closed - //Run this at the session host location leaveSession = ( - session:OneWaySessionProps|SharedSessionProps|string, + sessionId:string, userId:string, - clear:boolean=true, //clear all data related to this user incl permissions - remoteUser:boolean=true //send user an all-clear to unsubscribe on their end + clear:boolean=true //clear all data related to this user incl permissions ) => { - let sessionId:string|undefined; - if(typeof session === 'string') { - sessionId = session; - session = this.sessions.oneWay[sessionId]; - if(!session) session = this.sessions.shared[sessionId]; - } else sessionId = session._id; + let session:any = this.sessions.private[sessionId]; + if(!session) session = this.sessions.shared[sessionId]; if(session) { - if(this.sessions.oneWay[sessionId]) { - if( userId === session.settings.source || - userId === session.settings.listener || - session.settings.admins?.[userId] || - session.settings.moderators?.[userId] - ) { - delete this.sessions.oneWay[sessionId]; - delete this.users[userId]?.sessions[sessionId]; - delete this.users[userId]?.sessionSubs?.[sessionId]; + if(this.sessions.private[sessionId]) { + if(userId === session.settings.source || userId === session.settings.listener || session.settings.admins?.[userId] || session.settings.moderators?.[userId]) { + delete this.sessions.private[sessionId]; + delete this.users[userId].sessions[sessionId]; if(clear) { if(session.settings.admins?.[userId]) delete (this.sessions.shared[sessionId].settings?.admins as any)[userId]; if(session.settings.moderators?.[userId]) delete (this.sessions.shared[sessionId].settings?.moderators as any)[userId]; } - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'unsubscribeFromSession',args:[session._id, userId, clear]}); - } else { - this.unsubsribeFromSession(session, userId, clear); - } } } else if (this.sessions.shared[sessionId]) { delete this.sessions.shared.settings.users[userId]; - delete this.users[userId]?.sessions[sessionId]; - delete this.users[userId]?.sessionSubs?.[sessionId]; + delete this.users[userId].sessions[sessionId]; if(clear) { if(session.settings.admins?.[userId]) delete (this.sessions.shared[sessionId].settings?.admins as any)[userId]; if(session.settings.moderators?.[userId]) delete (this.sessions.shared[sessionId].settings?.moderators as any)[userId]; if(session.data.shared[userId]) delete this.sessions.shared[sessionId].data?.shared[userId]; if(session.settings.host === userId) { - this.swapHost(session, undefined, true); - delete session.data.shared[userId]; + delete session.settings.host; + delete session.data.shared; + session.data.shared = {}; + this.swapHost(session); } } - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'unsubscribeFromSession',args:[session._id, userId, clear]}); - } else { - this.unsubsribeFromSession(session, userId, clear); - } } return true; } return false; } - //Delete a session. Run this at the session host location - deleteSession = (session:string|OneWaySessionProps|SharedSessionProps, userId:string, remoteUsers=true) => { - - if(typeof session === 'string') { - let id = session; - session = this.sessions.oneWay[id]; - if(!session) session = this.sessions.shared[id]; - } - if(session) { - if(session.source === userId || session.listener === userId || session.admins?.[userId] || session.ownerId === userId) { - for(const user in session.settings.users) { - if(this.users[user]?.sessions) delete this.users[user].sessions[session._id]; - if(this.users[user]?.sessionSubs) delete this.users[user].sessionSubs[session._id]; - if(remoteUsers) { - if(session.users) { - for(const key in session.users) { - if(this.users[key]?.send) - this.users[key].send({route:'unsubscribeFromSession',args:[session._id, key]}); - } - } - else if(session.listener) { - if(this.users[session.listener]?.send) - this.users[session.listener].send({route:'unsubscribeFromSession',args:[session._id, session.listener]}); - } else if (this.users[userId]?.send) { - this.users[userId].send({route:'unsubscribeFromSession',args:[session._id, userId]}); - } - } else { - this.unsubsribeFromSession(session, user); - } - } - if(this.sessions.oneWay[session._id]) delete this.sessions.oneWay[session._id]; - else if(this.sessions.shared[session._id]) delete this.sessions.oneWay[session._id]; - if(session.onclose) session.onclose(session); - } - } - return true; - } - getFirstMatch(obj1:{[key:string]:any},obj2:{[key:string]:any}) { for(const i in obj1) { - if(i in obj2) return i; + for(const j in obj2) { + if(i === j) return i; + } } return false; } swapHost = ( - session:OneWaySessionProps|SharedSessionProps|string, - newHostId?:string, - adoptData:boolean=true, //copy original session hosts data? - remoteUser=true + session:PrivateSessionProps|SharedSessionProps|string, + newHostId?:string ) => { if(typeof session === 'string') { - if(this.sessions.oneWay[session]) session = this.sessions.oneWay[session]; + if(this.sessions.private[session]) session = this.sessions.private[session]; else if(this.sessions.shared[session]) session = this.sessions.shared[session]; } if(typeof session === 'object' && session.settings) { - let oldHost = session.settings.host; delete session.settings.host; if(newHostId) { if(session.settings.users[newHostId]) session.settings.host = newHostId; @@ -552,112 +310,71 @@ export class SessionsService extends Service { if(match) session.settings.host = match; }//sendAll leadership when host swapping if(!session.settings.host) session.settings.host = Object.keys(session.settings.users)[0]; //replace host - if(adoptData && oldHost && session.settings.inheritHostData !== false) { - if(session.data?.shared[oldHost]) { //oneWay data will stay the same - if(session.data?.shared[oldHost]) { - session.data.shared[session.settings.host] = Object.assign( - session.data.shared[session.settings.host] ? session.data.shared[session.settings.host] : {}, - session.data.shared[oldHost] - ); - if(remoteUser) { + return true; + } + return false; + } - } - } + deleteSession = (sessionId:string, userId:string) => { + let session:any = this.sessions.private[sessionId]; + if(!session) session = this.sessions.shared[sessionId]; + if(session) { + if(session.source === userId || session.listener === userId || session.admins?.[userId] || session.ownerId === userId) { + for(const user in session.settings.users) { + if(this.users[user].sessions) delete this.users[user].sessions[sessionId]; } + if(this.sessions.private[sessionId]) delete this.sessions.private[sessionId] + else if(this.sessions.shared[sessionId]) delete this.sessions.private[sessionId] } - return true; } - return false; + return true; } - //run these on the clientside user subscribeToSession = ( - session:SharedSessionProps|OneWaySessionProps|string, + session:SharedSessionProps|PrivateSessionProps|string, userId:string, - onmessage?:(session:SharedSessionProps|OneWaySessionProps, update:any, user:SessionUser)=>void, - onopen?:(session:SharedSessionProps|OneWaySessionProps, user:SessionUser)=>void, - onclose?:(session:SharedSessionProps|OneWaySessionProps, user:SessionUser)=>void + onmessage?:(session:SharedSessionProps|PrivateSessionProps, userId:string)=>void, + onopen?:(session:SharedSessionProps|PrivateSessionProps, userId:string)=>void, + onclose?:(session:SharedSessionProps|PrivateSessionProps, userId:string)=>void ) => { if(typeof session === 'string') { - let s = this.sessions.oneWay[session]; + let s = this.sessions.private[session]; if(!s) s = this.sessions.shared[session] as any; if(!s) return undefined; session = s; - } - - let user = this.users[userId]; - if(!user) return undefined; - if(!user.sessionSubs) user.sessionSubs = {}; - if(!user.sessionSubs[session._id]) user.sessionSubs[session._id] = {}; - - if(onmessage) user.sessionSubs[session._id].onmessage = onmessage; - if(onopen) this.sessionSubs[userId][session._id].onopen = onopen; - if(onclose) user.sessionSubs[session._id].onclose = onclose; - if(typeof onopen === 'function') { + } + + if(typeof session.onopen === 'function') { let sub = this.subscribe('joinSession',(res) => { - if(res._id === (session as any)._id) - this.sessionSubs[userId][(session as any)._id].onopen(session as any, user); + if(res._id === (session as any)._id) (session as any).onopen(session, userId); this.unsubscribe('joinSession', sub as number); - }); - user.sessionSubs[session._id].onopenSub = sub; + }) } - - return session; - } - - //run these on the clientside user - unsubsribeFromSession = ( - session:SharedSessionProps|OneWaySessionProps|string, - userId?:string, - clear=true //clear session data (default true) - ) => { - if(typeof session === 'string') { - let s = this.sessions.oneWay[session]; - if(!s) s = this.sessions.shared[session] as any; - if(!s) return undefined; - session = s; - } - const clearSessionSubs = (Id:string, s:SharedSessionProps|OneWaySessionProps) => { - let u = this.users[Id]; - if(!u) return undefined; - if(u.sessionSubs?.[s._id]) { - if(u.sessionSubs[s._id].onopenSub) { - this.unsubscribe('joinSession', u.sessionSubs[s._id].onopenSub as number); - } - } - if(u.sessionSubs[s._id].onclose) u.sessionSubs[s._id].onclose(s as any, u); - delete u.sessionSubs[s._id]; - } + if(typeof session === 'object') { //we need to fire onmessage events when the session updates (setState for sessionId) and when the user updates - if(userId) { - clearSessionSubs(userId, session); - } else { - for(const key in this.users) { - clearSessionSubs(key, session); - } - } + if(onmessage) session.onmessage = onmessage; + if(onopen) session.onclose = onopen; + if(onclose) session.onclose = onclose; - if(clear) { - if(this.sessions.oneWay[session._id]) delete this.sessions.oneWay[session._id]; - else if(this.sessions.shared[session._id]) delete this.sessions.shared[session._id]; + + // if(typeof session.onmessage === 'function') + // this.subscribe(session._id,(session)=>{ session.onmessage(session,userId); }); + + // this.setState({[session._id]:session}); } + return session; } //iterate all subscriptions, e.g. run on backend - sessionUpdateCheck = ( - sessionHasUpdate?:( - session:OneWaySessionProps|SharedSessionProps, - update:{shared?:any,oneWay?:any} - )=>void,transmit=true - ) => { + sessionUpdateCheck = (transmit=true) => { let updates:any = { - oneWay:{}, + private:{}, shared:{} }; - for(const session in this.sessions.oneWay) { - const sesh = this.sessions.oneWay[session]; + for(const session in this.sessions.private) { + const sesh = this.sessions.private[session]; const updateObj = { _id:sesh._id, settings:{ @@ -667,31 +384,27 @@ export class SessionsService extends Service { data:{} } as any; //pull user's updated props and send to listener if(!this.users[sesh.source]) { - delete this.sessions.oneWay[session]; - continue; - } + delete this.sessions.private[session] + break; + } if(sesh.settings && sesh.data) { for(const prop in sesh.settings.propnames) { - if(prop in this.users[sesh.source]) { - if(this.sessions.oneWay[session].data) { + if( this.users[sesh.source][prop]) { + if(this.sessions.private[session].data) { if(typeof sesh.data[prop] === 'object') { if(this.users[sesh.source][prop] && (stringifyFast(sesh.data[prop]) !== stringifyFast(this.users[sesh.source][prop]) || !(prop in sesh.data))) updateObj.data[prop] = this.users[sesh.source][prop]; } - else if(prop in this.users[sesh.source] && (sesh.data[prop] !== this.users[sesh.source][prop] || !(prop in sesh.data))) + else if(this.users[sesh.source][prop] && (sesh.data[prop] !== this.users[sesh.source][prop] || !(prop in sesh.data))) updateObj.data[prop] = this.users[sesh.source][prop]; } else updateObj.data[prop] = this.users[sesh.source][prop]; - } else if(this.sessions.oneWay[session]?.data && prop in this.sessions.oneWay[session]?.data) - delete (this.sessions.oneWay[session].data as any)[prop]; + } else if(this.sessions.private[session]?.data?.[prop]) delete (this.sessions.private[session].data as any)[prop]; } } if(Object.keys(updateObj.data).length > 0) { - this.recursivelyAssign(this.sessions.oneWay[session].data, updateObj.data); //set latest data on the source object as reference - updates.oneWay[sesh._id as string] = updateObj; - - if(sessionHasUpdate) sessionHasUpdate(sesh,updateObj); - if(sesh.settings.onhasupdate) sesh.onhasupdate(sesh,updateObj); + this.recursivelyAssign(this.sessions.private[session].data, updateObj.data); //set latest data on the source object as reference + updates.private[sesh._id as string] = updateObj; } } @@ -706,99 +419,85 @@ export class SessionsService extends Service { } as any; if(sesh.settings?.host) { //host receives object of all other users - const oneWayData = {}; //host receives all users' props + const privateData = {}; //host receives all users' props const sharedData = {}; //users receive host props for(const user in sesh.settings.users) { - if(!this.users[user]) { //if no user found assume they're to be kicked from session + if(!this.users[user]) { delete sesh.settings.users[user]; //dont need to delete admins, mods, etc as they might want to come back <_< - if( sesh.settings.host === user ) - this.swapHost(sesh, undefined, true); - if( sesh.data?.shared[user] ) - delete sesh.data.shared[user]; - if( sesh.data?.oneWay?.[user] ) - delete sesh.data.shared[user]; + if( sesh.data?.shared[user]) delete sesh.data.shared[user]; + if( sesh.data?.private?.[user]) delete sesh.data.shared[user]; + if(sesh.settings.host === user) this.swapHost(sesh); updateObj.settings.users = sesh.settings.users; updateObj.settings.host = sesh.settings.host; continue; - } else if (sesh.settings.newUser) { //propagate who joined the room too - updateObj.settings.users = sesh.settings.users; - updateObj.settings.host = sesh.settings.host; - sesh.settings.newUser = false; } - if(user !== sesh.settings.host) { //the host will receive the oneWay data - oneWayData[user] = {}; + if(user !== sesh.settings.host) { + privateData[user] = {}; for(const prop in sesh.settings.propnames) { - if(prop in this.users[user]) { - if(sesh.data?.oneWay && !(user in sesh.data.oneWay)) { - if(typeof this.users[user][prop] === 'object') - oneWayData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); - else oneWayData[user][prop] = this.users[user][prop]; - } else if(typeof oneWayData[user][prop] === 'object' && sesh.data) { - if(prop in this.users[user][prop] && (stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data))) - oneWayData[user][prop] = this.users[user][prop]; + if(this.users[user][prop]) { + if(sesh.data?.private && !(user in sesh.data.private)) { + if(typeof this.users[user][prop] === 'object') privateData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); + else privateData[user][prop] = this.users[user][prop]; + } else if(typeof privateData[user][prop] === 'object' && sesh.data) { + if(this.users[user][prop] && (stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data))) + privateData[user][prop] = this.users[user][prop]; } - else if(this.users[user][prop] && sesh.data?.oneWay?.[prop] !== this.users[user][prop]) - oneWayData[user][prop] = this.users[user][prop]; - } else if (sesh.data?.oneWay?.[user] && prop in sesh.data?.oneWay?.[user]) - delete sesh.data.oneWay[user][prop]; //if user deleted the prop, session can delete it + else if(this.users[user][prop] && sesh.data?.private?.[prop] !== this.users[user][prop]) + privateData[user][prop] = this.users[user][prop]; + } else if (sesh.data?.private?.[user]?.[prop]) delete sesh.data.private[user][prop]; //if user deleted the prop, session can delete it } - if(Object.keys(oneWayData[user]).length === 0) - delete oneWayData[user]; - } else { //the rest of the users will receive the shared data + if(Object.keys(privateData[user]).length === 0) delete privateData[user]; + } else { sharedData[user] = {}; for(const prop in sesh.settings.hostprops) { - if(prop in this.users[user]) { + if(this.users[user][prop]) { if(sesh.data && !(user in sesh.data.shared)) { - if(typeof this.users[user][prop] === 'object') - sharedData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); + if(typeof this.users[user][prop] === 'object') sharedData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); else sharedData[user][prop] = this.users[user][prop]; } else if(typeof sharedData[user][prop] === 'object' && sesh.data) { - if((stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data.shared[user]))) + if(this.users[user][prop] && (stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data.shared[user]))) sharedData[user][prop] = this.users[user][prop]; - } else if(sesh.data?.shared[user][prop] !== this.users[user][prop]) + } + else if(this.users[user][prop] && sesh.data?.shared[user][prop] !== this.users[user][prop]) sharedData[user][prop] = this.users[user][prop]; - } else if (sesh.data?.shared[user] && prop in sesh.data?.shared[user]) - delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it + } else if (sesh.data?.shared[user]?.[prop]) delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it } } } - if(Object.keys(oneWayData).length > 0) { - updateObj.data.oneWay = oneWayData; + if(Object.keys(privateData).length > 0) { + updateObj.data.private = privateData; } if(Object.keys(sharedData).length > 0) { updateObj.data.shared = sharedData; } - } else { //all users receive the same update via shared data when no host set + } else { //all users receive the same update when no host set const sharedData = {}; //users receive all other user's props if(sesh.settings?.users) { for(const user in sesh.settings.users) { - if(!this.users[user]) { //if no user found assume they're to be kicked from session + if(!this.users[user]) { delete sesh.settings.users[user]; //dont need to delete admins, mods, etc as they might want to come back <_< - if( sesh.settings.host === user ) - this.swapHost(sesh, undefined, true); - if( sesh.data?.shared[user] ) - delete sesh.data.shared[user]; - if( sesh.data?.oneWay?.[user] ) - delete sesh.data.shared[user]; + if( sesh.data?.shared[user]) delete sesh.data.shared[user]; + if( sesh.data?.private?.[user]) delete sesh.data.shared[user]; + if(sesh.settings.host === user) this.swapHost(sesh); updateObj.settings.users = sesh.settings.users; updateObj.settings.host = sesh.settings.host; continue; } sharedData[user] = {}; for(const prop in sesh.settings.propnames) { - if(prop in this.users[user]) { + if(this.users[user][prop]) { if(sesh.data && !(user in sesh.data.shared)) { if(typeof this.users[user][prop] === 'object') sharedData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); else sharedData[user][prop] = this.users[user][prop]; - } else if(typeof sesh.data?.shared[user]?.[prop] === 'object') { + } else if(typeof sesh.data?.shared[user][prop] === 'object') { if((stringifyFast(sesh.data.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data.shared[user]))) { //if(stringifyFast(this.users[user][prop]).includes('peer')) console.log(stringifyFast(this.users[user][prop])) sharedData[user][prop] = this.users[user][prop]; } - } else if(sesh.data?.shared[user]?.[prop] !== this.users[user][prop]) + } + else if(sesh.data?.shared[user][prop] !== this.users[user][prop]) sharedData[user][prop] = this.users[user][prop]; - } else if (sesh.data?.shared[user] && prop in sesh.data?.shared[user]) - delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it + } else if (sesh.data?.shared[user]?.[prop]) delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it } if(Object.keys(sharedData[user]).length === 0) delete sharedData[user]; } @@ -806,26 +505,24 @@ export class SessionsService extends Service { //console.log(sharedData); updateObj.data.shared = sharedData; } - } + } } - if(updateObj.data.shared || updateObj.data.oneWay) { + if(updateObj.data.shared || updateObj.data.private) updates.shared[sesh._id as string] = updateObj; - if(updateObj.data.shared) { - Object.assign(this.sessions.shared[session].data?.shared, updateObj.data.shared); - //set latest data on the source object as reference - } - if(updateObj.data.oneWay) { - Object.assign(this.sessions.shared[session].data?.oneWay, updateObj.data.oneWay); - //set latest data on the source object as reference - } - if(sessionHasUpdate) sessionHasUpdate(sesh,updateObj); - if(sesh.settings.onhasupdate) sesh.settings.onhasupdate(sesh,updateObj); + + if(updateObj.data.shared) { + this.recursivelyAssign(this.sessions.shared[session].data?.shared,updateObj.data.shared) + //set latest data on the source object as reference + } + if(updateObj.data.private) { + this.recursivelyAssign(this.sessions.shared[session].data?.private,updateObj.data.private) + //set latest data on the source object as reference } } - if(Object.keys(updates.oneWay).length === 0) delete updates.oneWay; + if(Object.keys(updates.private).length === 0) delete updates.private; if(Object.keys(updates.shared).length === 0) delete updates.shared; if(Object.keys(updates).length === 0) return undefined; @@ -838,82 +535,91 @@ export class SessionsService extends Service { } - //transmit updates to users and setState locally based on userId. Todo: this could be more efficient + //transmit updates to users and setState locally based on userId transmitSessionUpdates = (updates:{ - oneWay:{[key:string]:any}, + private:{[key:string]:any}, shared:{[key:string]:any} }) => { let users = {}; - if(updates.oneWay) { - for(const s in updates.oneWay) { //oneWay session ids - let session = this.sessions.oneWay[s]; + if(updates.private) { + for(const s in updates.private) { + let session = this.sessions.private[s]; if(session?.settings) { - let u = session.settings.listener; //single user listener - if(!users[u]) users[u] = {}; - users[u].oneWay[s] = updates.oneWay[s]; + let u = session.settings.listener; + if(!users[u]) users[u] = {private:{}}; + else if(!users[u].private) users[u].private = {}; + users[u].private[s] = updates.private[s]; } } } if(updates.shared) { - for(const s in updates.shared) { //shared session ids + for(const s in updates.shared) { let session = this.sessions.shared[s]; if(session?.settings) { - for(const u in session.settings.users) { //for users in session - if(!users[u]) users[u] = {}; - users[u].shared[s] = updates.shared[s]; + let copy; + if(session.settings.host) { + copy = Object.assign({},updates.shared[s]); + delete copy.data.private; + } + for(const u in session.settings.users) { + if(!users[u]) users[u] = {shared:{}}; + else if(!users[u].shared) users[u].shared = {}; + if(session.settings.host) { + if(u !== session.settings.host) { + users[u].shared[s] = copy; + } else users[u].shared[s] = updates.shared[s]; + } + else users[u].shared[s] = updates.shared[s]; } } } } - //each user will receive an update for all sessions they are subscribed to //console.log(users) let message = {route:'receiveSessionUpdates', args:null as any} for(const u in users) { message.args = [u, users[u]]; - if((this.users[u] as any)?.send) (this.users[u] as any).send(JSON.stringify(message)); + if((this.users[u] as any).send) (this.users[u] as any).send(JSON.stringify(message)); this.setState({[u]:Object.create(message)}) } return users; } - //receive updates as a user - receiveSessionUpdates = (origin:any, update:{oneWay:{[key:string]:any},shared:{[key:string]:any}}|string) => { //following operator format we get the origin passed + //receive updates as users + receiveSessionUpdates = (origin:any, update:{private:{[key:string]:any},shared:{[key:string]:any}}|string) => { //following operator format we get the origin passed if(update) if(typeof update === 'string') update = JSON.parse(update as string); if(typeof update === 'object') { let user = this.users[origin]; - if(user) { - if(!user.sessions) user.sessions = {oneWay:{},shared:{}}; - if(!user.sessionSubs) user.sessionSubs = {}; - } - - if(update.oneWay) { - for(const key in update.oneWay) { - this.recursivelyAssign(this.sessions.oneWay[key].data, update.oneWay[key].data); - if(this.sessions.oneWay[key]?.settings.onmessage) - this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key], update.oneWay[key]); - if(user?.sessionSubs[user._id]?.[key]?.onmessage) - user.sessionSubs[user._id][key].onmessage(user.sessions[key], update, user); + if(!user) return undefined; + if(!user.sessions) user.sessions = {}; + + if(update.private) { + for(const key in update.private) { + if(!user.sessions[key]) continue; + this.recursivelyAssign(user.sessions[key].data,update.private[key].data); + if(user.sessions[key].onmessage) + user.sessions[key].onmessage(user.sessions[key],user._id) } } if(update.shared) { for(const key in update.shared) { - if(update.shared[key].settings.users) this.sessions.shared[key].settings.users = update.shared[key].settings.users; - if(update.shared[key].settings.host) this.sessions.shared[key].settings.host = update.shared[key].settings.host; - if(update.shared[key].data.oneWay) this.recursivelyAssign(this.sessions.shared[key].data.oneWay, update.shared[key].data.oneWay); - if(update.shared[key].data.shared) this.recursivelyAssign(this.sessions.shared[key].data.shared, update.shared[key].data.shared); - if(this.sessions.shared[key]?.settings.onmessage) - this.sessions.shared[key].settings.onmessage(this.sessions.shared[key], update.shared[key]); - if(user?.sessionSubs[user._id]?.[key]?.onmessage) - user.sessionSubs[user._id][key].onmessage(user.sessions[key], update, user); + if(!user.sessions[key]) continue; + if(update.shared[key].settings.users) user.sessions[key].settings.users = update.shared[key].settings.users; + if(update.shared[key].settings.host) user.sessions[key].settings.host = update.shared[key].settings.host; + if(update.shared[key].data.private) this.recursivelyAssign(user.sessions[key].data.private, update.shared[key].data.private); + if(update.shared[key].data.shared) this.recursivelyAssign(user.sessions[key].data.shared, update.shared[key].data.shared); + if(user.sessions[key].onmessage) + user.sessions[key].onmessage(user.sessions[key],user._id) } } return user; } } + //you either need to run this loop on a session to + // pass updates up to the server from your user manually getUpdatedUserData = (user:SessionUser) => { const updateObj = {}; for(const key in user.sessions) { @@ -962,7 +668,7 @@ export class SessionsService extends Service { } //e.g. run on frontend - userUpdateCheck = (user:SessionUser, onupdate?:(user:SessionUser, updateObj:{[key:string]:any})=>void) => { + userUpdateCheck = (user:SessionUser) => { //console.log('checking',user, this); if(user.sessions) { const updateObj = this.getUpdatedUserData(user); @@ -972,8 +678,7 @@ export class SessionsService extends Service { if(Object.keys(updateObj).length > 0) { let message = { route:'setUserProps', args:[user._id, updateObj] }; if(user.send) user.send(message); - this.setState({[user._id]:message}); - if(onupdate) { onupdate(user, updateObj) }; + this.setState({[user._id]:message}) return updateObj; } } @@ -995,17 +700,6 @@ export class SessionsService extends Service { return true; } - userUpdateLoop = { //this node loop will run separately from the one below it - __operator:this.userUpdateCheck, - __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O - } - - sessionLoop = { - __operator:this.sessionUpdateCheck, - __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O - } - - //more general object streaming //more rudimentary object streaming than the above sessions @@ -1188,7 +882,7 @@ export class SessionsService extends Service { //can remove a whole stream or just a key from a stream if supplied removeStream = (streamName,key) => { - if(streamName && this.streamSettings[streamName] && !key) { + if(streamName && !key) { if(this.streamSettings[streamName].onclose) (this.streamSettings[streamName] as any).onclose(this.streamSettings[streamName]); this.unsubscribe(streamName); //remove the subscriptions to this stream @@ -1246,6 +940,16 @@ export class SessionsService extends Service { __node:{loop:10} } + userUpdateLoop = { //this node loop will run separately from the one below it + __operator:this.userUpdateCheck, + __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O + } + + sessionLoop = { + __operator:this.sessionUpdateCheck, + __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O + } + } \ No newline at end of file diff --git a/src/services/sse/SSE.browser.ts b/src/services/sse/SSE.browser.ts index cdd35c15..eee71130 100644 --- a/src/services/sse/SSE.browser.ts +++ b/src/services/sse/SSE.browser.ts @@ -27,7 +27,7 @@ export type EventSourceInfo = { request:(message:any, method?:string)=>Promise, post:(route:any, args?:any)=>void, run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean)=>any, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, unsubscribe:(route:any, sub:number)=>Promise, terminate:() => void, graph:SSEfrontend @@ -64,36 +64,26 @@ export class SSEfrontend extends Service { if(!('keepState' in options)) options.keepState = true; //default true if(!options.events) options.events = {}; - let close; if(options.events.close) { - close = options.events.close; + let close = options.events.close; + options.events.close = (ev) => { if(sse.onclose) sse.onclose(ev,sse); close(ev,sse); }; } - options.events.close = (ev) => { - if(sse.onclose) sse.onclose(ev, sse); - if(close) close(ev,sse); - delete this.eventsources[options.url]; - }; - - let open; if(options.events.open) { - open = options.events.open; + let open = options.events.open; + options.events.open = (ev) => { if(sse.onopen) sse.onopen(ev,sse); open(ev,sse); }; } - options.events.open = (ev) => { if(sse.onopen) sse.onopen(ev,sse); if(open) open(ev,sse); }; - - let error; if(options.events.error) { - error = options.events.error; + let error = options.events.error; + options.events.error = (ev) => { if(sse.onerror) sse.onerror(ev,sse); error(ev,sse); }; } - options.events.error = (ev) => { if(sse.onerror) sse.onerror(ev,sse); if(error) error(ev,sse); }; - - let message; if(options.events.message) { - message = options.events.message; + let message = options.events.message; + options.events.message = (ev) => { if(sse.onmessage) sse.onmessage(ev,sse); message(ev,sse); }; } - if(!sse.onmessage) { - //default hook - sse.onmessage = (ev, sse) => { + if(!options.events.message) { + options.events.message = (ev, sse) => { + let data = ev.data; if(data) if(typeof data === 'string') { @@ -103,7 +93,7 @@ export class SSEfrontend extends Service { if(data[0] === '"') { data = data.substring(1,data.length-1)}; //console.log(message) data = JSON.parse(data); //parse stringified objects - + if(data.route === 'setId' && sse) { sse._id = data.args; options.events.message = (e, sse) => { //clear extra logic after id is set @@ -113,18 +103,11 @@ export class SSEfrontend extends Service { } } } - + const result = this.receive(ev.data,sse); - if(options.keepState) this.setState({[options.url]:data}); + if(options.keepState) this.setState({[options.url]:data}); } } - - options.events.message = (ev) => { - if(sse.onmessage) sse.onmessage(ev,sse); - if(message) message(ev,sse); - }; - - if(!options.events.error) options.events.error = (ev, sse) => { this.terminate(sse as any); delete this.eventsources[options.url]; @@ -151,7 +134,7 @@ export class SSEfrontend extends Service { } let request = (message:ServiceMessage|any, method?:string, sessionId?:string) => { - return this.request(message, options.url, method, sessionId); + return this.request(message, options.url, sessionId, method); } let post = (route:any, args?:any, method?:string) => { @@ -169,8 +152,8 @@ export class SSEfrontend extends Service { return this.request({route,args}, options.url, method, sessionId); } - let subscribe = (route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean):Promise => { - return this.subscribeToSSE(route, options.url, callback, args, key, subInput, sse._id); + let subscribe = (route:any, callback?:((res:any)=>void)|string):Promise => { + return this.subscribeToSSE(route, options.url, callback, sse._id); } let unsubscribe = (route:any, sub:number):Promise => { @@ -204,7 +187,7 @@ export class SSEfrontend extends Service { type:XMLHttpRequestResponseType='', mimeType?:string|undefined ) => { - if(typeof message === 'number' || (typeof message === 'object' && !message.byteLength && (type === 'json' || type === 'text' || !type))) { + if(typeof message === 'object' && (type === 'json' || type === 'text' || !type)) { message = JSON.stringify(message); } @@ -285,20 +268,13 @@ export class SSEfrontend extends Service { return res; } - subscribeSSE = ( - route:string, - url:string, - args?:any[], - key?:string, - subInput?:boolean - ) => { - if(this.restrict?.[route]) return undefined; + subscribeSSE = (route:string,url:string,key?:string,subInput?:boolean) => { return this.subscribe(route,(res) => { this.POST(res,url,'json'); - },args,key,subInput) + },key,subInput) } - subscribeToSSE = (route:string, url:string, callback?:string|((res:any)=>void), args?:any[], key?:string, subInput?:boolean, sessionId?:string) => { + subscribeToSSE = (route:string, url:string, callback?:string|((res:any)=>void), sessionId?:string, key?:string, subInput?:boolean) => { if(url) { this.__node.state.subscribeEvent(url,(res) => { let msg = JSON.parse(res); @@ -311,7 +287,7 @@ export class SSEfrontend extends Service { } }); - return this.eventsources[url].run('subscribeSSE',[route,url,args,key,subInput,sessionId]); + return this.eventsources[url].run('subscribeSSE',[route,url,sessionId,key,subInput]); } } diff --git a/src/services/sse/SSE.node.ts b/src/services/sse/SSE.node.ts index f4a26ce5..cc92cd04 100644 --- a/src/services/sse/SSE.node.ts +++ b/src/services/sse/SSE.node.ts @@ -1,5 +1,5 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import {createSession, createChannel, Session, Channel} from 'better-sse'; //third party lib. SSEs really just push notifications to an http endpoint but it's minimal overhead +import {createSession, createChannel, Session, SessionState, Channel} from 'better-sse'; //third party lib. SSEs really just push notifications to an http endpoint but it's minimal overhead import http from 'http' import https from 'https' import { Readable } from "node:stream"; @@ -21,14 +21,14 @@ export type SSEProps = { export type SSEChannelInfo = { channel: Channel>, sessions:{ - [key:string]:Session + [key:string]:Session }, requests:{[key:string]:Function}, //outstanding request promises send:(message:any, eventName?:string, sessionId?:string)=>any, request:(message:any, method?:string, sessionId?:string, eventName?:string)=>Promise|Promise[], post:(route:any, args?:any, method?:string, sessionId?:string, eventName?:string)=>void, run:(route:any, args?:any, method?:string, sessionId?:string, eventName?:string)=>Promise|Promise[], - subscribe:(route:any, callback?:((res:any)=>void)|string,args?:any[],key?:string,subInput?:boolean,sessionId?:string,eventName?:string)=>Promise|Promise[]|undefined, + subscribe:(route:any, callback?:((res:any)=>void)|string, sessionId?:string)=>Promise|Promise[]|undefined, unsubscribe:(route:any, sub:number, sessionId?:string, eventName?:string)=>Promise|Promise[], terminate:() => boolean, _id:string, @@ -37,14 +37,13 @@ export type SSEChannelInfo = { export type SSEClientInfo = { _id:string, - session:Session, + session:Session, served:SSEChannelInfo, send:(message:any, eventName?:string)=>any, request:(message:any, method?:string, eventName?:string)=>Promise, post:(route:any, args?:any, method?:string, eventName?:string)=>void, run:(route:any, args?:any, method?:string, eventName?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, - args?:any[],key?:string,subInput?:boolean,sessionId?:string,eventName?:string)=>any, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, unsubscribe:(route:any, sub:number, eventName?:string)=>Promise, terminate:() => boolean, onclose?:(session:any,sseinfo:any,_id:string,req:http.IncomingMessage,res:http.ServerResponse)=>void, @@ -75,7 +74,7 @@ export class SSEbackend extends Service { this.load(this); } - openSSE = (options:SSEProps) => { + setupSSE = (options:SSEProps) => { const server = options.server; let path = options.path; @@ -98,7 +97,9 @@ export class SSEbackend extends Service { sse._id = options._id ? options._id : path; - + if(!sse.onconnectionclose) sse.onconnectionclose = (session,sse,id,req,res) => { + delete sse.sessions[id]; + } const send = ( message:any, //the data you want to send @@ -146,10 +147,8 @@ export class SSEbackend extends Service { return this.request(r, path, method, sessionId, eventName) } - let subscribe = (route:any, callback?:((res:any)=>void)|string, - args?:any[],key?:string,subInput?:boolean, - sessionId?:string, eventName?:string):Promise|Promise[]|undefined => { - return this.subscribeToSSE(route, options.url, callback, args, key, subInput, sessionId, eventName); + let subscribe = (route:any, callback?:((res:any)=>void)|string, sessionId?:string):Promise|Promise[]|undefined => { + return this.subscribeToSSE(route, options.url, callback, sessionId); } let unsubscribe = (route:any, sub:number, sessionId?:string, eventName?:string):Promise|Promise[] => { @@ -194,7 +193,7 @@ export class SSEbackend extends Service { return run(route,args,method,_id,eventName); }, subscribe:(route,callback?)=>{ - return subscribe(route,callback,undefined,_id); + return subscribe(route,callback,_id); }, unsubscribe:(route,sub,eventName?)=>{ return unsubscribe(route,sub,_id,eventName); @@ -204,22 +203,12 @@ export class SSEbackend extends Service { delete sse.sessions[_id]; return true; }, - onclose:(session,sse,_id,req,res)=>{ - if(sse.onconnectionclose) sse.onconnectionclose(session,sse,_id,req,res); - }, + onclose:()=>options.onconnectionclose, graph:this } as SSEClientInfo; session.push(JSON.stringify({route:'setId',args:_id})); //associate this user's connection with a server generated id - session.on('close',()=>{ - let obj = this.eventsources[_id]; - let onclose = obj.onclose; - - delete this.eventsources[_id]; - - if(onclose) - (obj as any).onclose(session,sse,_id,req,response); - }) + session.on('close',()=>{if(this.eventsources[_id].onclose) (this.eventsources[_id] as any).onclose(session,sse,_id,req,response)}) if(sse.onconnection) {sse.onconnection(session,sse,_id,req,response);} }); @@ -295,7 +284,7 @@ export class SSEbackend extends Service { } - open = this.openSSE; + open = this.setupSSE; streamIterable = ( path:string, @@ -347,8 +336,8 @@ export class SSEbackend extends Service { eventName?:string, //event name? default is 'message' sessionId?:string //particular client? ) => { - if(!path && ((typeof data === 'object' && !data.byteLength) || typeof data === 'number')) { - if(data?.route) { + if(!path && typeof data === 'object') { + if(data.route) { let keys = Object.keys(this.servers) if(keys.length > 0) { @@ -454,15 +443,13 @@ export class SSEbackend extends Service { subscribeSSE = ( route:string, path:string, - args?:any[],key?:string,subInput?:boolean, sessionId?:string, eventName?:string ) => { - if(this.restrict?.[route]) return undefined; if(this.servers[path]) { return this.subscribe(route, (res) => { this.servers[path].send({args:res, callbackId:route}, eventName, sessionId); - }, args, key, subInput); + }) } } @@ -470,7 +457,6 @@ export class SSEbackend extends Service { route:string, path:string, callback?:string|((res:any)=>void), - args?:any[],key?:string,subInput?:boolean, sessionId?:string, eventName?:string ) => { @@ -489,7 +475,7 @@ export class SSEbackend extends Service { if(this.servers[path].sessions[sessionId]) { return this.eventsources[sessionId].run( 'subscribeSSE', - {route:'subscribeSSE',args:[route,path,args,key,subInput]}, + {route:'subscribeSSE',args:[route,path]}, undefined, eventName ) as Promise @@ -500,7 +486,7 @@ export class SSEbackend extends Service { promises.push( this.eventsources[k].run( 'subscribeSSE', - {route:'subscribeSSE',args:[route,path,args,key,subInput]}, + {route:'subscribeSSE',args:[route,path]}, undefined, eventName ) as Promise diff --git a/src/services/todo/RemoteService.ts b/src/services/todo/RemoteService.ts deleted file mode 100644 index f2995ac5..00000000 --- a/src/services/todo/RemoteService.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { isNativeClass } from '../../core/Graph' -import {Service, ServiceMessage} from '../Service' - -//trying to generalize e.g. the Socket and Worker classes - -export class RemoteService extends Service { - - endpoints:{ - [key:string]:{ - connection:any, - postCmd:Function, - class:any, - classArgs?:any - } - } - - class:any; - onmessage:string; - close:string; - onerror?:string; - onclose?:string; - onmessageTransform?:(message:any) => any; - onerrorTransform?:(er:any) => any; - post:string; - - createConnection = (instanceArgs:any[], settings?:{[key:string]:Function}) => { - - let info = { - _id: `connection${Math.floor(Math.random()*1000000000000000)}` - } as any; - - if(typeof this.class === 'function') { - if(isNativeClass(this.class)) { - info.connection = new this.class(...instanceArgs); - } else { - info.connection = this.class(...instanceArgs); - } - } else info.connection = this.class; - - - //defaults - if(this.onmessage) { - info.connection[this.onmessage] = (message:any) => { - if(this.onmessageTransform) { - message = this.onmessageTransform(message); - } - this.receive(message); - this.setState({[info._id]:message}); - } - } - - if(this.onerror) { - info.connection[this.onerror] = (er) => { - if(this.onerrorTransform) er = this.onerrorTransform(er); - } - } - - //overwrite callbacks with settings - if(settings) { - for(const key in settings) { - info.connection[key] = settings[key]; - } - } - - return info; - } - - __wrapConnection = (info:any) => { - info.send = () => {}; - info.post = () => {}; - info.run = () => {}; - info.request = () => {}; - info.subscribe = () => {}; - info.unsubscribe = () => {}; - info.start = async () => {}; - info.stop = async () => {}; - info.terminate = () => {}; - return info; - } - - transmit = (message:ServiceMessage|any, endpoint:string|any, transformer?:(message:any,endpoint:any) => any[] ) => { - - // put in transformer - // if(!transfer) { - // transfer = this.getTransferable(message); //automatically transfer arraybuffers - // } - if(typeof endpoint === 'string') { - endpoint = this.endpoints[endpoint]; - } - - if(typeof endpoint === 'object') { - if(transformer) { - let args = transformer(message,endpoint) as any[]; - endpoint.connection[endpoint.post](...args); - } else { - endpoint.connection[endpoint.post](message); - } - - return true; - } - - return false; - } - -} \ No newline at end of file diff --git a/src/services/unsafe/Unsafe.service.ts b/src/services/unsafe/Unsafe.service.ts new file mode 100644 index 00000000..cf2e59a1 --- /dev/null +++ b/src/services/unsafe/Unsafe.service.ts @@ -0,0 +1,150 @@ +import { parseFunctionFromText } from "../utils" +import { Graph } from "../../core/Graph" + +//Contains evals and other things you probably don't want wide open on an API +export const unsafeRoutes = { + + //add a route and parse it from text + setRoute:function(fn:string|((...args:[])=>any),fnName?:string){ + //console.log(fn, fnName) + //if(fnName === 'setupChart') console.log(fn); + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //if(fnName === 'setupChart') console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + if(this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__operator = fn //overwrite operator + } + else { + let node = (this.__node.graph as Graph).add({__node:{tag:fnName},__operator:fn}); + } + return true; + } + return false; + }, + setNode:function(fn:string|((...args:[])=>any),fnName?:string){ + //console.log(fn, fnName) + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + if(this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__operator = fn; //overwrite operator + } + else (this.__node.graph as Graph).add({__node:{tag:fnName},__operator:fn}); + //console.log(this) + return true; + } + return false; + }, + setMethod:function(route:string,fn:string|((...args:[])=>any),fnName?:string){ //set a method on a route + //console.log(fn, fnName) + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + if(this.__node.graph.get(route)) { + this.__node.graph.get(route)[fnName] = fn; //overwrite method + } + else (this.__node.graph as Graph).add({__node:{tag:fnName,[fnName]:fn}}); + //console.log(this) + return true; + } + return false; + }, + assignRoute:function(route:string,source:{[key:string]:any}) { //set values on a route + //console.log(fn, fnName) + if(this.__node.graph.get(route) && typeof source === 'object') { + Object.assign(this.__node.graph.get(route),source); + } + }, + transferClass:(classObj:any, className?:string)=>{ //send a class over a remote service + if(typeof classObj === 'object') { + let str = classObj.toString();//needs to be a class prototype + let message = {route:'receiveClass',args:[str,className]}; + + return message; + } + return false; + }, + receiveClass:function(stringified:string, className?:string){ //eval a class string and set it as a key on the local graph by class name, so this.__node.graph.method exists + if(typeof stringified === 'string') { + //console.log(stringified) + if(stringified.indexOf('class') === 0) { + let cls = (0,eval)('('+stringified+')'); + let name = className; + + if(!name) + name = cls.name; //get classname + this.__node.graph[name] = cls; + + return true; + } + } + return false; + }, + setGlobal:(key:string, value:any) => { //set a value on the globalThis scope + globalThis[key] = value; + return true; + }, + assignGlobalObject:(target:string, source:{[key:string]:any}) => { //assign a value on an object on the globalThis scope + if(!globalThis[target]) return false; + if(typeof source === 'object') Object.assign(globalThis[target],source); + return true; + }, + setValue:function(key:string, value:any) { //set a value on the graph scope + this.__node.graph[key] = value; + return true; + }, + assignObject:function(target:string, source:{[key:string]:any}){ //assign a value on an object on the globalThis scope + if(!this.__node.graph[target]) return false; + if(typeof source === 'object') Object.assign( this.__node.graph[target],source); + return true; + }, + setGlobalFunction:(fn:any, fnName?:string) => { //set a value on the globalThis scope + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + globalThis[fnName] = fn; + //console.log(this) + return true; + } + return false; + }, + assignFunctionToGlobalObject:function (globalObjectName:string, fn:any, fnName:any) { //assign a value on an object on the globalThis scope + if(! globalThis[globalObjectName]) return false; + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + this.__node.graph[globalObjectName][fnName] = fn; + //console.log(this) + return true; + } + return false; + }, + setFunction:function(fn:any, fnName?:string){ //set a value on the globalThis scope + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + this.__node.graph[fnName] = fn; + //console.log(this) + return true; + } + return false; + }, + assignFunctionToObject:function(objectName:string, fn:any, fnName:any) { //assign a value on an object on the globalThis scope + if(! this.__node.graph[objectName]) return false; + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + this.__node.graph[objectName][fnName] = fn; + //console.log(this) + return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/services/utils.ts b/src/services/utils.ts index 17cad895..253d8874 100644 --- a/src/services/utils.ts +++ b/src/services/utils.ts @@ -1,56 +1,37 @@ - - -export let recursivelyStringifyFunctions = (obj:{[key:string]:any}) => { - let cpy = {}; - for(const key in obj) { - if(typeof obj[key] === 'object') { - cpy[key] = recursivelyStringifyFunctions(obj[key]); - } - else if (typeof obj[key] === 'function') { - cpy[key] = obj[key].toString(); - } else cpy[key] = obj[key]; - } - return cpy; -} - -export function getFnParamNames(fn){ - if(typeof fn !== 'string') fn = fn.toString(); - const arrowMatch = fn.match(/\(?[^]*?\)?\s*=>/) - if (arrowMatch) return arrowMatch[0].replace(/[()\s]/gi,'').replace('=>','').split(',') - const match = fn.match(/\([^]*?\)/) - return match ? match[0].replace(/[()\s]/gi,'').split(',') : [] -} - -export let getFunctionHead = (methodString) => { - let startindex = methodString.indexOf('=>')+1; - if(startindex <= 0) { - startindex = methodString.indexOf('){'); - } - if(startindex <= 0) { - startindex = methodString.indexOf(') {'); - } - return methodString.slice(0, methodString.indexOf('{',startindex) + 1); -} - export function parseFunctionFromText(method='') { //Get the text inside of a function (regular or arrow); let getFunctionBody = (methodString) => { return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '$2$3$4'); } + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf('=>')+1; + if(startindex <= 0) { + startindex = methodString.indexOf('){'); + } + if(startindex <= 0) { + startindex = methodString.indexOf(') {'); + } + return methodString.slice(0, methodString.indexOf('{',startindex) + 1); + } + let newFuncHead = getFunctionHead(method); let newFuncBody = getFunctionBody(method); + let newFunc; if (newFuncHead.includes('function')) { - let varName = newFuncHead.substring(newFuncHead.indexOf('(')+1,newFuncHead.lastIndexOf(')')); + let varName = newFuncHead.split('(')[1].split(')')[0] newFunc = new Function(varName, newFuncBody); } else { - if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { - let varName = newFuncHead.substring(newFuncHead.indexOf('(')+1,newFuncHead.lastIndexOf(')')); - newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf('{') + 1, newFuncBody.length - 1)); - } else { - try { newFunc = (0, eval)(method); } catch { } // Just evaluate the method + if(newFuncHead.substring(0,6) === newFuncBody.substring(0,6)) { + //newFuncBody = newFuncBody.substring(newFuncHead.length); + let varName = newFuncHead.split('(')[1].split(')')[0] + //console.log(varName, newFuncHead ,newFuncBody); + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf('{')+1,newFuncBody.length-1)); + } + else { + try {newFunc = (0,eval)(newFuncHead + newFuncBody + "}");} catch {} } } @@ -128,11 +109,11 @@ export const stringifyWithCircularRefs = (function() { if (key) { updateParents(key, value); } let other = refs.get(value); - if (other) { - return '[Circular Reference]' + other; - } else { - refs.set(value, path.join('.')); - } + if (other) { + return '[Circular Reference]' + other; + } else { + refs.set(value, path.join('.')); + } } } return value; @@ -153,75 +134,6 @@ if((JSON as any).stringifyWithCircularRefs === undefined) { (JSON as any).stringifyWithCircularRefs = stringifyWithCircularRefs; } - -export const stringifyWithFunctionsAndCircularRefs = (function() { - const refs = new Map(); - const parents:any[] = []; - const path = ["this"]; - - function clear() { - refs.clear(); - parents.length = 0; - path.length = 1; - } - - function updateParents(key, value) { - var idx = parents.length - 1; - var prev = parents[idx]; - if(typeof prev === 'object') { - if (prev[key] === value || idx === 0) { - path.push(key); - parents.push(value.pushed); - } else { - while (idx-- >= 0) { - prev = parents[idx]; - if(typeof prev === 'object') { - if (prev[key] === value) { - idx += 2; - parents.length = idx; - path.length = idx; - --idx; - parents[idx] = value; - path[idx] = key; - break; - } - } - idx--; - } - } - } - } - - function checkCircular(key, value) { - if (value != null) { - if (typeof value === "object") { - if (key) { updateParents(key, value); } - - let other = refs.get(value); - if (other) { - return '[Circular Reference]' + other; - } else { - refs.set( typeof value === 'function' ? value.toString() : value, path.join('.')); - } - } - } - return typeof value === 'function' ? value.toString() : value; - } - - return function stringifyWithFunctionsAndCircularRefs(obj, space?) { - try { - parents.push(obj); - return JSON.stringify(obj, checkCircular, space); - } finally { - clear(); - } - } -})(); - -if((JSON as any).stringifyWithFunctionsAndCircularRefs === undefined) { - //Workaround for objects containing DOM nodes, which can't be stringified with JSON. From: https://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json - (JSON as any).stringifyWithFunctionsAndCircularRefs = stringifyWithFunctionsAndCircularRefs; -} //partial stringification for objects and removing circular references. This allows MUCH faster object equivalency comparison with three-tier depth checking export const stringifyFast = (function() { const refs = new Map(); @@ -364,4 +276,3 @@ if((JSON as any).stringifyFast === undefined) { //Workaround for objects containing DOM nodes, which can't be stringified with JSON. From: https://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json (JSON as any).stringifyFast = stringifyFast; } - diff --git a/src/services/webrtc/WebRTC.browser.ts b/src/services/webrtc/WebRTC.browser.ts index a53cb43a..ec598e6d 100644 --- a/src/services/webrtc/WebRTC.browser.ts +++ b/src/services/webrtc/WebRTC.browser.ts @@ -1,51 +1,36 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; -//how it works: -//https://hacks.mozilla.org/2013/07/webrtc-and-the-ocean-of-acronyms/ - export type WebRTCProps = { _id?:string, channels?:{ [key:string]:(true|RTCDataChannelInit|RTCDataChannel) }, config?:RTCConfiguration, - description?:RTCSessionDescription|string, + hostdescription?:RTCSessionDescriptionInit|string, + peerdescription?:RTCSessionDescriptionInit|string, offer?:RTCOfferOptions, hostcandidates?:{[key:string]:RTCIceCandidate}, peercandidates?:{[key:string]:RTCIceCandidate}, - candidates?:{[key:string]:RTCIceCandidate}, answer?:RTCAnswerOptions, ontrack?:(ev:RTCTrackEvent)=>void, - removetrack?:(ev:MediaStreamTrackEvent)=>void, //when a media stream track is removed by the peer onicecandidate?:(ev:RTCPeerConnectionIceEvent)=>void, onicecandidateerror?:(ev:Event)=>void, - onnegotiationneeded?:(ev:Event, description:RTCSessionDescription)=>void, + onnegotiationneeded?:(ev:Event)=>void, ondatachannel?:(ev:RTCDataChannelEvent)=>void, ondata?:(ev:MessageEvent, channel:RTCDataChannel, room)=>void, onconnectionstatechange?:(ev:Event)=>void, oniceconnectionstatechange?:(ev:Event)=>void, onclose?:(rtc:WebRTCInfo)=>void //custom callback - caller?:string, //e.g. caller's userId from Router - remoteId?:string, //e.g. set this when passing to the opposite user's 'receiveCallInformation' so you know which connection to call in the router for renegotiating - [key:string]:any //set whatever else for reference } export type WebRTCInfo = { _id:string, rtc:RTCPeerConnection, - senders?:(RTCRtpSender|undefined)[], - receivers?:(RTCRtpReceiver|undefined)[], - streams?:(MediaStream|undefined)[], //received mediastreams - polite?:boolean, //peer will prevent race conditions for simultaneous negotiations - videoSender?:RTCRtpSender, //audio track channel - audioSender?:RTCRtpSender, //video track channel - videoStream?:MediaStream, //audio track channel - audioStream?:MediaStream, //video track channel send:(message:any)=>void, //these callbacks work on the first available data channel to call to other webrtc services request:(message:any, method?:string)=>Promise, post:(route:any, args?:any)=>void, run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string,args?:any[],key?:string,subInput?:boolean,channelId?:string)=>Promise, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>Promise, unsubscribe:(route:any, sub:number)=>Promise, terminate:()=>boolean, graph:WebRTCfrontend @@ -61,11 +46,7 @@ export class WebRTCfrontend extends Service { [key:string]:WebRTCInfo } = {} - unanswered:{ - [key:string]:WebRTCProps - } = {} - - iceServers:RTCIceServer[] = [ + iceServers:{urls:string[]}[] = [ { urls: ['stun:stun.l.google.com:19302'] }, { urls: ['stun:stun1.l.google.com:19302'] }, { urls: ['stun:stun2.l.google.com:19302'] }, @@ -79,14 +60,42 @@ export class WebRTCfrontend extends Service { constructor( options?:ServiceOptions, - iceServers?:RTCIceServer[] + iceServers?:{urls:string[]}[] ) { super(options); + this.load(this); if(iceServers) this.iceServers = iceServers; + } + + createStream = ( //use navigator.mediaDevices.getUserMedia({audio:true,video:true}) for audio/video streams + options:{ + [key:string]:{ + track:MediaStreamTrack|MediaTrackConstraints, + onended:(ev)=>void, + onmute:(ev)=>void, + onunmute:(ev)=>void + } + } + ) => { + let stream = new MediaStream(); + for(const key in options) { + let track = options[key].track; + if(!(track instanceof MediaStreamTrack) && typeof track === 'object') { + track = new MediaStreamTrack(); + track.applyConstraints(options[key].track as MediaTrackConstraints) + stream.addTrack(track); + } - this.load(this); - //console.log(this) + if(track instanceof MediaStreamTrack) { + stream.addTrack(track as MediaStreamTrack); + track.onmute = options[key].onmute; + track.onunmute = options[key].onunmute; + track.onended = options[key].onended; + + } + } + return stream; } openRTC = async ( @@ -96,10 +105,10 @@ export class WebRTCfrontend extends Service { if(!options._id) options._id = `rtc${Math.floor(Math.random()*1000000000000000)}`; if(!options.config) options.config = {iceServers:this.iceServers}; + let rtc = new RTCPeerConnection(options.config); if(!this.rtc[options._id]) { - let rtc = new RTCPeerConnection(options.config); if(!options.channels) options.channels = { 'data':true }; //need one channel at least for the default service stuff to work @@ -175,12 +184,8 @@ export class WebRTCfrontend extends Service { }); } - let subscribe = (route:any, callback?:((res:any)=>void)|string, - args?:any[],key?:string, - subInput?:boolean, - channelId?:string - ) => { - return this.subscribeToRTC(route, options._id, channelId ? channelId : firstChannel, callback, args, key, subInput); + let subscribe = (route:any, callback?:((res:any)=>void)|string) => { + return this.subscribeToRTC(route, options._id, firstChannel, callback); } let unsubscribe = (route:any, sub:number) => { @@ -205,350 +210,181 @@ export class WebRTCfrontend extends Service { ...options } - const setMessageChannelHandle = (channel:RTCDataChannel) => { - if(!this.rtc[options._id].ondata) { - this.rtc[options._id].ondata = (mev) => { + //console.log('opening webrtc channel',this.rtc) + if(!options.ondatachannel) options.ondatachannel = (ev:RTCDataChannelEvent) => { + this.rtc[options._id].channels[ev.channel.label] = ev.channel; + if(!options.ondata) { + ev.channel.addEventListener('message', (mev) => { //console.log('message on data channel', mev); - this.receive(mev.data, channel, this.rtc[options._id]); + this.receive(mev.data, ev.channel, this.rtc[options._id]); this.setState({[options._id]:mev.data}); - } - channel.addEventListener('message', (mev) => { - //console.log('message on data channel', mev); - if(this.rtc[options._id].ondata) - this.rtc[options._id].ondata(mev, channel, this.rtc[options._id]); - }); - } - else { - channel.addEventListener('message', (mev) => { - if(this.rtc[options._id].ondata) - this.rtc[options._id].ondata(mev, channel, this.rtc[options._id]); }); } + else ev.channel.addEventListener('message', (mev) => { options.ondata(mev.data, ev.channel, this.rtc[options._id]); }); + } - if(this.rtc[options._id].channels) { - for(const channel in this.rtc[options._id].channels) { - if(this.rtc[options._id].channels[channel] instanceof RTCDataChannel) { + if(options.channels) { + for(const channel in options.channels) { + if(options.channels[channel] instanceof RTCDataChannel) { //OK } - else if( typeof this.rtc[options._id].channels[channel] === 'object') { - this.rtc[options._id].channels[channel] = this.addDataChannel(rtc,channel,(this.rtc[options._id].channels)[channel] as any); + else if( typeof options.channels[channel] === 'object') { + options.channels[channel] = this.addDataChannel(rtc,channel,(options.channels)[channel] as any); } else { - this.rtc[options._id].channels[channel] = this.addDataChannel(rtc,channel); + options.channels[channel] = this.addDataChannel(rtc,channel); } - setMessageChannelHandle(this.rtc[options._id].channels[channel] as RTCDataChannel); - + (options.channels[channel] as RTCDataChannel).addEventListener('message', (mev) => { + //console.log('message on data channel', mev); + this.receive(mev.data, channel, this.rtc[options._id]); + this.setState({[options._id]:mev.data}); + }); } } - rtc.ontrack = (ev) => { - if(!this.rtc[options._id].receivers) this.rtc[options._id].receivers = []; - this.rtc[options._id].receivers.push(ev.receiver); - - if(!this.rtc[options._id].streams) this.rtc[options._id].streams = []; - this.rtc[options._id].streams.push(...ev.streams); - - let rlength = this.rtc[options._id].receivers.length; - let slength = this.rtc[options._id].streams.length; - - ev.streams.forEach((s) => { - s.addEventListener('removetrack', (ev) => { - this.rtc[options._id].receivers[rlength] = undefined; - this.rtc[options._id].streams[slength] = undefined; - if(this.rtc[options._id].removetrack) this.rtc[options._id].removetrack(ev); - }) - }) - - if(this.rtc[options._id].ontrack) this.rtc[options._id].ontrack(ev); - }; - - rtc.ondatachannel = (ev) => { - this.rtc[options._id].channels[ev.channel.label] = ev.channel; - - setMessageChannelHandle(ev.channel); - - if(this.rtc[options._id].ondatachannel) - this.rtc[options._id].ondatachannel(ev); - }; - - rtc.onicecandidate = (ev) => { if(this.rtc[options._id].onicecandidate) this.rtc[options._id].onicecandidate(ev); }; - rtc.onicecandidateerror = (ev) => { if(this.rtc[options._id].onicecandidateerror) this.rtc[options._id].onicecandidateerror(ev); }; - - let initialOffer = this.rtc[options._id].description === undefined; - - rtc.onnegotiationneeded = async (ev) => { - if(!initialOffer) { - const offer = await rtc.createOffer(this.rtc[options._id].offer); - if (rtc.signalingState != "stable") return; - await rtc.setLocalDescription(offer); - - if(this.rtc[options._id].onnegotiationneeded) this.rtc[options._id].onnegotiationneeded(ev, rtc.localDescription); - } - }; - /* - rtc.onnegotiationneeded = async () => { //you need to implement this - const offer = await rtc.createOffer(); - if (rtc.signalingState != "stable") return; - await rtc.setLocalDescription(offer); - io.send({route:'negotiateCall', args: [options._id, rtc.localDescription]}); - } - */ - rtc.oniceconnectionstatechange = (ev) => { if(this.rtc[options._id].oniceconnectionstatechange) this.rtc[options._id].oniceconnectionstatechange(ev); }; - rtc.onconnectionstatechange = (ev) => { if(this.rtc[options._id].onconnectionstatechange) this.rtc[options._id].onconnectionstatechange(ev); }; + rtc.ontrack = options.ontrack; + rtc.onicecandidate = options.onicecandidate; + rtc.onicecandidateerror = options.onicecandidateerror; + rtc.ondatachannel = options.ondatachannel; + rtc.onnegotiationneeded = options.onnegotiationneeded; + rtc.oniceconnectionstatechange = options.oniceconnectionstatechange; + rtc.onconnectionstatechange = options.onconnectionstatechange; rtc.addEventListener('connectionstatechange', (ev) => { if(rtc.connectionState === 'closed' || rtc.connectionState === 'failed') { if(this.rtc[options._id].onclose) { this.rtc[options._id].onclose(this.rtc[options._id]); } - - delete this.rtc[options._id]; } - }); - + }) - if(!this.rtc[options._id].onicecandidate) this.rtc[options._id].onicecandidate = (ev:RTCPeerConnectionIceEvent) => { + } else { + Object.assign(this.rtc[options._id],options); + } + + if(options.hostdescription && !options.peerdescription) { + if(!options.onicecandidate) options.onicecandidate = (ev:RTCPeerConnectionIceEvent) => { if(ev.candidate) { let icecandidate = ev.candidate; - if(!this.rtc[options._id].candidates) this.rtc[options._id].candidates = {}; - this.rtc[options._id].candidates[`candidate${Math.floor(Math.random()*1000000000000000)}`] = icecandidate; + if(!this.rtc[options._id].peercandidates) this.rtc[options._id].peercandidates = {}; + this.rtc[options._id].peercandidates[`peercandidate${Math.floor(Math.random()*1000000000000000)}`] = icecandidate; } } - - if(!options.description) return await new Promise((res,rej) => { - this.rtc[options._id].rtc.createOffer(options.offer) - .then((offer) => this.rtc[options._id].rtc.setLocalDescription(offer)) - .then(()=>{ - initialOffer = false; - res(this.rtc[options._id]); //this is to be transmitted to the user - }); + + // console.log(options.hostdescription) + return await new Promise((res,rej) => { + //console.log('desc', options.hostdescription) + if(typeof options.hostdescription === 'string') { + options.hostdescription = JSON.parse(decodeURIComponent(options.hostdescription)); + } + const description = new RTCSessionDescription(options.hostdescription as RTCSessionDescriptionInit); + //console.log('desc2', description) + + options.hostdescription = description + rtc.setRemoteDescription(description).then(()=>{ + if(options.hostcandidates) { + for(const prop in options.hostcandidates) { + const candidate = new RTCIceCandidate(options.hostcandidates[prop]) + rtc.addIceCandidate(candidate).catch(console.error); + } + } + rtc.createAnswer(options.answer) + .then((answer)=> rtc.setLocalDescription(answer)) + .then(()=>{ + this.rtc[options._id].peerdescription = encodeURIComponent(JSON.stringify(rtc.localDescription)); + res(this.rtc[options._id]); + }); + }).catch(rej); //we can now receive data }); - - } else { - Object.assign(this.rtc[options._id],options); - } - - - if(options.description) { - this.rtc[options._id].polite = true; - await this.negotiateCall(options._id, options.description, true); } - - if(options.candidates) { - for(const prop in options.candidates) { - const candidate = new RTCIceCandidate(options.candidates[prop]) - this.rtc[options._id].rtc.addIceCandidate(candidate).catch(console.error); - } - } - - return this.rtc[options._id]; - } - - open = this.openRTC; //for the router - - addIceCandidate = (rtc:RTCPeerConnection|string, candidate:RTCIceCandidate) => { - if(typeof rtc === 'string') rtc = this.rtc[rtc]?.rtc; - if(typeof candidate === 'string') candidate = JSON.parse(decodeURIComponent(candidate)); - if(rtc && rtc.remoteDescription) return rtc.addIceCandidate(candidate); - } - - //receive and compile unanswered/unadded call information (e.g. peer descriptions and ice candidates) - //https://hacks.mozilla.org/2013/07/webrtc-and-the-ocean-of-acronyms/ - receiveCallInformation = async ( options:WebRTCProps ) => { - if(!options._id) options._id = `rtc${Math.floor(Math.random()*1000000000000000)}`; - if (this.rtc[options._id]) { - if(options.candidates) { - for(const key in options.candidates) - this.addIceCandidate(this.rtc[options._id].rtc, options.candidates[key]); - delete options.candidates; - } - Object.assign(this.rtc[options._id],options); + if(options.peerdescription) { + this.answerPeer(rtc,options); } - else if(this.unanswered[options._id]) { - this.recursivelyAssign(this.unanswered[options._id], options); // - } else this.unanswered[options._id] = options; - return options._id; - } - - answerCall = ( options:WebRTCProps|string ) => { - if(typeof options === 'string') options = this.unanswered[options]; - delete this.unanswered[options._id]; - return this.openRTC(options); - } + if(!options.onicecandidate && !this.rtc[options._id]?.onicecandidate) options.onicecandidate = (ev:RTCPeerConnectionIceEvent) => { + if(ev.candidate) { + let icecandidate = ev.candidate; - rejectCall = ( options:WebRTCProps|string ) => { - if(typeof options === 'string') options = this.unanswered[options]; - delete this.unanswered[options._id]; - return true; - } + if(!this.rtc[options._id].hostcandidates) this.rtc[options._id].hostcandidates = {}; + this.rtc[options._id].hostcandidates[`hostcandidate${Math.floor(Math.random()*1000000000000000)}`] = icecandidate; - negotiateCall = async ( rtc:RTCPeerConnection|string, description:string|RTCSessionDescription, polite?:boolean) => { - if(typeof rtc === 'string') { - if(polite === undefined) - polite = this.rtc[rtc].description !== undefined; //only the person called should have this defined - rtc = this.rtc[rtc].rtc; - } - if(typeof description === 'string') description = new RTCSessionDescription(JSON.parse(decodeURIComponent(description))); - if((description as RTCSessionDescription).type === 'offer' && rtc.signalingState !== 'stable') { - if(!polite) return; - await Promise.all([ - rtc.setLocalDescription({type:'rollback'}), - rtc.setRemoteDescription(description as RTCSessionDescription) - ]); - return encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); //we need to run negotiateCall on the other end now with this description to update the call information - } else { - await rtc.setRemoteDescription(description as RTCSessionDescription); - } if ((description as RTCSessionDescription).type == "offer") { - await rtc.setLocalDescription(await rtc.createAnswer()); - return encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); //we need to run negotiateCall on the other end now with this description to update the call information + } } - } - createOffer(rtc:RTCPeerConnection|string, options:WebRTCProps|string) { - if(typeof rtc === 'string') rtc = this.rtc[rtc].rtc; - if(typeof options === 'string') options = this.rtc[options]; - return new Promise((res,rej) => { - if(!rtc) rej(undefined); - (rtc as RTCPeerConnection).createOffer((options as WebRTCProps).offer) - .then((offer) => (rtc as RTCPeerConnection).setLocalDescription(offer)) + return await new Promise((res,rej) => { + rtc.createOffer(options.offer) + .then((offer) => rtc.setLocalDescription(offer)) .then(()=>{ - let description = encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); - res(description); //this is to be transmitted to the user - }); - }) + this.rtc[options._id].hostdescription = encodeURIComponent(JSON.stringify(rtc.localDescription)); + res(this.rtc[options._id]); //this is to be transmitted to the user + }); + }); + } - createAnswer(rtc:RTCPeerConnection|string, options:WebRTCProps|string) { - if(typeof rtc === 'string') rtc = this.rtc[rtc]?.rtc as RTCPeerConnection; - if(typeof options === 'string') options = this.rtc[options]; - - return new Promise((res,rej) => { - if(!rtc) rej(undefined); - (rtc as RTCPeerConnection).createAnswer((options as WebRTCProps).answer) - .then((answer)=> (rtc as RTCPeerConnection).setLocalDescription(answer)) - .then(()=>{ - let description = encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); - res(description); - }); - }); + addIceCandidate(rtc:RTCPeerConnection, candidate:RTCIceCandidate) { + return rtc.addIceCandidate(candidate); } - - answerPeer = (rtc:RTCPeerConnection|string, options:WebRTCProps|string) => { - if(typeof rtc === 'string') { - let cpy = Object.assign(this.rtc[rtc],options); - delete cpy.description; - delete cpy.candidates; - Object.assign(this.rtc[rtc],cpy); - rtc = this.rtc[rtc]?.rtc; - } - if(typeof options === 'string') options = this.rtc[options]; + //use the + answerPeer(rtc:RTCPeerConnection,options:WebRTCProps) { return new Promise((res,rej) => { - if(typeof (options as WebRTCProps).description === 'string') { - (options as WebRTCProps).description = JSON.parse(decodeURIComponent((options as WebRTCProps).description as string)); + if(typeof options.peerdescription === 'string') { + options.peerdescription = JSON.parse(decodeURIComponent(options.peerdescription)); } - const description = new RTCSessionDescription((options as WebRTCProps).description as RTCSessionDescriptionInit); - - (rtc as RTCPeerConnection).setRemoteDescription(description).then(()=>{ - if((options as WebRTCProps).candidates) { - for(const prop in (options as WebRTCProps).candidates) { - const candidate = new RTCIceCandidate((options as WebRTCProps).candidates[prop]) - if(this.rtc[(options as WebRTCProps)._id]) this.rtc[(options as WebRTCProps)._id].candidates[prop] = (options as WebRTCProps).candidates[prop]; - (rtc as RTCPeerConnection).addIceCandidate(candidate).catch(console.error); + const description = new RTCSessionDescription(options.peerdescription as RTCSessionDescriptionInit); + options.peerdescription = description; + + if(this.rtc[options._id]) this.rtc[options._id].peerdescription = description; + rtc.setRemoteDescription(description).then(()=>{ + if(options.peercandidates) { + for(const prop in options.peercandidates) { + const candidate = new RTCIceCandidate(options.peercandidates[prop]) + if(this.rtc[options._id]) this.rtc[options._id].peercandidates[prop] = options.peercandidates[prop]; + rtc.addIceCandidate(candidate).catch(console.error); } } - if(description.type === 'offer') { - this.rtc[(options as WebRTCProps)._id].rtc.createAnswer((options as WebRTCProps).answer).then((a) => { - this.rtc[(options as WebRTCProps)._id].rtc.setLocalDescription(a); - }); - } - res(this.rtc[(options as WebRTCProps)._id] ? this.rtc[(options as WebRTCProps)._id] : rtc); + res(this.rtc[options._id] ? this.rtc[options._id] : rtc); }).catch(rej); //we can now receive data }); } - - createStream = ( //use navigator.mediaDevices.getUserMedia({audio:true,video:true}) for audio/video streams - options:{ - [key:string]:{ - track:MediaStreamTrack|MediaTrackConstraints, - onended:(ev)=>void, - onmute:(ev)=>void, - onunmute:(ev)=>void - } - } - ) => { - let stream = new MediaStream(); - for(const key in options) { - let track = options[key].track; - if(!(track instanceof MediaStreamTrack) && typeof track === 'object') { - track = new MediaStreamTrack(); - track.applyConstraints(options[key].track as MediaTrackConstraints) - stream.addTrack(track); - } - - if(track instanceof MediaStreamTrack) { - stream.addTrack(track as MediaStreamTrack); - track.onmute = options[key].onmute; - track.onunmute = options[key].onunmute; - track.onended = options[key].onended; - - } - } - return stream; - } addUserMedia = ( rtc:RTCPeerConnection, options:MediaStreamConstraints={ - audio:true, + audio:false, video:{ optional:[ - {minWidth: 320 }, - {minWidth: 640 }, - {minWidth: 1024 }, - {minWidth: 1280 }, - {minWidth: 1920 }, - {minWidth: 2560 }, + {minWidth: 320}, + {minWidth: 640}, + {minWidth: 1024}, + {minWidth: 1280}, + {minWidth: 1920}, + {minWidth: 2560}, ] } as MediaTrackConstraints - }, - info?:WebRTCInfo + } ) => { - - return new Promise(async (res,rej) => { - - let RTCRtpSenders:any[] = []; - - let stream = await navigator.mediaDevices.getUserMedia(options) - - if(stream) { + let senders:any[] = []; + navigator.mediaDevices.getUserMedia(options) + .then((stream) => { let tracks = stream.getTracks() tracks.forEach((track) => { - let sender = rtc.addTrack(track,stream); - if(track.kind === 'video' && info) {info.videoSender = sender; info.videoStream = stream; } - if(track.kind === 'audio' && info) {info.audioSender = sender; info.audioStream = stream; } - RTCRtpSenders.push(sender); + senders.push(rtc.addTrack(track,stream)); }); - let str = stream; - - if(info) info.senders = - info.senders ? - [...info.senders, ...RTCRtpSenders] : - RTCRtpSenders; - - res(str); } - }); + ) + return senders; } //add media streams to the dat channel addTrack = (rtc:RTCPeerConnection, track:MediaStreamTrack, stream:MediaStream) => { - return rtc.addTrack(track,stream); + rtc.addTrack(track,stream); + return true; } removeTrack = (rtc:RTCPeerConnection,sender:RTCRtpSender) => { @@ -564,107 +400,9 @@ export class WebRTCfrontend extends Service { return rtc.createDataChannel(name,options); } - enableAudio = async (call:WebRTCInfo, audioOptions:boolean|(MediaTrackConstraints & {deviceId?:string})=true) => { - if(call.audioStream) this.disableAudio(call); - let stream = await this.addUserMedia( - call.rtc, - { - audio:audioOptions, - video:false - }, - call - ); - - if((audioOptions as any)?.deviceId) (call.audioSender as any).deviceId = (audioOptions as any).deviceId; - - return stream; - } - - enableVideo = async ( - call:WebRTCInfo, - videoOptions:(MediaTrackConstraints & {deviceId?:string, optional?:{minWidth: number}[] }) = { - //deviceId: 'abc' //or below default setting: - optional:[ - {minWidth: 320}, - {minWidth: 640}, - {minWidth: 1024}, - {minWidth: 1280}, - {minWidth: 1920}, - {minWidth: 2560}, - {minWidth: 3840}, - ] - } as MediaTrackConstraints & { deviceId?:string, optional?:{minWidth: number}[] }, - includeAudio:boolean|(MediaTrackConstraints & {deviceId?:string}) = false - ) => { //the maximum available resolution will be selected if not specified - - if(call.videoStream) this.disableVideo(call); - - let stream = await this.addUserMedia( - call.rtc, - { - audio:includeAudio, - video:videoOptions ? videoOptions : { - optional: [ - {minWidth: 320}, - {minWidth: 640}, - {minWidth: 1024}, - {minWidth: 1280}, - {minWidth: 1920}, - {minWidth: 2560}, - {minWidth: 3840}, - ] - } as MediaTrackConstraints - }, - call - ); - - if(videoOptions?.deviceId) (call.videoSender as any).deviceId = videoOptions.deviceId; - if(includeAudio) { - if((includeAudio as any)?.deviceId) - (call.audioSender as any).deviceId = (includeAudio as any).deviceId; - else if(videoOptions?.deviceId) (call.audioSender as any).deviceId = (videoOptions as any).deviceId; - } - - return stream; - } - - disableAudio(call:WebRTCInfo) { - if(call.audioSender) { - call.senders?.find((s,i) => { - if(call.audioStream?.getAudioTracks()[0].id === s.track.id) { - call.senders.splice(i,1); - return true; - } - }); - call.rtc.removeTrack(call.audioSender); - call.audioSender = undefined; - } - call.audioStream?.getTracks().forEach((track) => { - if(track.kind === 'audio') track.stop(); - }); - call.audioStream = undefined; - } - - disableVideo(call:WebRTCInfo) { - if(call.videoSender) { - call.senders?.find((s,i) => { - if(call.videoStream?.getVideoTracks()[0].id === s.track.id) { - call.senders.splice(i,1); - return true; - } - }); - call.rtc.removeTrack(call.videoSender); - call.videoSender = undefined; - } - call.videoStream?.getTracks().forEach((track) => { - if(track.kind === 'video') track.stop(); - }); - call.videoStream = undefined; - } - //send data on a data channel transmit = (data:ServiceMessage|any, id?:string, channel?:string|RTCDataChannel ) => { - if((typeof data === 'object' && ((data.route || data.node) || !(data as ArrayBufferLike).byteLength && typeof (data as Blob).arrayBuffer !== 'function') || typeof data === 'number')) + if(typeof data === 'object' || typeof data === 'number') data = JSON.stringify(data); //we need strings if(!channel && id) { //select first channel @@ -679,13 +417,13 @@ export class WebRTCfrontend extends Service { } else { //send on all channels on all rooms for(const id in this.rtc) { if(this.rtc[id].channels[channel] instanceof RTCDataChannel) - (this.rtc[id].channels[channel] as RTCDataChannel).send(data); // This may be a string, a Blob, an ArrayBuffer, a TypedArray or a DataView object. + (this.rtc[id].channels[channel] as RTCDataChannel).send(data); } } } if(channel instanceof RTCDataChannel) - channel.send(data); // This may be a string, a Blob, an ArrayBuffer, a TypedArray or a DataView object. + channel.send(data); //console.log('sending',channel,data) @@ -706,16 +444,16 @@ export class WebRTCfrontend extends Service { tx = (rtc as WebRTCInfo).rtc; } - if(rtc instanceof RTCPeerConnection && rtc.signalingState !== 'closed') { + if(rtc instanceof RTCPeerConnection) { rtc.close(); - } else if(tx && tx.signalingState !== 'closed') { + } else if(tx) { if(tx) tx.close(); } return true; } - request = (message:ServiceMessage|any, channel:RTCDataChannel, _id:string, method?:string) => { //return a promise which can resolve with a server route result through the socket + request = (message:ServiceMessage|any, channel:RTCDataChannel, _id:string,method?:string) => { //return a promise which can resolve with a server route result through the socket let callbackId = `${Math.random()}`; let req:any = {route:'runRequest', args:[message,_id,callbackId]}; if(method) req.method = method; @@ -734,45 +472,33 @@ export class WebRTCfrontend extends Service { }); } - runRequest = ( - message:any, - channelOrRtcId:RTCDataChannel|string, //data channel or rtc id (which grabs the first channel) - callbackId:string|number - ) => { //send result back + runRequest = (message:any, channel:RTCDataChannel|string, callbackId:string|number) => { //send result back let res = this.receive(message); - if(channelOrRtcId) { - if(typeof channelOrRtcId === 'string') { + if(channel) { + if(typeof channel === 'string') { for(const key in this.rtc) { - if(key === channelOrRtcId) {channelOrRtcId = this.rtc[key].channels.data ? this.rtc[key].channels.data as RTCDataChannel : this.rtc[key].channels[Object.keys(this.rtc[key].channels)[0]] as RTCDataChannel; break;} + if(key === channel) {channel = this.rtc[key].channels.data as RTCDataChannel; break;} } - } + } if(res instanceof Promise) res.then((v) => { res = {args:v, callbackId}; - if(channelOrRtcId instanceof RTCDataChannel) channelOrRtcId.send(JSON.stringify(res)); + if(channel instanceof RTCDataChannel) channel.send(JSON.stringify(res)); return res; }) else { res = {args:res, callbackId}; - if(channelOrRtcId instanceof RTCDataChannel) channelOrRtcId.send(JSON.stringify(res)); + if(channel instanceof RTCDataChannel) channel.send(JSON.stringify(res)); } } return res; } - subscribeRTC = ( - route:string, - rtcId:string, - args?:any[], - key?:string, - subInput?:boolean, - channel?:string|RTCDataChannel - ) => { - if(this.restrict?.[route]) return undefined; + subscribeRTC = (route:string, rtcId:string, channel:string|RTCDataChannel) => { if(typeof channel === 'string' && this.rtc[rtcId]) { channel = this.rtc[rtcId].channels[channel] as RTCDataChannel; - } else if (!channel) { channel = this.rtc[rtcId].channels[Object.keys(this.rtc[rtcId].channels)[0]] as RTCDataChannel } + } return this.subscribe(route, (res:any) => { //console.log('running request', message, 'for worker', worker, 'callback', callbackId) if(res instanceof Promise) { @@ -782,15 +508,10 @@ export class WebRTCfrontend extends Service { } else { (channel as RTCDataChannel).send(JSON.stringify({args:res, callbackId:route})); } - },args,key,subInput); + }); } - subscribeToRTC = ( - route:string, rtcId:string, channelId:string, callback?:string|((res:any)=>void), - args?:any[], - key?:string, - subInput?:boolean - ) => { + subscribeToRTC = (route:string, rtcId:string, channelId:string, callback?:string|((res:any)=>void)) => { if(typeof channelId === 'string' && this.rtc[rtcId]) { let c = this.rtc[rtcId]; let channel = c.channels[channelId]; @@ -805,7 +526,7 @@ export class WebRTCfrontend extends Service { else callback(res.args); } }); - return c.request({route:'subscribeRTC', args:[route,rtcId,args,key,subInput,channelId]}); + return c.request({route:'subscribeRTC', args:[route,channelId]}); } } } diff --git a/src/services/worker/ProxyListener.ts b/src/services/worker/ProxyListener.ts index c3ca33ae..af89123a 100644 --- a/src/services/worker/ProxyListener.ts +++ b/src/services/worker/ProxyListener.ts @@ -6,111 +6,76 @@ declare var WorkerGlobalScope; const mouseEventHandler = makeSendPropertiesHandler([ 'ctrlKey', 'metaKey', - 'altKey', 'shiftKey', 'button', - 'which', 'pointerType', 'clientX', 'clientY', 'pageX', 'pageY', - 'movementX', - 'movementY', - 'x', - 'y', - 'which', - 'timeStamp' ]); - -const wheelEventHandlerImpl = makeSendPropertiesHandler([ - 'deltaX', - 'deltaY', -]); - -const keydownEventHandler = makeSendPropertiesHandler([ - 'ctrlKey', - 'metaKey', - 'shiftKey', - 'altKey', - 'isComposing', - 'keyCode', - 'key', - 'code', - 'repeat', - 'timeStamp' -]); - -function focusEventHandler(event, sendFn) { - const data = { type:event.type } as any; - data.isTrusted = event.isTrusted; - data.bubbles = event.bubbles; - data.cancelBubble = event.cancelBubble; - data.cancelable = event.cancelable; - data.composed = event.composed; - data.defaultPrevent = event.defaultPrevented; - data.eventPhase = event.eventPhase; - data.returnValue = event.returnValue; - - data.currentTarget = event.currentTarget.id ? event.currentTarget.id : event.currentTarget.constructor.name; - data.target = data.currentTarget; - data.srcElement = data.currentTarget; - - sendFn(data); -} - -function wheelEventHandler(event, sendFn, preventDefault) { - if(preventDefault && event.preventDefault) event.preventDefault(); - wheelEventHandlerImpl(event, sendFn); -} - -function preventDefaultHandler(event, sendFn, preventDefault) { - if(preventDefault && event.preventDefault) event.preventDefault(); -} - -function copyProperties(src, properties, dst) { - for (const name of properties) { - dst[name] = src[name]; + const wheelEventHandlerImpl = makeSendPropertiesHandler([ + 'deltaX', + 'deltaY', + ]); + const keydownEventHandler = makeSendPropertiesHandler([ + 'ctrlKey', + 'metaKey', + 'shiftKey', + 'keyCode', + ]); + + function wheelEventHandler(event, sendFn) { + event.preventDefault(); + wheelEventHandlerImpl(event, sendFn); } -} - -function makeSendPropertiesHandler(properties) { - return function sendProperties(event, sendFn) { - const data = {type: event.type}; - copyProperties(event, properties, data); + + function preventDefaultHandler(event) { + event.preventDefault(); + } + + function copyProperties(src, properties, dst) { + for (const name of properties) { + dst[name] = src[name]; + } + } + + function makeSendPropertiesHandler(properties) { + return function sendProperties(event, sendFn) { + const data = {type: event.type}; + copyProperties(event, properties, data); + sendFn(data); + }; + } + + function touchEventHandler(event, sendFn) { + const touches = []; + const data = {type: event.type, touches}; + for (let i = 0; i < event.touches.length; ++i) { + const touch = event.touches[i]; + touches.push({ + pageX: touch.pageX, + pageY: touch.pageY, + }); + } sendFn(data); - }; -} - -function touchEventHandler(event, sendFn, preventDefault) { - if(preventDefault && event.preventDefault) event.preventDefault(); - const touches = []; - const data = {type: event.type, touches}; - for (let i = 0; i < event.touches.length; ++i) { - const touch = event.touches[i]; - touches.push({ - pageX: touch.pageX, - pageY: touch.pageY, - }); } - sendFn(data); -} - -let i = 1; -let keys = {}; -while(i < 222) { //proxy all key events - keys[i] = true; //avoid F keys - i++; -} - + + // The four arrow keys + const orbitKeys = { + '37': true, // left + '38': true, // up + '39': true, // right + '40': true, // down + }; -function filteredKeydownEventHandler(event, sendFn, preventDefault) { - let {keyCode} = event; - if (keys[keyCode]) { - if(preventDefault && event.preventDefault && (keyCode < 110 || keyCode > 123)) event.preventDefault(); - keydownEventHandler(event, sendFn); + function filteredKeydownEventHandler(event, sendFn) { + const {keyCode} = event; + if (orbitKeys[keyCode]) { + event.preventDefault(); + keydownEventHandler(event, sendFn); + } } -} export const eventHandlers = { //you can register more event handlers in this object contextmenu: preventDefaultHandler, @@ -120,21 +85,15 @@ export const eventHandlers = { //you can register more event handlers in this ob pointerdown: mouseEventHandler, pointermove: mouseEventHandler, pointerup: mouseEventHandler, - pointerlockchange: mouseEventHandler, - webkitpointerlockchange: mouseEventHandler, - focus: focusEventHandler, - blur: focusEventHandler, - pointerout: mouseEventHandler, touchstart: touchEventHandler, touchmove: touchEventHandler, touchend: touchEventHandler, wheel: wheelEventHandler, keydown: filteredKeydownEventHandler, - keyup: filteredKeydownEventHandler }; //do this on main thread -export function initProxyElement(element, worker, id, preventDefault?:boolean) { +export function initProxyElement(element, worker, id) { if( !id ) id = 'proxy'+Math.floor(Math.random()*1000000000000000); @@ -151,34 +110,10 @@ export function initProxyElement(element, worker, id, preventDefault?:boolean) { for (const [eventName, handler] of entries) { element.addEventListener(eventName, function(event) { //add all of the event listeners we care about - handler(event, sendEvent, preventDefault); + handler(event, sendEvent); }); } - if(eventHandlers.keydown) { - globalThis.addEventListener('keydown', function(ev) { - eventHandlers.keydown(ev, sendEvent, preventDefault); - }) - } - - if(eventHandlers.keyup) { - globalThis.addEventListener('keyup', function(ev) { - eventHandlers.keyup(ev, sendEvent, preventDefault); - }) - } - - // if(eventHandlers.focus) { - // globalThis.addEventListener('focus', function(ev) { - // eventHandlers.focus(ev, sendEvent); - // }) - // } - - // if(eventHandlers.blur) { - // globalThis.addEventListener('blur', function(ev) { - // eventHandlers.blur(ev, sendEvent); - // }) - // } - const sendSize = () => { const rect = element.getBoundingClientRect(); @@ -209,7 +144,6 @@ export class EventDispatcher { addEventListener( type, listener ) { - //console.log(type,listener); if ( this.__listeners === undefined ) this.__listeners = {}; const listeners = this.__listeners; if ( listeners[ type ] === undefined ) { @@ -254,12 +188,13 @@ export class EventDispatcher { for ( let i = 0, l = array.length; i < l; i ++ ) { array[ i ].call( this, event ); } - //event.target = null; + event.target = null; } } } -function noop() {}; +function noop() { +}; /////////////https://threejsfundamentals.org/threejs/lessons/threejs-offscreencanvas.html export class ElementProxyReceiver extends EventDispatcher { @@ -320,8 +255,6 @@ export class ElementProxyReceiver extends EventDispatcher { focus() {} - blur() {} - } /////////////https://threejsfundamentals.org/threejs/lessons/threejs-offscreencanvas.html @@ -330,11 +263,7 @@ export class ProxyManager { targets:any={}; constructor() { - if(!globalThis.document) globalThis.document = { - elementFromPoint:(...args:any[])=>{ //hax - return this.targets[Object.keys(this.targets)[0]].proxied; - } - } as any; //threejs hack for workers + if(!globalThis.document) globalThis.document = {} as any; //threejs hack for workers } makeProxy = (id, addTo=undefined) => { //addTo installs the desirable functions to the object you want @@ -371,7 +300,6 @@ export class ProxyManager { addTo.handleEvent = proxy.handleEvent.bind(proxy); addTo.dispatchEvent = proxy.dispatchEvent.bind(proxy); addTo.focus = proxy.focus.bind(proxy); - addTo.blur = proxy.blur.bind(proxy); } } diff --git a/_old/Subprocess.ts b/src/services/worker/Subprocess.ts similarity index 97% rename from _old/Subprocess.ts rename to src/services/worker/Subprocess.ts index b13fcadd..72ea8655 100644 --- a/_old/Subprocess.ts +++ b/src/services/worker/Subprocess.ts @@ -1,11 +1,8 @@ -import { parseFunctionFromText } from '../src/services/utils'; -import { WorkerInfo, WorkerService } from '../src/services/worker/Worker.service'; -import { remoteGraphRoutes } from '../src/services/remote/remote.routes'; -import { Graph, GraphNodeProperties } from '../src/core/Graph'; -import {methodstrings} from '../src/loaders/methodstrings' -export type Subprocess = (context:SubprocessContext,data:{[key:string]:any}|any)=>{[key:string]:any}|undefined +import { parseFunctionFromText } from '../utils'; +import { WorkerInfo, WorkerService } from './Worker.service'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; -//deprecated, just use remoteRoutes and normal node routines +export type Subprocess = (context:SubprocessContext,data:{[key:string]:any}|any)=>{[key:string]:any}|undefined export type SubprocessContextProps = { ondata:Subprocess, @@ -104,10 +101,11 @@ let recursivelyAssign = (target,obj) => { } + export const subprocessRoutes = { - ...remoteGraphRoutes, + ...unsafeRoutes, loadAlgorithms:loadAlgorithms, - 'initSubprocesses':async function initSubprocesses( //requires remoteGraphRoutes + 'initSubprocesses':async function initSubprocesses( //requires unsafeRoutes subprocesses:{ //use secondary workers to run processes and report results back to the main thread or other [key:string]:SubprocessWorkerProps }, @@ -347,7 +345,7 @@ export const subprocessRoutes = { if(typeof options?.ondata === 'function') ctx = createSubprocess(options,inputs); if(ctx) this.__node.graph.ALGORITHMS[ctx._id] = ctx; - //console.log(ctx,options); + console.log(ctx,options); if(ctx) return ctx._id; } @@ -358,7 +356,6 @@ export const subprocessRoutes = { data:{[key:string]:any}, _id?:string ){ - //console.log(data); if(!this.__node.graph.ALGORITHMS) this.__node.graph.ALGORITHMS = {}; if(!_id) _id = Object.keys(this.__node.graph.ALGORITHMS)[0]; //run the first key if none specified diff --git a/src/services/worker/Worker.service.ts b/src/services/worker/Worker.service.ts index d1e42aa9..be899064 100644 --- a/src/services/worker/Worker.service.ts +++ b/src/services/worker/Worker.service.ts @@ -7,6 +7,7 @@ declare var WorkerGlobalScope; export type WorkerRoute = { worker?:WorkerInfo workerUrl?: string|URL|Blob, + workerId?: string, transferFunctions?:{[key:string]:Function}, transferClasses?:{[key:string]:Function}, parentRoute?:string, //if a child of a worker node, subscribe to a route on a parent worker? @@ -33,16 +34,16 @@ export type WorkerProps = { export type WorkerInfo = { worker:Worker|MessagePort, send:(message:any,transfer?:any)=>void, - request:(message:any, method?:string,transfer?:any)=>Promise, - post:(route:any, args?:any, method?:string, transfer?:any)=>void, - run:(route:any, args?:any, method?:string,transfer?:any)=>Promise - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean, blocking?:boolean)=>Promise, + request:(message:any, transfer?:any, method?:string)=>Promise, + post:(route:any, args?:any, transfer?:any)=>void, + run:(route:any, args?:any, transfer?:any, method?:string)=>Promise + subscribe:(route:any, callback?:((res:any)=>void)|string, blocking?:boolean)=>Promise, unsubscribe:(route:any, sub:number)=>Promise, start:(route?:any, portId?:string, callback?:((res:any)=>void)|string, blocking?:boolean)=>Promise, stop:(route?:string, portId?:string)=>Promise, workerSubs:{[key:string]:{sub:number|false, route:string, portId:string, callback?:((res:any)=>void)|string, blocking?:boolean}}, terminate:()=>boolean, - postMessage:(message:any,transfer?:any[])=>void, //original worker post message + postMessage:(message:any,transfer:any[])=>void, //original worker post message graph:WorkerService, _id:string } & WorkerProps & WorkerRoute @@ -77,60 +78,62 @@ export class WorkerService extends Service { } } - loadWorkerRoute = (node:WorkerRoute & GraphNode, routeKey:string) => { - if(node.workerUrl) node.url = node.workerUrl; - if(node._id) node.__node.tag = node._id; - if(!node.__node.tag) node.__node.tag = routeKey; - node._id = node.__node.tag; + loadWorkerRoute = (rt:WorkerRoute & GraphNode,routeKey:string) => { + if(rt.workerUrl) rt.url = rt.workerUrl; + if(rt.workerId) rt.__node.tag = rt.workerId; + if(!rt.__node.tag) rt.__node.tag = routeKey; + rt._id = rt.__node.tag; let worker:WorkerInfo; - if(this.workers[node._id]) worker = this.workers[node._id]; - else if (node.worker) worker = node.worker; + if(this.workers[rt._id]) worker = this.workers[rt._id]; + else if (rt.worker) worker = rt.worker; if(!worker) { - worker = this.addWorker(node); + worker = this.addWorker(rt); + } - node.worker = worker; + rt.worker = worker; - if(!node.__ondisconnected) { + if(!rt.worker.__ondisconnected) { let ondelete = (rt) => { //removing the original route will trigger ondelete rt.worker?.terminate(); } - node.__addOndisconnected(ondelete); + const root = rt.__node + root.addOnDisconnected(ondelete); } //console.log(rt); - //requires remoteGraphRoutes on the worker (enabled on the default worker) - if(node.transferFunctions) { - for(const prop in node.transferFunctions) { - this.transferFunction(worker,node.transferFunctions[prop],prop) + //requires unsafeRoutes on the worker (enabled on the default worker) + if(rt.transferFunctions) { + for(const prop in rt.transferFunctions) { + this.transferFunction(worker,rt.transferFunctions[prop],prop) } } - if(node.transferClasses) { - for(const prop in node.transferClasses) { - this.transferClass(worker,node.transferClasses[prop],prop) + if(rt.transferClasses) { + for(const prop in rt.transferClasses) { + this.transferClass(worker,rt.transferClasses[prop],prop) } } if(worker) { - if(!node.__operator) { - node.__operator = (...args) => { + if(!rt.__operator) { + rt.__operator = (...args) => { //console.log('operator', args) - if(node.callback) { - if(!this.__node.nodes.get(node.__node.tag)?.__children) worker.post(node.callback,args); - else return worker.run(node.callback,args); + if(rt.callback) { + if(!this.__node.nodes.get(rt.__node.tag)?.__children) worker.post(rt.callback,args); + else return worker.run(rt.callback,args); } else { - if(!this.__node.nodes.get(node.__node.tag)?.__children) worker.send(args); + if(!this.__node.nodes.get(rt.__node.tag)?.__children) worker.send(args); else return worker.request(args); } } } - if(node.init) { //requires remoteGraphRoutes - worker.run(node.init,node.initArgs,undefined,node.initTransfer); + if(rt.init) { //requires unsafeRoutes + worker.run(rt.init,rt.initArgs,rt.initTransfer); } - // //need remoteGraphRoutes loaded + // //need unsafeRoutes loaded // worker.run('setValue',[rt.callback+'_routeProxy', rt.callback]); // this.transferFunction( @@ -158,11 +161,11 @@ export class WorkerService extends Service { } } - workerloader:any = { //todo: clean this up and extrapolate to other services + workerloader:any = { 'workers':(node: WorkerRoute & GraphNode, parent:WorkerRoute & GraphNode, graph:Graph, roots:any) => { let rt = node as WorkerRoute; if(!node.parentRoute && (parent?.callback && parent?.worker)) node.parentRoute = parent?.callback; - if(rt?.worker || (rt?._id && this.workers[rt._id]) || (rt as WorkerRoute)?.workerUrl) { //each set of props with a worker will instantiate a new worker, else you can use the same worker elsewhere by passing the corresponding tag + if(rt?.worker || rt?.workerId || (rt as WorkerRoute)?.workerUrl) { //each set of props with a worker will instantiate a new worker, else you can use the same worker elsewhere by passing the corresponding tag let worker = this.loadWorkerRoute(rt as any, rt.__node.tag); @@ -173,19 +176,19 @@ export class WorkerService extends Service { if(rt.__node.tag !== rt.__parent && worker._id !== rt.__parent) rt.portId = this.establishMessageChannel(worker, rt.__parent) as string; } - else if(rt.__node.tag !== rt.__parent?.__node?.tag && worker._id !== rt.__parent?.tag) { + else if(rt.__node.tag !== rt.__parent?.__node?.tag && worker._id !== rt.__parent.tag) { rt.portId = this.establishMessageChannel(worker, (rt.__parent as any).worker) as string; } }; if(rt.parentRoute) { if(!rt.stopped) { if(typeof rt.__parent === 'string' && rt.__parent === worker._id) { - worker.run('subscribe', [rt.parentRoute, undefined, undefined, rt.callback]); + worker.run('subscribe', [rt.parentRoute, undefined, rt.callback]); } else if(rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag) { - worker.run('subscribe', [rt.parentRoute, undefined, undefined, rt.callback]); + worker.run('subscribe', [rt.parentRoute, undefined, rt.callback]); } - else worker.run('subscribeToWorker', [rt.parentRoute, rt.portId, undefined, rt.callback, undefined, undefined, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId + else worker.run('subscribeToWorker', [rt.parentRoute, rt.portId, rt.callback, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId worker.workerSubs[rt.parentRoute+rt.portId].sub = sub; }); } @@ -197,7 +200,7 @@ export class WorkerService extends Service { if(rt.__parent === worker._id) { worker.run('subscribe', [rt.__parent, undefined, rt.callback]); } - else worker.run('subscribeToWorker', [rt.__parent, rt.portId, undefined, rt.callback, undefined, undefined, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId + else worker.run('subscribeToWorker', [rt.__parent, rt.portId, rt.callback, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId worker.workerSubs[rt.__parent+rt.portId].sub = sub; }); } @@ -208,9 +211,9 @@ export class WorkerService extends Service { //console.log(rt); if(!rt.stopped) { if(rt.__node.tag === rt.__parent.__node.tag || worker._id === rt.__parent.__node.tag) { - worker.run('subscribe', [rt.__parent.__node.tag, undefined, undefined, rt.callback]); + worker.run('subscribe', [rt.__parent.__node.tag, undefined, rt.callback]); } - else worker.run('subscribeToWorker', [rt.__parent.__node.tag, rt.portId, undefined, rt.callback, undefined, undefined, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId + else worker.run('subscribeToWorker', [rt.__parent.__node.tag, rt.portId, rt.callback, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub = sub; }); } @@ -222,9 +225,9 @@ export class WorkerService extends Service { } } else if(rt.__parent && rt.parentRoute) { if(typeof rt.__parent === 'string' && (roots[rt.__parent] as any)?.worker) { - ((roots[rt.__parent] as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, undefined, undefined, undefined, rt.blocking); + ((roots[rt.__parent] as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, rt.blocking); } else if((rt.__parent as any)?.worker) { - ((rt.__parent as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, undefined, undefined, undefined, rt.blocking); + ((rt.__parent as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, rt.blocking); } } //console.log(rt); @@ -238,7 +241,6 @@ export class WorkerService extends Service { let result = this.receive(ev.data); //this will handle graph logic and can run requests for the window or messsage ports etc etc. //console.log(JSON.stringify(ev.data), JSON.stringify(result),JSON.stringify(Array.from((self as any).SERVICE.nodes.keys()))) //console.log(result); - if(this.__node.keepState) this.setState({[this.name]:result}); //subscribe to all outputs } //this will work for iframes too } @@ -281,7 +283,7 @@ export class WorkerService extends Service { return this.transmit(message,worker,transfer); } - let post = (route:any,args?:any,method?:string, transfer?:any) => { + let post = (route:any,args?:any,transfer?:any, method?:string) => { //console.log('sent', message) let message:any = { route, @@ -292,7 +294,7 @@ export class WorkerService extends Service { return this.transmit(message,worker,transfer); } - let run = (route:any, args?:any, method?:string, transfer?:any) => { + let run = (route:any,args?:any, transfer?:any, method?:string) => { return new Promise ((res,rej) => { let callbackId = Math.random(); let req = {route:'runRequest', args:[{route, args}, options._id, callbackId]} as any; @@ -312,7 +314,7 @@ export class WorkerService extends Service { }); } - let request = (message:ServiceMessage|any, method?:string, transfer?:any) => { + let request = (message:ServiceMessage|any, transfer?:any, method?:string) => { return new Promise ((res,rej) => { let callbackId = Math.random(); let req = {route:'runRequest', args:[message,options._id,callbackId]} as any; @@ -334,8 +336,8 @@ export class WorkerService extends Service { let workerSubs = {}; //subscribe to this worker from the thread running this function - let subscribe = (route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean, blocking?:boolean) => { - return this.subscribeToWorker(route, options._id, callback, args, key, subInput, blocking); + let subscribe = (route:any, callback?:((res:any)=>void)|string, blocking?:boolean) => { + return this.subscribeToWorker(route, options._id, callback, blocking); } let unsubscribe = (route:any, sub:number):Promise => { @@ -345,12 +347,12 @@ export class WorkerService extends Service { //start a subscription to another worker/main thread on this worker let start = async (route?:string, portId?:string, callback?:string, blocking?:boolean) => { if(route) - await run('subscribeToWorker',[route, portId, undefined, callback, blocking]).then((sub) => { + await run('subscribeToWorker',[route, portId, callback, blocking]).then((sub) => { if(sub) workerSubs[route+portId] = {sub, route, portId, callback, blocking}; }); else for(const key in workerSubs) { if(typeof workerSubs[key].sub !== 'number') - await run('subscribeToWorker', [workerSubs[key].route, workerSubs[key].portId, undefined, workerSubs[key].callback, undefined, workerSubs[key].blocking]).then((sub) => { + await run('subscribeToWorker', [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].callback, workerSubs[key].blocking]).then((sub) => { workerSubs[key].sub = sub; }); @@ -367,9 +369,10 @@ export class WorkerService extends Service { } else { for(const key in workerSubs) { if(typeof workerSubs[key].sub === 'number') { - await run('unpipeWorkers', [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]).then(console.log); + await run('unpipeWorkers',[workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]) } workerSubs[key].sub = false; + console.log(JSON.stringify(workerSubs)); } } return true; @@ -378,7 +381,7 @@ export class WorkerService extends Service { let terminate = () => { for(const key in workerSubs) { if(typeof workerSubs[key].sub === 'number') { - run('unpipeWorkers', [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]); + run('unpipeWorkers',[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]) } workerSubs[key].sub = false; } return this.terminate(options._id); @@ -397,11 +400,9 @@ export class WorkerService extends Service { worker.onmessage = options.onmessage; (worker as Worker).onerror = options.onerror; - - let workersettings = { + this.workers[options._id] = { worker:(worker as any), - __node:{tag:options._id}, send, post, run, @@ -417,21 +418,9 @@ export class WorkerService extends Service { ...options } as WorkerInfo; - let node = this.add(workersettings); - - this.workers[options._id] = node as GraphNode & WorkerInfo; - - node.__addOndisconnected(function() { terminate(); }); - return this.workers[options._id]; } - open = this.addWorker; //for the router - - close = () => { - globalThis.close(); //workers can terminate themselves - } - //new Worker(urlFromString) toObjectURL = (scriptTemplate:string) => { let blob = new Blob([scriptTemplate],{type:'text/javascript'}); @@ -533,34 +522,24 @@ export class WorkerService extends Service { return message; } - terminate = (worker:Worker|MessagePort|string|WorkerInfo) => { + terminate = (worker:Worker|MessagePort|string) => { let onclose; - - let str; if(typeof worker === 'string') { - str = worker; let obj = this.workers[worker]; if(obj) { delete this.workers[worker]; worker = obj.worker; if(obj.onclose) onclose = obj.onclose; } - } else if (typeof worker === 'object') { - if((worker as WorkerInfo)?._id) { - worker = (worker as WorkerInfo).worker; - delete this.workers[(worker as WorkerInfo)?._id]; - } } if(worker instanceof Worker) { worker.terminate(); if(onclose) onclose(worker); - if(str && this.get(str)) this.remove(str); return true; } if(worker instanceof MessagePort) { worker.close(); if(onclose) onclose(worker); - if(str && this.get(str)) this.remove(str); return true; } return false; @@ -630,28 +609,24 @@ export class WorkerService extends Service { }); } - runRequest = (message:ServiceMessage|any, worker:undefined|string|Worker|MessagePort, callbackId:string|number, getTransferable=true) => { - + runRequest = (message:ServiceMessage|any, worker:undefined|string|Worker|MessagePort, callbackId:string|number) => { let res = this.receive(message); - if(typeof worker === 'string' && this.workers[worker]) { if(this.workers[worker].port) worker = this.workers[worker].port; else worker = this.workers[worker].worker; } if(res instanceof Promise) { res.then((r) => { - let transfer = getTransferable ? this.getTransferable(r) : undefined; if(worker instanceof Worker || worker instanceof MessagePort) - worker.postMessage({args:r,callbackId}, transfer) + worker.postMessage({args:r,callbackId}) else if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) - globalThis.postMessage({args:r,callbackId},transfer); + globalThis.postMessage({args:r,callbackId}); }); } else { - let transfer = getTransferable ? this.getTransferable(res) : undefined; if(worker instanceof Worker || worker instanceof MessagePort) - worker.postMessage({args:res,callbackId}, transfer) + worker.postMessage({args:res,callbackId}) else if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) - globalThis.postMessage({args:res,callbackId}, transfer); + globalThis.postMessage({args:res,callbackId}); } return res; @@ -660,13 +635,10 @@ export class WorkerService extends Service { subscribeWorker = ( route:string, worker:WorkerInfo|Worker|string|MessagePort, - args?:any[], - key?:string, - subInput?:boolean, blocking?:boolean, //requires a WorkerInfo object - getTransferable:boolean=true + key?:string, + subInput?:boolean ) => { - if(this.restrict?.[route]) return undefined; let callback:(res:any) => void; @@ -703,23 +675,20 @@ export class WorkerService extends Service { } else { callback = (res:any) => { + //console.log('subscription triggered for', route, 'to', worker instanceof Worker ? worker : 'window', 'result:', res); if(res instanceof Promise) { res.then((r) => { - let transfer = getTransferable ? this.getTransferable(r) : undefined; - //console.log(transfer); - if((worker as Worker)?.postMessage) - (worker as Worker).postMessage({args:r,callbackId:route}, transfer) + if((worker as any)?.postMessage) + (worker as any).postMessage({args:r,callbackId:route}) else if(globalThis.postMessage) - globalThis.postMessage({args:r,callbackId:route}, transfer); + globalThis.postMessage({args:r,callbackId:route}); }); } else { - let transfer = getTransferable ? this.getTransferable(res) : undefined; - //console.log(transfer); - if((worker as Worker)?.postMessage) - (worker as Worker).postMessage({args:res,callbackId:route}, transfer) + if((worker as any)?.postMessage) + (worker as any).postMessage({args:res,callbackId:route}) else if(globalThis.postMessage) - globalThis.postMessage({args:res,callbackId:route}, transfer); + globalThis.postMessage({args:res,callbackId:route}); } } } @@ -736,18 +705,16 @@ export class WorkerService extends Service { else worker = this.workers[worker].worker; } //else we are subscribing to window - return this.subscribe(route, callback, args, key, subInput); + return this.subscribe(route,callback,key,subInput); } subscribeToWorker = ( route:string, workerId:string, callback?:((res:any)=>void)|string, - args?:any[], + blocking?:boolean, key?:string, - subInput?:boolean, - blocking?:boolean, //blocking subscriptions won't return if the subscribing thread hasn't finished with the result - getTransferable = true //auto process transfer arrays (default true) + subInput?:boolean ) => { if(typeof workerId === 'string' && this.workers[workerId]) { @@ -760,7 +727,7 @@ export class WorkerService extends Service { else callback(res.args); } }); - return this.workers[workerId].run('subscribeWorker', [route, workerId, args, key, subInput, blocking, getTransferable]); + return this.workers[workerId].run('subscribeWorker', [route, workerId, blocking, key, subInput]); } } @@ -781,18 +748,14 @@ export class WorkerService extends Service { sourceRoute:string, listenerRoute:string, portId?:string, - args?:any[], - key?:any, - subInput?:boolean, - blocking?:boolean, - getTransferable?:boolean + blocking?:boolean ) => { if(typeof sourceWorker === 'string') sourceWorker = this.workers[sourceWorker]; if(typeof listenerWorker === 'string') listenerWorker = this.workers[listenerWorker]; if(!portId) { portId = this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker) as string; } - return listenerWorker.run('subscribeToWorker',[sourceRoute,portId,listenerRoute,args,key,subInput,blocking,getTransferable]) as Promise; //just run .unsubscribe on worker2. + return listenerWorker.run('subscribeToWorker',[sourceRoute,portId,listenerRoute,blocking]) as Promise; //just run .unsubscribe on worker2. } unpipeWorkers = ( @@ -801,10 +764,32 @@ export class WorkerService extends Service { sub?:number ) => { if(typeof sourceWorker === 'string') sourceWorker = this.workers[sourceWorker]; - if(typeof sourceWorker === 'object') { - //console.log(sourceWorker,sourceRoute); + if(sourceWorker) return sourceWorker.run('unsubscribe',[sourceRoute,sub]); - } + } + + //requires unsafe service to load on other end + transferFunction(worker:WorkerInfo, fn:Function, fnName?:string) { + if(!fnName) fnName = fn.name; + return worker.request({ + route:'setRoute', + args:[ + fn.toString(), + fnName + ] + } as ServiceMessage); + } + + //requires unsafe service to load on other end + transferClass(worker:WorkerInfo, cls:Function, className?:string) { + if(!className) className = cls.name; + return worker.request({ + route:'receiveClass', + args:[ + cls.toString(), + className + ] + } as ServiceMessage); } } \ No newline at end of file diff --git a/src/services/worker/Worker.ts b/src/services/worker/Worker.ts index 97210ada..ab5c9559 100644 --- a/src/services/worker/Worker.ts +++ b/src/services/worker/Worker.ts @@ -2,7 +2,7 @@ import { WorkerService } from './Worker.service'; //import { GPUService } from '../gpu/GPU.service'; import { workerCanvasRoutes } from './WorkerCanvas'; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; import { Math2 } from 'brainsatplay-math'; //wonder if we can have a scheme to dynamic import within the services? e.g. to bring in node-only or browser-only services without additional workers @@ -13,7 +13,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope (self as any).SERVICE = new WorkerService({ services:{ workerCanvasRoutes, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading Math, Math2 } diff --git a/src/services/worker/WorkerCanvas.ts b/src/services/worker/WorkerCanvas.ts index e023b800..1c1cab3d 100644 --- a/src/services/worker/WorkerCanvas.ts +++ b/src/services/worker/WorkerCanvas.ts @@ -1,6 +1,4 @@ //provide routes for applying canvases to workers - -import worker from './canvas.worker' import { proxyElementWorkerRoutes, initProxyElement } from './ProxyListener'; declare var WorkerGlobalScope; @@ -21,7 +19,7 @@ export type WorkerCanvasTransferProps = { //defined in main thread to send to wo export type CanvasProps = { //defined in worker thread canvas:any, //offscreen canvas context?:string|CanvasRenderingContext2D|WebGL2RenderingContext|WebGLRenderingContext, - _id:string, + _id?:string, width?:number, height?:number, draw?:string|((self:any,canvas:any,context:any)=>void), @@ -29,19 +27,18 @@ export type CanvasProps = { //defined in worker thread init?:string|((self,canvas:any,context:any)=>void), clear?:string|((self,canvas:any,context:any)=>void), animating?:boolean, - preventDefault?:boolean, //we can generically prevent defaults on key events (except F1-12 for debug reasons) [key:string]:any } export type CanvasControls = { _id:string, - draw:(props?:any,transfer?:any)=>void, //if you set props they will be available on "self" or "this" in the draw functions - update:(props:{[key:string]:any},transfer?:any)=>void, + draw:(props?:any)=>void, + update:(props:{[key:string]:any})=>void, clear:()=>void, init:()=>void, stop:()=>void, start:()=>void, - set:(newDrawProps:CanvasProps,transfer?:any)=>void + set:(newDrawProps:CanvasProps)=>void } export type WorkerCanvasControls = { @@ -58,23 +55,14 @@ export type WorkerCanvas = { //this is the object stored on the worker to track update?:((self:WorkerCanvas,canvas:WorkerCanvas['canvas'],context:WorkerCanvas['context'],input:any)=>void), init?:((self:WorkerCanvas,canvas:WorkerCanvas['canvas'],context:WorkerCanvas['context'])=>void), clear?:((self:WorkerCanvas,canvas:WorkerCanvas['canvas'],context:WorkerCanvas['context'])=>void), - stop:()=>void, - start:()=>void, - set:(newDrawProps:CanvasProps,transfer?:any)=>void, - terminate:()=>void, animating:boolean, //animation will start automatically, else you can call draw conditionally [key:string]:any //any transferrable props you want to use in your animation } export function Renderer( - options:CanvasProps & { - worker?:Worker|string|Blob|MessagePort|true, - route?:string - } + options:CanvasProps & {worker?:Worker|string|Blob|MessagePort, route?:string} ) { - if(options.worker === true) { - options.worker = worker - } + if(options.worker) { let worker = options.worker; let route = options.route; @@ -85,10 +73,10 @@ export function Renderer( delete options.worker; delete options.route; - return transferCanvas(worker as any, options as WorkerCanvasTransferProps, route); + return transferCanvas(worker, options as WorkerCanvasTransferProps, route); } else { - initProxyElement(options.canvas,undefined,options._id, options.preventDefault); + initProxyElement(options.canvas,undefined,options._id); return setupCanvas(options); } } @@ -100,12 +88,11 @@ export function transferCanvas( route?:string //we can reroute from the default 'setupCanvas' e.g. for other rendering init processes like in threejs ) { - //console.log(options); if(!options) return undefined; if(!options._id) options._id = `canvas${Math.floor(Math.random()*1000000000000000)}`; - let offscreen = options.canvas instanceof OffscreenCanvas ? options.canvas : (options.canvas as any).transferControlToOffscreen(); + let offscreen = (options.canvas as any).transferControlToOffscreen(); if(!options.width) options.width = options.canvas.clientWidth; if(!options.height) options.height = options.canvas.clientHeight; @@ -114,9 +101,8 @@ export function transferCanvas( canvas:offscreen, }}; - let proxy; - if(this?.__node?.graph) proxy = this.__node.graph.run('initProxyElement', options.canvas, worker, options._id, options.preventDefault); //initiate an element proxy - else proxy = initProxyElement(options.canvas,worker,options._id, options.preventDefault); + if(this?.__node?.graph) this.__node.graph.run('initProxyElement', options.canvas, worker, options._id); //initiate an element proxy + else initProxyElement(options.canvas,worker,options._id); if(options.draw) { if(typeof options.draw === 'function') message.args.draw = options.draw.toString() @@ -135,15 +121,15 @@ export function transferCanvas( else message.args.clear = options.clear; } - let tr = [offscreen]; + let transfer = [offscreen]; if(options.transfer) { - tr.push(...options.transfer); + transfer.push(...options.transfer); delete options.transfer; } //console.log(worker,message); - worker.postMessage(message,tr); + worker.postMessage(message,transfer); //lets add some utilities to make it easy to update the thread const canvascontrols = { @@ -151,11 +137,11 @@ export function transferCanvas( width:options.width, height:options.height, worker, - draw:(props?:any,transfer?:any)=>{ - worker.postMessage({route:'drawFrame',args:[props,options._id]},transfer); + draw:(props?:any)=>{ + worker.postMessage({route:'drawFrame',args:[props,options._id]}); }, - update:(props:{[key:string]:any},transfer?:any)=>{ - worker.postMessage({route:'updateCanvas',args:[props,options._id]}, transfer); + update:(props:{[key:string]:any})=>{ + worker.postMessage({route:'updateCanvas',args:[props,options._id]}) }, clear:()=>{ worker.postMessage({route:'clearCanvas',args:options._id}) @@ -170,11 +156,10 @@ export function transferCanvas( start:()=>{ worker.postMessage({route:'startAnim',args:options._id}) }, - set:(newDrawProps:CanvasProps,transfer?:any)=>{ - worker.postMessage({route:'setDraw',args:[newDrawProps,options._id]},transfer); + set:(newDrawProps:CanvasProps)=>{ + worker.postMessage({route:'setDraw',args:[newDrawProps,options._id]}); }, terminate:()=>{ - if(proxy) proxy.terminate(); (worker as Worker).terminate(); } } @@ -201,13 +186,10 @@ export function setDraw( if(settings.canvas) { canvasopts.canvas = settings.canvas; - if(canvasopts.proxy) canvasopts.proxy.terminate(); - let proxy; //create an element proxy to add event listener functionality - if(this?.__node?.graph) proxy = this.__node.graph.run('makeProxy', canvasopts._id, canvasopts.canvas); - else proxy = proxyElementWorkerRoutes.makeProxy(canvasopts._id, canvasopts.canvas); + if(this?.__node?.graph) this.__node.graph.run('makeProxy', canvasopts._id, canvasopts.canvas); + else proxyElementWorkerRoutes.makeProxy(canvasopts._id, canvasopts.canvas); - canvasopts.proxy = proxy; //now the canvas can handle mouse and resize events, more can be implemented } if(typeof settings.context === 'string') canvasopts.context = canvasopts.canvas.getContext(settings.context); @@ -217,19 +199,19 @@ export function setDraw( if(settings.height) canvasopts.canvas.height = settings.height; if(typeof settings.draw === 'string') settings.draw = parseFunctionFromText(settings.draw); if(typeof settings.draw === 'function') { - canvasopts.draw = settings.draw.bind(settings); + canvasopts.draw = settings.draw; } if(typeof settings.update === 'string') settings.update = parseFunctionFromText(settings.update); if(typeof settings.update === 'function') { - canvasopts.update = settings.update.bind(settings); + canvasopts.update = settings.update; } if(typeof settings.init === 'string') settings.init = parseFunctionFromText(settings.init); if(typeof settings.init === 'function') { - canvasopts.init = settings.init.bind(settings); + canvasopts.init = settings.init; } if(typeof settings.clear === 'string') settings.clear = parseFunctionFromText(settings.clear); if(typeof settings.clear === 'function') { - canvasopts.clear = settings.clear.bind(settings); + canvasopts.clear = settings.clear; } return settings._id; } @@ -251,29 +233,19 @@ export function setupCanvas( typeof options.context === 'string' ? canvasOptions.context = options.canvas.getContext(options.context) : canvasOptions.context = options.context; //get the rendering context based on string passed ('animating' in options) ? canvasOptions.animating = options.animating : canvasOptions.animating = true; - let proxy; if(this?.__node?.graph?.CANVASES[canvasOptions._id]) { this.__node.graph.run('setDraw',canvasOptions); } else if(globalThis.CANVASES?.[canvasOptions._id]) { setDraw(canvasOptions); } else { - if(this?.__node?.graph) { - canvasOptions.graph = this.__node.graph; - if(!canvasOptions.__node) {canvasOptions.__node = {}} - if(!canvasOptions.__node.tag) canvasOptions.__node.tag = canvasOptions._id; - canvasOptions = this.__node.graph.add(canvasOptions); //replace with node - canvasOptions.__addOndisconnected = () => { - canvasOptions.stop(); - delete this.__node.graph.CANVASES[canvasOptions._id]; - } - } + if(this?.__node?.graph) canvasOptions.graph = this.__node.graph; if(this?.__node?.graph) this.__node.graph.CANVASES[canvasOptions._id] = canvasOptions; else globalThis.CANVASES[canvasOptions._id] = canvasOptions; //create an element proxy to add event listener functionality - if(this?.__node?.graph) proxy = this.__node.graph.run('makeProxy', canvasOptions._id, canvasOptions.canvas); - else proxy = proxyElementWorkerRoutes.makeProxy(canvasOptions._id, canvasOptions.canvas); + if(this?.__node?.graph) this.__node.graph.run('makeProxy', canvasOptions._id, canvasOptions.canvas); + else proxyElementWorkerRoutes.makeProxy(canvasOptions._id, canvasOptions.canvas); //now the canvas can handle mouse and resize events, more can be implemented if(options.width) canvasOptions.canvas.width = options.width; @@ -282,111 +254,82 @@ export function setupCanvas( if(typeof canvasOptions.draw === 'string') { canvasOptions.draw = parseFunctionFromText(canvasOptions.draw); } else if(typeof canvasOptions.draw === 'function') { - canvasOptions.draw = canvasOptions.draw.bind(canvasOptions); + canvasOptions.draw = canvasOptions.draw; } if(typeof canvasOptions.update === 'string') { canvasOptions.update = parseFunctionFromText(canvasOptions.update); } else if(typeof canvasOptions.update === 'function') { - canvasOptions.update = canvasOptions.update.bind(canvasOptions); + canvasOptions.update = canvasOptions.update; } if(typeof canvasOptions.init === 'string') { canvasOptions.init = parseFunctionFromText(canvasOptions.init); } else if(typeof canvasOptions.init === 'function') { - canvasOptions.init = canvasOptions.init.bind(canvasOptions); + canvasOptions.init = canvasOptions.init; } if(typeof canvasOptions.clear === 'string') { canvasOptions.clear = parseFunctionFromText(canvasOptions.clear); } else if(typeof canvasOptions.clear === 'function') { - canvasOptions.clear = canvasOptions.clear.bind(canvasOptions); + canvasOptions.clear = canvasOptions.clear; } - - const finishSetup = () => { - canvasOptions.stop = () => {stopAnim(canvasOptions._id);}; - canvasOptions.start = (draw?:any) => {startAnim(canvasOptions._id,draw);}; - canvasOptions.set = (settings:any) => {setDraw(settings,canvasOptions._id);} - - if(typeof canvasOptions.draw === 'function' && canvasOptions.animating) { - let draw = (s,canvas,context) => { - if(s.animating) { - let res = s.draw(s,canvas,context); - if(res?.then) { - res.then(() => { - requestAnimationFrame(()=>{ - draw(s,canvas,context); - }); - }) - } - else requestAnimationFrame(()=>{ - draw(s,canvas,context); - }); - } - } - - draw(canvasOptions, canvasOptions.canvas,canvasOptions.context); - - } + if(typeof canvasOptions.init === 'function') + (canvasOptions.init as any)(canvasOptions, canvasOptions.canvas,canvasOptions.context); - if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) - return canvasOptions._id as string; - else { - //lets add some utilities to make it easy to update the thread - const canvascontrols = { - _id:options._id, - width:options.width, - height:options.height, - proxy, - draw:(props?:any)=>{ - drawFrame(props,options._id); - }, - update:(props:{[key:string]:any})=>{ - updateCanvas(props,options._id); - }, - clear:()=>{ - clearCanvas(options._id); - }, - init:()=>{ - //console.log('Posting init') - initCanvas(options._id); - }, - stop:()=>{ - stopAnim(options._id); - }, - start:()=>{ - startAnim(options._id); - }, - set:(newDrawProps:CanvasProps)=>{ - setDraw(newDrawProps,options._id); - }, - terminate:()=>{ - if(canvascontrols.proxy) { - canvascontrols.proxy.terminate(); - } - if(this.__node?.graph) this.__node.graph.remove(options._id); - else { - stopAnim(options._id); - if(this?.__node?.graph) delete this.__node.graph.CANVASES[canvasOptions._id]; - else delete globalThis.CANVASES[canvasOptions._id]; - } - } - } + canvasOptions.stop = () => {stopAnim(canvasOptions._id);}; + canvasOptions.start = (draw?:any) => {startAnim(canvasOptions._id,draw);}; + canvasOptions.set = (settings:any) => {setDraw(settings,canvasOptions._id);} - return canvascontrols as CanvasControls; + if(typeof canvasOptions.draw === 'function' && canvasOptions.animating) { + let draw = (s,canvas,context) => { + if(s.animating) { + s.draw(s,canvas,context); + requestAnimationFrame(()=>{ + draw(s,canvas,context); + }); + } } + + draw(canvasOptions, canvasOptions.canvas,canvasOptions.context); + } + } - if(typeof canvasOptions.init === 'function') { - let res = (canvasOptions.init as any)(canvasOptions, canvasOptions.canvas,canvasOptions.context); - if(res?.then) { - return new Promise((resolve) => { - res.then(()=>{ - resolve(finishSetup()) - }); - }) as Promise; - } - } - return finishSetup(); + if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) + return canvasOptions._id as string; + else { + //lets add some utilities to make it easy to update the thread + const canvascontrols = { + _id:options._id, + width:options.width, + height:options.height, + draw:(props?:any)=>{ + drawFrame(props,options._id); + }, + update:(props:{[key:string]:any})=>{ + updateCanvas(props,options._id); + }, + clear:()=>{ + clearCanvas(options._id); + }, + init:()=>{ + //console.log('Posting init') + initCanvas(options._id); + }, + stop:()=>{ + stopAnim(options._id); + }, + start:()=>{ + startAnim(options._id); + }, + set:(newDrawProps:CanvasProps)=>{ + setDraw(newDrawProps,options._id); + }, + terminate:()=>{ + stopAnim(options._id); + } + } + return canvascontrols as CanvasControls; } } @@ -440,11 +383,11 @@ export function updateCanvas(input?:any,_id?:string){ return undefined; } -export function setProps(props?:{[key:string]:any},_id?:string){ //update animation props, e.g. the radius or color of a circle you are drawing with a stored value +export function setProps(props?:{[key:string]:any},_id?:string,){ //update animation props, e.g. the radius or color of a circle you are drawing with a stored value let canvasopts = getCanvas.call(this, _id); - if(canvasopts && props) { + if(canvasopts) { Object.assign(canvasopts,props); if(props.width) canvasopts.canvas.width = props.width; if(props.height) canvasopts.canvas.height = props.height; @@ -485,20 +428,19 @@ export function startAnim(_id?:string, draw?:string|((this:any,canvas:any,contex return undefined; } -export function stopAnim(_id:string){ +export function stopAnim(_id?:string){ let canvasopts = getCanvas.call(this, _id); if(canvasopts) { canvasopts.animating = false; - if(typeof canvasopts.clear === 'function') - requestAnimationFrame(canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context)); + if(typeof canvasopts.clear === 'function') canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); return _id; } return undefined; } -export function getCanvas (_id?:string) { +function getCanvas (_id?:string) { let canvasopts; if(this?.__node?.graph) { if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; @@ -523,8 +465,7 @@ export const workerCanvasRoutes = { updateCanvas:updateCanvas, setProps:setProps, startAnim:startAnim, - stopAnim:stopAnim, - getCanvas:getCanvas + stopAnim:stopAnim }; function parseFunctionFromText(method='') { @@ -566,7 +507,4 @@ function parseFunctionFromText(method='') { return newFunc; -} - - - +} \ No newline at end of file diff --git a/src/services/wss/WSS.browser.ts b/src/services/wss/WSS.browser.ts index 6bed648f..8a274d76 100644 --- a/src/services/wss/WSS.browser.ts +++ b/src/services/wss/WSS.browser.ts @@ -1,34 +1,20 @@ -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type WSSRoute = { - socket?:WebSocketInfo - transferFunctions?:{[key:string]:Function}, - transferClasses?:{[key:string]:Function}, - parentRoute?:string, //if a child of a socket node, subscribe to a route on a parent worker? - callback?:string, //Run this route on the socket when the operator is called. If this route is a child of another node, run this node on the child worker when it receives a message. - stopped?:boolean, // Don't run the callback until we call the thread to start? E.g. for recording data periodically. - blocking?:boolean, //should the subscribed socket wait for the subscriber to resolve before sending a new result? Prevents backup and makes async processing easier - init?:string, //run a callback on the socket on socket init? - initArgs?:any[] //arguments to go with the socket init? -} & GraphNodeProperties & WebSocketProps - export type WebSocketProps = { host:string, port:number, path?:string, - debug?:boolean, onmessage?:(data:string | ArrayBufferLike | Blob | ArrayBufferView, ws:WebSocket, wsinfo:WebSocketInfo)=>void, //will use this.receive as default onopen?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, onclose?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, - onerror?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, + onerror?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void protocol?:'ws'|'wss', keepState?:boolean, type?:'socket', _id?:string, [key:string]:any -} & GraphNodeProperties +} export type WebSocketInfo = { socket:WebSocket, @@ -37,12 +23,12 @@ export type WebSocketInfo = { request:(message:any, method?:string)=>Promise, post:(route:any, args?:any)=>void, run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?: any[], key?: string, subInput?: boolean)=>any, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, unsubscribe:(route:any, sub:number)=>Promise, terminate:()=>boolean, _id?:string, graph:WSSfrontend -} & WebSocketProps & GraphNode +} & WebSocketProps //browser side websockets export class WSSfrontend extends Service { @@ -50,7 +36,7 @@ export class WSSfrontend extends Service { name='wss' sockets:{ - [key:string]:WebSocketInfo & GraphNode + [key:string]:WebSocketInfo } = { } connections = { //higher level reference for Router @@ -63,66 +49,17 @@ export class WSSfrontend extends Service { this.load(this); } - loadWebSocketRoute = (node: WebSocketProps & GraphNode) => { - let wsInfo = this.openWS(node); - - if (!wsInfo.__ondisconnected) { - wsInfo.__addOndisconnected(() => { - wsInfo.terminate(); - }); - } - - if (!node.__operator) { - node.__operator = (...args) => { - //console.log('operator', args) - if(node.callback) { - if(!this.__node.nodes.get(node.__node.tag)?.__children) wsInfo.post(node.callback,args); - else return wsInfo.run(node.callback,args); - } else { - if(!this.__node.nodes.get(node.__node.tag)?.__children) wsInfo.send(args); - else return wsInfo.request(args); - } - } - } - - if(!node.__ondisconnected) { - let ondelete = (rt) => { //removing the original route will trigger ondelete - rt?.terminate(); - } - node.__addOndisconnected(ondelete); - } - - // Additional setup or event handlers can be added here - // ... - - return wsInfo; - }; - - socketloader = { - 'websockets': (node: WebSocketProps & GraphNode, parent: WebSocketProps & GraphNode, graph: WSSfrontend, roots: any) => { - node._id = node.__node.tag; - let ws = this.loadWebSocketRoute(node); - Object.assign(node,ws); - if (parent && parent.type === 'socket') { - let parentWs = this.sockets[parent._id]; - - // Logic to subscribe child node to parent WebSocket - if (node.parentRoute) { - parentWs.subscribe(node.parentRoute, node.__operator); - } - } - } - } - openWS = ( options:WebSocketProps = { host:'localhost', port:7000, path:undefined, - protocol:'ws' + protocol:'ws', + onclose:(ev:any,socket:WebSocket,wsinfo:WebSocketInfo)=>{ + if(ev.target.url) delete this.sockets[ev.target.url]; + } } ) => { - let protocol = options.protocol; if(!protocol) protocol = 'ws'; let address = `${protocol}://${options.host}`; @@ -139,49 +76,39 @@ export class WSSfrontend extends Service { const socket = new WebSocket(address); if(!options.onmessage) { - if(!options._id) { - options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { - if(data) if(typeof data === 'string') { - if(options.debug) { - console.log("Message from ",address, ": ", data); - } - let substr = data.substring(0,8); - if(substr.includes('{') || substr.includes('[')) { - if(substr.includes('\\')) data = data.replace(/\\/g,""); - if(data[0] === '"') { data = data.substring(1,data.length-1)}; - //console.log(message) - data = JSON.parse(data); //parse stringified objects - - if(data.route === 'setId') { - this.sockets[address]._id = data.args; - - options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { //clear extra logic after id is set - if(options.debug) { - console.log("Message from ",address, ": ", data); - } - this.receive(data); - if(options.keepState) { - this.setState({[address as string]:data}); - } + if(!options._id){ + options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { + if(data) if(typeof data === 'string') { + let substr = data.substring(0,8); + if(substr.includes('{') || substr.includes('[')) { + if(substr.includes('\\')) data = data.replace(/\\/g,""); + if(data[0] === '"') { data = data.substring(1,data.length-1)}; + //console.log(message) + data = JSON.parse(data); //parse stringified objects + + if(data.route === 'setId') { + this.sockets[address]._id = data.args; + options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { //clear extra logic after id is set + this.receive(data); + if(options.keepState) { + this.setState({[address as string]:data}); } } } - } - - let res = this.receive(data); - if(options.keepState) this.setState({[address]:data}); - } //default onmessage + } + } + + let res = this.receive(data); + if(options.keepState) this.setState({[address]:data}); + } //default onmessage } else { options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo)=> { - if(options.debug) { - console.log("Message from ",(socket as WebSocket).url, ": ", data); - } this.receive(data,socket,this.sockets[address]); if(options.keepState) { this.setState({[address]:data}); } - }; + }; //clear this extra logic after id is set } } @@ -190,25 +117,9 @@ export class WSSfrontend extends Service { (this.sockets[address] as any).onmessage(ev.data, socket, this.sockets[address]); }); } - - socket.addEventListener('open',(ev)=>{ - if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(ev, socket, this.sockets[address]); - }); - - socket.addEventListener('close',(ev)=>{ - let obj = this.sockets[address]; - let onclose = obj.onclose; - - delete this.sockets[address]; //delete by default onclose (memory saving) - this.remove(address); - - if(onclose) onclose(ev,socket, obj); - - }); - - socket.addEventListener('error',(ev)=>{ - if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(ev,socket, this.sockets[address]); - }); + socket.addEventListener('open',(ev)=>{if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(ev,socket, this.sockets[address]);}); + socket.addEventListener('close',(ev)=>{if(this.sockets[address].onclose) (this.sockets[address] as any).onclose(ev,socket, this.sockets[address]);}); + socket.addEventListener('error',(ev)=>{if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(ev,socket, this.sockets[address]);}); let send = (message:ServiceMessage|any) => { @@ -230,18 +141,15 @@ export class WSSfrontend extends Service { let run = (route:any,args?:any,method?:string) => { return new Promise ((res,rej) => { let callbackId = Math.random(); - let req = { - route:'runRequest', - args:[{route, args}, this.sockets[address]._id, callbackId] - } as any; + let req = {route:'runRequest', args:[{route, args}, options._id, callbackId]} as any; + //console.log(req) if(method) req.args[0].method = method; let onmessage = (ev)=>{ - let data = ev.data; - if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(ev.data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { + if(typeof ev.data === 'string' && ev.data.indexOf('{') > -1) ev.data = JSON.parse(ev.data); + if(typeof ev.data === 'object') { + if(ev.data.callbackId === callbackId) { socket.removeEventListener('message',onmessage); - res(data.args); //resolve the request with the corresponding message + res(ev.data.args); //resolve the request with the corresponding message } } } @@ -253,16 +161,15 @@ export class WSSfrontend extends Service { let request = (message:ServiceMessage|any, method?:string) => { return new Promise ((res,rej) => { let callbackId = Math.random(); - let req = {route:'runRequest', args:[message, this.sockets[address]._id, callbackId]} as any; + let req = {route:'runRequest', args:[message,options._id,callbackId]} as any; //console.log(req) if(method) req.method = method; let onmessage = (ev)=>{ - let data = ev.data; - if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(ev.data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { + if(typeof ev.data === 'string' && ev.data.indexOf('{') > -1) ev.data = JSON.parse(ev.data); + if(typeof ev.data === 'object') { + if(ev.data.callbackId === callbackId) { socket.removeEventListener('message',onmessage); - res(data.args); //resolve the request with the corresponding message + res(ev.data.args); //resolve the request with the corresponding message } } } @@ -271,8 +178,8 @@ export class WSSfrontend extends Service { }); } - let subscribe = (route:any, callback?:((res:any)=>void)|string, args?: any[], key?: string, subInput?: boolean):Promise => { - return this.subscribeToSocket(route, this.sockets[address]._id, callback, args, key, subInput); + let subscribe = (route:any, callback?:((res:any)=>void)|string):Promise => { + return this.subscribeToSocket(route, options._id, callback); } let unsubscribe = (route:any, sub:number):Promise => { @@ -280,10 +187,10 @@ export class WSSfrontend extends Service { } let terminate = () => { - return this.terminate(address); + return this.terminate(options._id); } - Object.assign(options, { + this.sockets[address] = { type:'socket', socket, address, @@ -293,18 +200,12 @@ export class WSSfrontend extends Service { request, subscribe, unsubscribe, - terminate - }); - - if(!(options instanceof GraphNode)) { - let node = this.add(options); - node.__addOndisconnected(function() { terminate(); }); - options = node as any; - } - this.sockets[address] = options as GraphNode & WebSocketInfo; - //console.log(node,this.get(address),this.sockets[address]); + terminate, + graph:this, + ...options + }; - return options as WebSocketInfo; + return this.sockets[address]; } open = this.openWS; @@ -313,48 +214,33 @@ export class WSSfrontend extends Service { data:string | ArrayBufferLike | Blob | ArrayBufferView | ServiceMessage, ws:WebSocket ) => { - if( - (typeof data === 'object' && - (((data as ServiceMessage)?.route || ((data as ServiceMessage)?.node)) || ( - typeof (data as Blob).arrayBuffer !== 'function' && - typeof (data as ArrayBufferLike).byteLength !== 'number' - ))) || typeof data === 'number' - ) data = JSON.stringify(data); + if(typeof data === 'object') data = JSON.stringify(data); if(!ws) { let s = this.sockets[Object.keys(this.sockets)[0]]; if(s) ws = s.socket; } - if(ws instanceof WebSocket && ws?.readyState === 1) ws.send(data as any); + if(ws instanceof WebSocket && ws?.readyState === 1) ws.send(data); return true; } terminate = (ws:WebSocket|string) => { - - let str; if(!ws) { - //terminate all - let keys = Object.keys(this.sockets) - for(const key in keys) { - this.terminate(key); - } + let key = Object.keys(this.sockets)[0] + if(key) ws = this.sockets[key].socket; } else if(typeof ws === 'string') { - str = ws; for(const k in this.sockets) { - if(k.includes(ws) || this.sockets[k]._id === k) { + if(k.includes(ws)) { ws = this.sockets[k].socket; break; } } } - if(ws instanceof WebSocket) { + if(ws instanceof WebSocket) if(ws.readyState === ws.OPEN) ws.close(); - - if(this.get(str ? str : ws.url)) this.remove(str ? str : ws.url); - } return true; } @@ -388,11 +274,10 @@ export class WSSfrontend extends Service { ws:WebSocket|string, callbackId:string|number ) => { //send result back - //console.log('running request', message, this.__node.nodes); let res = this.receive(message); if(typeof ws === 'string') { for(const s in this.sockets) { - if(s === ws || this.sockets[s]._id === ws) {ws = this.sockets[s].socket; break;} + if(s === ws) {ws = this.sockets[s].socket; break;} } } if(ws) { @@ -411,13 +296,12 @@ export class WSSfrontend extends Service { return res; } - subscribeSocket = (route:string, socket:WebSocket|string, args?:any[], key?:string, subInput?:boolean) => { - if(this.restrict?.[route]) return undefined; + subscribeSocket = (route:string, socket:WebSocket|string, key?:string, subInput?:boolean) => { if(typeof socket === 'string' && this.sockets[socket]) { socket = this.sockets[socket].socket; } - if(typeof socket === 'object') { + if(typeof socket === 'object') return this.subscribe(route, (res:any) => { //console.log('running request', message, 'for worker', worker, 'callback', callbackId) if((socket as WebSocket).readyState === (socket as WebSocket).OPEN) { @@ -429,11 +313,10 @@ export class WSSfrontend extends Service { (socket as WebSocket).send(JSON.stringify({args:res, callbackId:route})); } } - },args,key,subInput); - } + },key,subInput); } - subscribeToSocket = (route:string, socketId:string, callback?:((res:any)=>void)|string, args?:any[], key?:string,subInput?:boolean) => { + subscribeToSocket = (route:string, socketId:string, callback?:((res:any)=>void)|string, key?:string, subInput?:boolean) => { if(typeof socketId === 'string' && this.sockets[socketId]) { this.__node.state.subscribeEvent(socketId, (res) => { let msg = JSON.parse(res); @@ -445,7 +328,7 @@ export class WSSfrontend extends Service { else callback(msg.args); } }); - return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId, args, key,subInput]}); + return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId,key,subInput]}); } } diff --git a/src/services/wss/WSS.node.ts b/src/services/wss/WSS.node.ts index 544732e4..1ad69279 100644 --- a/src/services/wss/WSS.node.ts +++ b/src/services/wss/WSS.node.ts @@ -1,17 +1,14 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import WebSocket, { PerMessageDeflateOptions, WebSocketServer } from 'ws'; //third party lib. //createWebSocketStream <-- use this for cross-node instance communication +import WebSocket, { WebSocketServer } from 'ws'; //third party lib. //createWebSocketStream <-- use this for cross-node instance communication import http from 'http' import https from 'https' -import { GraphNodeProperties } from "../../core/Graph"; //import { GraphNode } from "../Graph"; export type SocketServerProps = { - server?:http.Server|https.Server|true, //set to true to indicate you want a wss when using the open() command if not providing a server... - port?:7000|number, - path?:'wss'|'hotreload'|'python'|string, - noServer?:boolean, - host?:'localhost'|'127.0.0.1'|string, //for matching upgrade urls - perMessageDeflate?:PerMessageDeflateOptions, + server:http.Server|https.Server, + host:'localhost'|'127.0.0.1'|string, + port:7000|number, + path:'wss'|'hotreload'|'python'|string, onmessage?:(data:any, ws:WebSocket, serverinfo:SocketServerInfo)=>void, onclose?:(wss:WebSocketServer, serverinfo:SocketServerInfo)=>void, onconnection?:(ws:WebSocket,request:http.IncomingMessage, serverinfo:SocketServerInfo, clientId:string)=>void, @@ -20,10 +17,8 @@ export type SocketServerProps = { onupgrade?:(ws:WebSocket, serverinfo:SocketServerInfo, request:http.IncomingMessage, socket:any, head:Buffer)=>void, //after handleUpgrade is called keepState?:boolean, type?:'wss', - debug?:boolean - serverOptions?:WebSocket.ServerOptions, [key:string]:any -} & GraphNodeProperties +} export type SocketServerInfo = { wss:WebSocketServer, @@ -45,7 +40,6 @@ export type SocketProps = { path?:string, socket?:WebSocket, address?:string, - debug?:boolean, serverOptions?:WebSocket.ServerOptions onmessage?:(data:string | ArrayBufferLike | Blob | ArrayBufferView | Buffer[], ws:WebSocket,wsinfo:SocketProps)=>void, //will use this.receive as default onopen?:(ws:WebSocket,wsinfo:SocketProps)=>void, @@ -55,7 +49,7 @@ export type SocketProps = { type?:'socket', _id?:string, keepState?:boolean -} & GraphNodeProperties +} export type SocketInfo = { socket:WebSocket, @@ -64,7 +58,7 @@ export type SocketInfo = { request:(message:any, method?:string)=>Promise, post:(route:any, args?:any, method?:string)=>void, run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean)=>any, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, unsubscribe:(route:any, sub:number)=>Promise, terminate:()=>void, graph:WSSbackend @@ -106,35 +100,25 @@ export class WSSbackend extends Service { options:SocketServerProps, ) => { - let port = options.port; + const host = options.host; + const port = options.port; let path = options.path; - const server = typeof options.server === 'object' ? options.server : undefined; - let host = options.host; + const server = options.server; delete (options as any).server if(!('keepState' in options)) options.keepState = true; - let opts = {} as any; - if(options.noServer) opts.noServer = true; - else if(port) { - if(port) opts.port = port; - } - else if(server) opts.server = server; - if(options.perMessageDeflate) opts.perMessageDeflate = options.perMessageDeflate; + let opts = { + host, + port + }; - if(typeof options.serverOptions) Object.assign(opts,options.serverOptions); + if(typeof options.serverOptions) Object.assign(opts,options.serverOptions) const wss = new WebSocketServer(opts); - let address = ''; - if(!host && server) { - let addr = server.address() as any; - if(!port) port = addr.port; - address = addr.address; - - } else if(host) address = host; - if(port) address += ':'+port; + let address = `${host}:${port}/`; if(path) { - if(!path.startsWith('/')) path = '/'+path; + if(path.startsWith('/')) path = path.substring(1); address += path; } @@ -148,10 +132,6 @@ export class WSSbackend extends Service { if(!options.onmessage) options.onmessage = (data) => { //default onmessage if(data instanceof Buffer) data = data.toString(); - - if(options.debug) { - console.log(data); - } //console.log(data); const result = this.receive(data, wss, this.servers[address]); //console.log(result) @@ -159,7 +139,7 @@ export class WSSbackend extends Service { } - wss.addListener('connection',(ws,request) => { + wss.on('connection',(ws,request) => { if(this.debug) console.log(`New socket connection on ${address}`); let clientId = `socket${Math.floor(Math.random()*1000000000000)}`; @@ -167,28 +147,20 @@ export class WSSbackend extends Service { ws.send(JSON.stringify({ route:'setId', args:clientId })); - this.openWS({ + let info = this.openWS({ socket:ws, address:clientId, - _id:clientId, - debug:options.debug, - onclose:(code,reason) => { - if(this.servers[address].onconnectionclosed) - (this.servers[address] as any).onconnectionclosed(code, reason, ws, this.servers[address], clientId); - - delete this.servers[address].clients[clientId]; //delete by default onclose (memory saving) - } + _id:clientId }); //add send/receive etc functionality - if(options.debug) { - let time = getHoursAndMinutes(new Date()); - console.log(time, ' | ', clientId, ' | Number of live sockets: ', Object.keys(this.servers[address].clients).length); - } - if((this.servers[address] as any).onconnection) (this.servers[address] as any).onconnection(ws,request,this.servers[address], clientId);//can overwrite the default onmesssage response - + + if((this.servers[address] as any).onconnectionclosed) + ws.on('close',(code,reason)=>{ + if(this.servers[address].onconnectionclosed) (this.servers[address] as any).onconnectionclosed(code,reason,ws, this.servers[address], clientId); + }); }); wss.on('error',(err) => { @@ -197,46 +169,32 @@ export class WSSbackend extends Service { else console.error(err); }) - let onUpgrade = (request:http.IncomingMessage, socket:any, head:Buffer) => { //https://github.com/websockets/ws + let onUpgrade = (request:http.IncomingMessage,socket:any,head:Buffer) => { //https://github.com/websockets/ws if(request.headers && request.url) { if(this.debug) console.log("Upgrade request at: ", request.url); - let pass = false; - - if(path && request.url === path) pass = true; - else { - let addr = (request as any).headers.host.split(':')[0]; - if(port) addr += ':'+port; - if(addr === address) pass = true; - else { - addr += request.url.split('?')[0]; - if(addr === address) pass = true; - } - } - - if(pass && this.servers[address]) { - this.servers[address].wss.handleUpgrade(request,socket,head, (ws) => { - if((this.servers[address] as any).onupgrade) - (this.servers[address] as any).onupgrade(ws, this.servers[address], request, socket, head); - this.servers[address].wss.emit('connection', ws, request); + let addr = (request as any).headers.host.split(':')[0]; + addr += ':'+port; + addr += request.url.split('?')[0]; + + if(addr === address && this.servers[addr]) { + this.servers[addr].wss.handleUpgrade(request,socket,head, (ws) => { + if((this.servers[address] as any).onupgrade) (this.servers[address] as any).onupgrade(ws, this.servers[address], request, socket, head); + this.servers[addr].wss.emit('connection',ws,request); }); } } } - if(server) - server.addListener('upgrade', onUpgrade); + server.addListener('upgrade',onUpgrade); - wss.addListener('close',()=> { - if(server) server.removeListener('upgrade',onUpgrade); + wss.on('close',()=> { + server.removeListener('upgrade',onUpgrade); if((this.servers[address] as any).onclose) (this.servers[address] as any).onclose(wss, this.servers[address]); else console.log(`wss closed: ${address}`); - - delete this.servers[address]; }); let send = (message:any, socketId?:string) => { - if(typeof message === 'object') message = JSON.stringify(message); if(!socketId) { for(const key in this.servers[address].clients) { this.sockets[key].send(message); @@ -272,14 +230,14 @@ export class WSSbackend extends Service { } else return this.sockets[socketId].run(route,args, method); }; - let subscribe = (route:any, callback?:((res:any)=>void)|string,socketId?:string, args?:any[], key?:string, subInput?:boolean) => { + let subscribe = (route:any, callback?:((res:any)=>void)|string,socketId?:string) => { if(!socketId) { let promises:any=[] - for(const k in this.servers[address].clients) { - promises.push(this.sockets[k].subscribe(route,callback,args,key,subInput)); + for(const key in this.servers[address].clients) { + promises.push(this.sockets[key].subscribe(route,callback)); } return promises; - } else this.sockets[socketId].subscribe(route,callback,args,key,subInput); + } else this.sockets[socketId].subscribe(route,callback); }; let unsubscribe = (route:any, sub:number,socketId?:string) => { @@ -330,28 +288,11 @@ export class WSSbackend extends Service { if(!('keepState' in options)) options.keepState = true; - if(options.onmessage) { - socket.on( - 'message', - (data)=>{( - this.sockets[address] as any).onmessage( - data, - socket, - this.sockets[address] - ); - } - ); - } - + if(options.onmessage) socket.on('message',(data)=>{(this.sockets[address] as any).onmessage(data,socket,this.sockets[address]);}); else if (options._id) { - socket.addListener('message', (data:any)=> { + socket.on('message', (data:any)=> { if(ArrayBuffer.isView(data)) data = data.toString(); - - if(options.debug) { - console.log("Message from ",options._id, ": ", data); - } - - this.receive(data,socket, this.sockets[address]); + this.receive(data,socket,this.sockets[address]); //console.log('socket received',data,Array.from(this.__node.nodes.keys())); if(options.keepState) { this.setState({[address]:data}); @@ -362,9 +303,6 @@ export class WSSbackend extends Service { let socketonmessage = (data:any)=>{ if(ArrayBuffer.isView(data)) data = data.toString(); if(data) { - if(options.debug) { - console.log("Message from ",address, ": ", data); - } if(typeof data === 'string') { //pulling this out of receive to check if setId was called let substr = data.substring(0,8); if(substr.includes('{') || substr.includes('[')) { @@ -375,16 +313,9 @@ export class WSSbackend extends Service { if(data.route === 'setId') { this.sockets[address]._id = data.args; - socket.removeEventListener( - 'message', - socketonmessage - ); - + socket.removeEventListener('message',socketonmessage); socket.on('message', (data:any)=> { if(ArrayBuffer.isView(data)) data = data.toString(); - if(options.debug) { - console.log("Message from ",this.sockets[address]._id, ": ", data); - } this.receive(data,socket,this.sockets[address]); if(options.keepState) { this.setState({[address]:data}); @@ -398,27 +329,13 @@ export class WSSbackend extends Service { this.receive(data,socket,this.sockets[address]); if(options.keepState) this.setState({[address]:data}); } - socket.addListener('message',socketonmessage); //add default callback if none specified + socket.on('message',socketonmessage); //add default callback if none specified options.onmessage = socketonmessage; } - - socket.addListener('open',()=>{ - if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(socket,this.sockets[address]); - }); - - socket.addListener('close',(code,reason)=>{ - let obj = this.sockets[address]; - let onclose = obj.onclose; - - delete this.sockets[address]; //delete by default onclose (memory saving) - - if(onclose) onclose(code,reason,socket,obj); - }); - - - socket.on('error',(er)=>{ - if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(er,socket,this.sockets[address]); - }); + socket.on('open',()=>{if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(socket,this.sockets[address]);}); + socket.on('close',(code,reason)=>{ + if(this.sockets[address].onclose) (this.sockets[address] as any).onclose(code,reason,socket,this.sockets[address]);}); + socket.on('error',(er)=>{if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(er,socket,this.sockets[address]);}); let send = (message:any) => { //console.log('sent', message) @@ -439,16 +356,15 @@ export class WSSbackend extends Service { let run = (route:any,args?:any, method?:string):Promise => { return new Promise ((res,rej) => { let callbackId = Math.random(); - let req = {route:'runRequest', args:[{route, args}, this.sockets[address]._id, callbackId]} as any; + let req = {route:'runRequest', args:[{route, args}, address, callbackId]} as any; + //console.log(req) if(method) req.args[0].method = method; let onmessage = (ev)=>{ - let data = ev.data; - if(typeof data === 'string' && data.indexOf('{') > -1) - data = JSON.parse(data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { + if(typeof ev.data === 'string' && ev.data.indexOf('{') > -1) ev.data = JSON.parse(ev.data); + if(typeof ev.data === 'object') { + if(ev.data.callbackId === callbackId) { socket.removeEventListener('message',onmessage); - res(data.args); //resolve the request with the corresponding message + res(ev.data.args); //resolve the request with the corresponding message } } } @@ -458,11 +374,11 @@ export class WSSbackend extends Service { } let request = (message:ServiceMessage|any, method?:string):Promise => { - return this.request(message,socket, this.sockets[address]._id as string, method); + return this.request(message,socket, address, method); } let subscribe = (route:any, callback?:((res:any)=>void)|string) => { - return this.subscribeToSocket(route, this.sockets[address]._id as string, callback); + return this.subscribeToSocket(route, address, callback); } let unsubscribe = (route:any, sub:number):Promise => { @@ -470,7 +386,7 @@ export class WSSbackend extends Service { } let terminate = () => { - this.terminate(this.sockets[address]._id as string); + this.terminate(address); } this.sockets[address] = { @@ -484,7 +400,6 @@ export class WSSbackend extends Service { unsubscribe, terminate, graph:this, - __node:{tag:address}, ...options } @@ -495,14 +410,7 @@ export class WSSbackend extends Service { message:string | ArrayBufferLike | Blob | ArrayBufferView | Buffer[] | ServiceMessage, ws:WebSocketServer|WebSocket, ) => { - if( - (typeof message === 'object' && - (((message as ServiceMessage)?.route || ((message as ServiceMessage)?.node)) || ( - typeof (message as Blob).arrayBuffer !== 'function' && - typeof (message as ArrayBufferLike).byteLength !== 'number' && - typeof (message as Buffer[])[0]?.byteLength !== 'number' - ))) || typeof message === 'number' - ) message = JSON.stringify(message); + if(typeof message === 'object') message = JSON.stringify(message); if(!ws) { @@ -514,9 +422,9 @@ export class WSSbackend extends Service { }; } if(ws instanceof WebSocketServer) { //broadcast to all clients - ws.clients.forEach((c:WebSocket) => {c.send(message as string)}) + ws.clients.forEach((c:WebSocket) => {c.send(message)}) } - else if(ws instanceof WebSocket) ws.send(message as string); + else if(ws instanceof WebSocket) ws.send(message); } closeWS = (ws:WebSocket|string) => { @@ -542,22 +450,13 @@ export class WSSbackend extends Service { } terminate = (ws:WebSocketServer|WebSocket|string) => { - - let str; if(!ws) { - let served = Object.keys(this.servers); - for(const key in served) { - this.terminate(key); - } - let sockets = Object.keys(this.sockets); - for(const key in sockets) { - this.terminate(key) - } + let served = this.servers[Object.keys(this.servers)[0]]; + if(served) ws = served.wss; //select first websocket server to transmit to all clients } else if(typeof ws === 'string') { - str = ws; for(const k in this.servers) { - if(k.includes(ws) || this.servers[k]._id === ws) { + if(k.includes(ws)) { ws = this.servers[k].wss; for(const key in this.servers[k].clients) { this.closeWS(this.servers[k].clients[key]); @@ -568,25 +467,21 @@ export class WSSbackend extends Service { } if(!ws) { for(const k in this.sockets) { - if(k.includes(ws as string) || this.sockets[k]._id === ws) { + if(k.includes(ws as string)) { ws = this.sockets[k].socket; delete this.sockets[k]; break; } } } - } if(ws instanceof WebSocketServer) { ws.close((er) => {if(er) console.error(er);}); } - else if(ws instanceof WebSocket) { + else if(ws instanceof WebSocket) if(ws.readyState === ws.OPEN) ws.close(); - - if(this.get(str ? str : ws.url)) this.remove(str ? str : ws.url); - } return true; } @@ -620,7 +515,7 @@ export class WSSbackend extends Service { ws:WebSocket|string, callbackId:string|number ) => { //send result back - let res = this.receive(message); + let res = this.receive(message); if(ws) { if(typeof ws === 'string') { for(const key in this.servers) { @@ -633,7 +528,7 @@ export class WSSbackend extends Service { if(s === ws) {ws = this.sockets[s].socket; break;} } } - } + } if(res instanceof Promise) { res.then((v) => { @@ -652,8 +547,7 @@ export class WSSbackend extends Service { return res; } - subscribeSocket = (route:string, socket:WebSocket|string, args?:any[], key?:string, subInput?:boolean) => { - if(this.restrict?.[route]) return undefined; + subscribeSocket = (route:string, socket:WebSocket|string, key?:string, subInput?:boolean) => { if(typeof socket === 'string') { if(this.sockets[socket]) socket = this.sockets[socket].socket; else { @@ -664,7 +558,7 @@ export class WSSbackend extends Service { } } - if(typeof socket === 'object') { + if(typeof socket === 'object') return this.subscribe(route, (res:any) => { //console.log('running request', message, 'for worker', worker, 'callback', callbackId) if((socket as WebSocket).readyState === (socket as WebSocket).OPEN) { @@ -676,11 +570,10 @@ export class WSSbackend extends Service { (socket as WebSocket).send(JSON.stringify({args:res, callbackId:route})); } } - },args,key,subInput); - } + },key,subInput); } - subscribeToSocket = (route:string, socketId:string, callback?:string|((res:any)=>void), args?:any[], key?:string, subInput?:boolean) => { + subscribeToSocket = (route:string, socketId:string, callback?:string|((res:any)=>void), key?:string, subInput?:boolean) => { if(typeof socketId === 'string' && this.sockets[socketId]) { this.__node.state.subscribeEvent(socketId, (res) => { if(res?.callbackId === route) { @@ -691,26 +584,8 @@ export class WSSbackend extends Service { else callback(res.args); } }) - return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId,args,key,subInput]}); + return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId,key,subInput]}); } } -} - - - - - - - - -function getHoursAndMinutes(date) { - let hours = date.getHours(); - let minutes = date.getMinutes(); - - // Convert the hours and minutes to two digits - hours = hours < 10 ? '0' + hours : hours; - minutes = minutes < 10 ? '0' + minutes : minutes; - - return `${hours}:${minutes}`; } \ No newline at end of file diff --git a/tests/core.test.ts b/tests/core.test.ts new file mode 100644 index 00000000..8385de24 --- /dev/null +++ b/tests/core.test.ts @@ -0,0 +1,87 @@ +import * as core from '../src/core/Graph'; +import * as operations from '../examples/graph/operations' +import { OperationsManager } from './utils'; + +globalThis.graphscriptDemoLog = false + +const manager = new OperationsManager(operations) + +const globals = operations.globals + +describe(`Basic graphscript behaviors are correct`, () => { + + describe(`Nodes behave properly when instantiated on Graph instances`, () => { + + beforeAll(() => manager.start()) + afterAll(() => manager.stop()) + + test('class-based nodes are properly instantiated', () => { + const valid = manager.next() + expect(valid).toStrictEqual(true); + }); + + test('model nodes are transformed into active nodes', () => { + const update = manager.next() + + const expected = 1 + expect(update).toStrictEqual(expected); + expect(globals.state.get('nodeA', 'x')).toStrictEqual(expected); + }); + + test('the primary node behaves the same as the model node', () => { + const update = manager.next() + const expected = 2 + expect(update).toStrictEqual(expected); + expect(globals.state.get('nodeA', 'x')).toStrictEqual(expected); + expect(globals.nodeAInstance.x).toStrictEqual(expected); + }); + + test('values are appropriately listened to', () => { + const update = manager.next() + const expected = 4 + expect(update).toStrictEqual(expected); + expect(globals.state.get('nodeB', 'x')).toStrictEqual(expected); + // expect(globals.state.get('nodeA.jump')).toStrictEqual('jumped' + expected); // TODO: This returns a function for some reason in state + }); + + const nestedListenersCheck = (update, expected, subset = false) => { + const nodeA = globals.graph.get('nodeA') + expect(update).toStrictEqual(expected); + if (!subset) { + expect(globals.state.get('nodeB.nodeC')).toStrictEqual(expected); + expect(nodeA.listenerUpdates['nodeB.nodeC']).toStrictEqual(expected); + } + expect(globals.state.get('nodeB.nodeC', 'z')).toStrictEqual(expected); + expect(nodeA.listenerUpdates['nodeB.nodeC.z']).toStrictEqual(expected); + } + + // This is nodeC + test("activating a nested node's operator will trigger a function listener bound to another", () => { + const update = manager.next() + nestedListenersCheck(update, 8) + }); + + // This is nodeC.z directly + test('activating a nested node will trigger a bound listener to another', () => { + const update = manager.next() + nestedListenersCheck(update, 9, true) + }); + + const jumpCheck = (update) => { + const expected = 'jumped' + const nodeC = globals.graph.get('nodeB.nodeC') + expect(update).toStrictEqual(expected); + expect(nodeC.listenerUpdates['nodeA.jump']).toStrictEqual(expected); + } + + test('functions are appropriately listened to', () => { + const update = manager.next() + jumpCheck(update) + }); + + test('using the graph helper to call a function is equivalent to a direct function call', () => { + const update = manager.next() + jumpCheck(update) + }); + }) + }) \ No newline at end of file diff --git a/tests/utils/index.ts b/tests/utils/index.ts new file mode 100644 index 00000000..3198e436 --- /dev/null +++ b/tests/utils/index.ts @@ -0,0 +1,191 @@ +export const isNode = typeof process === 'object' + +const elId = `escomposeOperationsManagerLog` + +const document = globalThis.document + +globalThis.graphscriptDemoLog = true + +if (!isNode) { + const ol = document.createElement('ol') + ol.id = elId + document.body.appendChild(ol) + + const style = document.createElement('style') + style.innerText = ` + ol { + position: absolute; + top: 0; + right: 0; + font-size: small; + margin: 0; + padding: 0; + background-color: rgba(255, 255, 255, 0.8); + padding: 10px; + overflow: scroll; + height: 100vh; + } + + li { + margin-left: 25px; + } + ` + document.body.appendChild(style) +} + +// Maintain a list of the active states +export const log = { + element: (isNode) ? undefined : document.getElementById(elId), + add: function (message) { + if (this.element) { + var li = document.createElement('li'); + li.innerText = message; + this.element.appendChild(li); + } else if (globalThis.graphscriptDemoLog) console.log(message) + }, + addCommand: function (message) { + + if (globalThis.graphscriptDemoLog) console.log(`--------- ${message} ---------`) + if (this.element) { + var li = document.createElement('div'); + li.innerText = message; + li.style.fontWeight = 'bold'; + this.element.appendChild(li); + } + }, + addHeader: function (message) { + if (globalThis.graphscriptDemoLog) console.log(`********* ${message} *********`) + if (this.element) { + var li = document.createElement('h3'); + li.innerText = message; + this.element.appendChild(li); + } + }, +} + + +export type OperationsType = (Function | { + function: Function, + name?: string, + header?: string, + ignore?: boolean +})[] + +export type OperationsStart = Function +export type OperationsStop = Function + + +export type OperationsConfig = { + operations?: OperationsType, + start?: OperationsStart, + stop?: OperationsStop +} + + +export class OperationsManager { + + operations: OperationsType = [] + + log = log + + step = 0 + #iterations = 0 + get iterations () { + return this.#iterations + } + + set iterations (val) { + this.#iterations = val + this.step = this.#iterations % this.operations.length + if (this.step === 0) this.stop() + } + + startFunction?: OperationsStart + stopFunction?: OperationsStop + started = false + + returned: any = {} + + constructor(config: OperationsConfig = {}){ + this.set(config) + // globalThis.onkeydown = (ev) => { + // const key = ev.key + // if (key === 'Enter') this.next() + // else if (key === ' ') this.runAll() + // } + } + + set(config: OperationsConfig = {}){ + if (Array.isArray(config)) this.setOperations(config) + else { + if ('start' in config) this.setStart(config.start) + if ('operations' in config) this.setOperations(config.operations) + if ('stop' in config) this.setStop(config.stop) + } + } + + + start = (...args) => { + if (this.started) return this.returned // Already started + else { + this.started = true + if (this.startFunction) { + this.returned = this.startFunction.call(this, ...args) + return this.returned + } + } + } + + stop = (...args) => { + if (this.started) { + this.started = false + if (this.stopFunction) return this.stopFunction.call(this, ...args) + } + } + + setStart(start){ + this.started = false + this.startFunction = start + } + + setStop(stop){ + this.stopFunction = stop + } + + setOperations(operations: OperationsType = []) { + this.operations = operations + } + + + runAll = () => { + if (this.step === 0) this.next() + + while (this.step > 0) { + this.next() + } + } + + run = (command) => { + if (!this.started) this.start() + + if (typeof command === 'function') command = { + function: command, + name: command.name + } + + if (command) { + if (command.ignore) return + else { + if (command.header) log.addHeader(command.header) + if (command.name) log.addCommand(command.name) + return command.function.call(this) + } + } + } + + next = () => { + const res = this.run(this.operations[this.step]) + this.iterations++ + return res + } +} \ No newline at end of file diff --git a/tinybuild.config.js b/tinybuild.config.js index 9c673dbf..24ac98d7 100644 --- a/tinybuild.config.js +++ b/tinybuild.config.js @@ -1,40 +1,35 @@ - const config = { bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" + "examples/graph/index.js" ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags + outfile: "examples/graph/dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags //outdir:[] //exit point files, define for multiple bundle files bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: true, //create esm module js files - bundleTypes: true, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) + bundleESM: false, //create esm module js files + bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - //minify: false, - minifyWhitespace:true, - sourcemap: false - //platform:'node' //for bundling the node.ts file + minify: false, //globalThis:null //'mymodule' //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }} + //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) }, - server: false//{ //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - // debug: false, - // protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - // host: "localhost", //'localhost' or '127.0.0.1' etc. - // port: 8080, //e.g. port 80, 443, 8000 - // startpage: "index.html", //home page - // socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - // hotreload: 5000, //hotreload websocket server port - // //watch: ['../'], //watch additional directories other than the current working directory - // pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - // python: false,//7000, //quart server port (configured via the python server script file still) - // python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - // errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - // certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - // keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - // } + server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) + debug: false, + protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well + host: "localhost", //'localhost' or '127.0.0.1' etc. + port: 8000, //e.g. port 80, 443, 8000 + startpage: "index.html", //home page + socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost + hotreload: 5000, //hotreload websocket server port + //watch: ['../'], //watch additional directories other than the current working directory + pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) + python: false,//7000, //quart server port (configured via the python server script file still) + python__node: 7000, //websocket relay port (relays messages to client from nodejs that were sent to it by python) + errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. + certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions + keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions + } } - -module.exports = config; //es5 //export default config; // \ No newline at end of file +export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/todo.md b/todo.md deleted file mode 100644 index 7363da63..00000000 --- a/todo.md +++ /dev/null @@ -1,19 +0,0 @@ -## TODO - -- Make proper loaders for all of our services so they can be declared and used in the tree definitions - -- Optimize some of the remote callback system, use a single callback and just check a list of callbackIds instead of a new messageevent for every request as it will parse JSON for each callback (much more inefficient). This is only for going pedal-to-the-metal with sockets etc but why shouldn't we. - -- Make definitive benchmarks - -- Document the router etc in great detail, need to streamline it a bit more as it introduces a lot of weird options structures that are a bit convoluted. - -- fix the local struct backend, it just seems to be stringifying for some reason. - -- Forever bug testing and trying to raise things to "industry standard" without making it artificially difficult to use the whole system. We want this to be baby's first super API - -## Demos todo - -- Editor: demonstrate live editing on a multithreaded + server application - -- bring other examples more up to date, try to get closer to more typical game logic standards our examples are all made by flying by the seat of our pants and not trying to seriously model standard engine code. That's part of the point though so there's a balance to strike between creative code and familiarity. Priority 1 is readability of the logic however, as it makes complex systems that much easier to build. \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index baefe6fe..1ccf64ae 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,13 +1,13 @@ { - "include": ["index.ts"], + "include": ["build/main/index.ts"], "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, - "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + "target": "es2020" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "es2020" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, "declaration": true, /* Generates corresponding '.d.ts' file. */ - "allowJs": true, /* Allow javascript files to be compiled. */ + "allowJs": false, /* Allow javascript files to be compiled. */ "skipLibCheck": true /* Skip type checking of declaration files. */, "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */, "outDir": "./dist" /* Redirect output structure to the directory. */,
- - -
-
- - -
-
- "; - else - dialog.innerHTML = " "; - dialog.close = function() { - that.prompt_box = null; - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - var graphcanvas = LGraphCanvas.active_canvas; - var canvas = graphcanvas.canvas; - canvas.parentNode.appendChild(dialog); - - if (this.ds.scale > 1) { - dialog.style.transform = "scale(" + this.ds.scale + ")"; - } - - var dialogCloseTimer = null; - var prevent_timeout = false; - LiteGraph.pointerListenerAdd(dialog,"leave", function(e) { - if (prevent_timeout) - return; - if(LiteGraph.dialog_close_on_mouse_leave) - if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) - dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay); //dialog.close(); - }); - LiteGraph.pointerListenerAdd(dialog,"enter", function(e) { - if(LiteGraph.dialog_close_on_mouse_leave) - if(dialogCloseTimer) clearTimeout(dialogCloseTimer); - }); - var selInDia = dialog.querySelectorAll("select"); - if (selInDia){ - // if filtering, check focus changed to comboboxes and prevent closing - selInDia.forEach(function(selIn) { - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - }); - } - - if (that.prompt_box) { - that.prompt_box.close(); - } - that.prompt_box = dialog; - - var first = null; - var timeout = null; - var selected = null; - - var name_element = dialog.querySelector(".name"); - name_element.innerText = title; - var value_element = dialog.querySelector(".value"); - value_element.value = value; - - var input = value_element; - input.addEventListener("keydown", function(e) { - dialog.is_modified = true; - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13 && e.target.localName != "textarea") { - if (callback) { - callback(this.value); - } - dialog.close(); - } else { - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - - var button = dialog.querySelector("button"); - button.addEventListener("click", function(e) { - if (callback) { - callback(input.value); - } - that.setDirty(true); - dialog.close(); - }); - - var rect = canvas.getBoundingClientRect(); - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (event) { - dialog.style.left = event.clientX + offsetx + "px"; - dialog.style.top = event.clientY + offsety + "px"; - } else { - dialog.style.left = canvas.width * 0.5 + offsetx + "px"; - dialog.style.top = canvas.height * 0.5 + offsety + "px"; - } - - setTimeout(function() { - input.focus(); - }, 10); - - return dialog; - }; - - LGraphCanvas.search_limit = -1; - LGraphCanvas.prototype.showSearchBox = function(event, options) { - // proposed defaults - var def_options = { slot_from: null - ,node_from: null - ,node_to: null - ,do_type_filter: LiteGraph.search_filter_enabled // TODO check for registered_slot_[in/out]_types not empty // this will be checked for functionality enabled : filter on slot type, in and out - ,type_filter_in: false // these are default: pass to set initially set values - ,type_filter_out: false - ,show_general_if_none_on_typefilter: true - ,show_general_after_typefiltered: true - ,hide_on_mouse_leave: LiteGraph.search_hide_on_mouse_leave - ,show_all_if_empty: true - ,show_all_on_open: LiteGraph.search_show_all_on_open - }; - options = Object.assign(def_options, options || {}); - - //console.log(options); - - var that = this; - var input_html = ""; - var graphcanvas = LGraphCanvas.active_canvas; - var canvas = graphcanvas.canvas; - var root_document = canvas.ownerDocument || document; - - var dialog = document.createElement("div"); - dialog.className = "litegraph litesearchbox graphdialog rounded"; - dialog.innerHTML = "Search "; - if (options.do_type_filter){ - dialog.innerHTML += ""; - dialog.innerHTML += ""; - } - dialog.innerHTML += "
"; - - if( root_document.fullscreenElement ) - root_document.fullscreenElement.appendChild(dialog); - else - { - root_document.body.appendChild(dialog); - root_document.body.style.overflow = "hidden"; - } - // dialog element has been appended - - if (options.do_type_filter){ - var selIn = dialog.querySelector(".slot_in_type_filter"); - var selOut = dialog.querySelector(".slot_out_type_filter"); - } - - dialog.close = function() { - that.search_box = null; - this.blur(); - canvas.focus(); - root_document.body.style.overflow = ""; - - setTimeout(function() { - that.canvas.focus(); - }, 20); //important, if canvas loses focus keys wont be captured - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - if (this.ds.scale > 1) { - dialog.style.transform = "scale(" + this.ds.scale + ")"; - } - - // hide on mouse leave - if(options.hide_on_mouse_leave){ - var prevent_timeout = false; - var timeout_close = null; - LiteGraph.pointerListenerAdd(dialog,"enter", function(e) { - if (timeout_close) { - clearTimeout(timeout_close); - timeout_close = null; - } - }); - LiteGraph.pointerListenerAdd(dialog,"leave", function(e) { - if (prevent_timeout){ - return; - } - timeout_close = setTimeout(function() { - dialog.close(); - }, 500); - }); - // if filtering, check focus changed to comboboxes and prevent closing - if (options.do_type_filter){ - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - selOut.addEventListener("click", function(e) { - prevent_timeout++; - }); - selOut.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selOut.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - } - } - - if (that.search_box) { - that.search_box.close(); - } - that.search_box = dialog; - - var helper = dialog.querySelector(".helper"); - - var first = null; - var timeout = null; - var selected = null; - - var input = dialog.querySelector("input"); - if (input) { - input.addEventListener("blur", function(e) { - this.focus(); - }); - input.addEventListener("keydown", function(e) { - if (e.keyCode == 38) { - //UP - changeSelection(false); - } else if (e.keyCode == 40) { - //DOWN - changeSelection(true); - } else if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - if (selected) { - select(selected.innerHTML); - } else if (first) { - select(first); - } else { - dialog.close(); - } - } else { - if (timeout) { - clearInterval(timeout); - } - timeout = setTimeout(refreshHelper, 250); - return; - } - e.preventDefault(); - e.stopPropagation(); - e.stopImmediatePropagation(); - return true; - }); - } - - // if should filter on type, load and fill selected and choose elements if passed - if (options.do_type_filter){ - if (selIn){ - var aSlots = LiteGraph.slot_types_in; - var nSlots = aSlots.length; // this for object :: Object.keys(aSlots).length; - - if (options.type_filter_in == LiteGraph.EVENT || options.type_filter_in == LiteGraph.ACTION) - options.type_filter_in = "_event_"; - /* this will filter on * .. but better do it manually in case - else if(options.type_filter_in === "" || options.type_filter_in === 0) - options.type_filter_in = "*";*/ - - for (var iK=0; iK (rect.height - 200)) - helper.style.maxHeight = (rect.height - event.layerY - 20) + "px"; - - /* - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (event) { - dialog.style.left = event.clientX + offsetx + "px"; - dialog.style.top = event.clientY + offsety + "px"; - } else { - dialog.style.left = canvas.width * 0.5 + offsetx + "px"; - dialog.style.top = canvas.height * 0.5 + offsety + "px"; - } - canvas.parentNode.appendChild(dialog); - */ - - input.focus(); - if (options.show_all_on_open) refreshHelper(); - - function select(name) { - if (name) { - if (that.onSearchBoxSelection) { - that.onSearchBoxSelection(name, event, graphcanvas); - } else { - var extra = LiteGraph.searchbox_extras[name.toLowerCase()]; - if (extra) { - name = extra.type; - } - - graphcanvas.graph.beforeChange(); - var node = LiteGraph.createNode(name); - if (node) { - node.pos = graphcanvas.convertEventToCanvasOffset( - event - ); - graphcanvas.graph.add(node, false); - } - - if (extra && extra.data) { - if (extra.data.properties) { - for (var i in extra.data.properties) { - node.addProperty( i, extra.data.properties[i] ); - } - } - if (extra.data.inputs) { - node.inputs = []; - for (var i in extra.data.inputs) { - node.addOutput( - extra.data.inputs[i][0], - extra.data.inputs[i][1] - ); - } - } - if (extra.data.outputs) { - node.outputs = []; - for (var i in extra.data.outputs) { - node.addOutput( - extra.data.outputs[i][0], - extra.data.outputs[i][1] - ); - } - } - if (extra.data.title) { - node.title = extra.data.title; - } - if (extra.data.json) { - node.configure(extra.data.json); - } - - } - - // join node after inserting - if (options.node_from){ - var iS = false; - switch (typeof options.slot_from){ - case "string": - iS = options.node_from.findOutputSlot(options.slot_from); - break; - case "object": - if (options.slot_from.name){ - iS = options.node_from.findOutputSlot(options.slot_from.name); - }else{ - iS = -1; - } - if (iS==-1 && typeof options.slot_from.slot_index !== "undefined") iS = options.slot_from.slot_index; - break; - case "number": - iS = options.slot_from; - break; - default: - iS = 0; // try with first if no name set - } - if (typeof options.node_from.outputs[iS] !== undefined){ - if (iS!==false && iS>-1){ - options.node_from.connectByType( iS, node, options.node_from.outputs[iS].type ); - } - }else{ - // console.warn("cant find slot " + options.slot_from); - } - } - if (options.node_to){ - var iS = false; - switch (typeof options.slot_from){ - case "string": - iS = options.node_to.findInputSlot(options.slot_from); - break; - case "object": - if (options.slot_from.name){ - iS = options.node_to.findInputSlot(options.slot_from.name); - }else{ - iS = -1; - } - if (iS==-1 && typeof options.slot_from.slot_index !== "undefined") iS = options.slot_from.slot_index; - break; - case "number": - iS = options.slot_from; - break; - default: - iS = 0; // try with first if no name set - } - if (typeof options.node_to.inputs[iS] !== undefined){ - if (iS!==false && iS>-1){ - // try connection - options.node_to.connectByTypeOutput(iS,node,options.node_to.inputs[iS].type); - } - }else{ - // console.warn("cant find slot_nodeTO " + options.slot_from); - } - } - - graphcanvas.graph.afterChange(); - } - } - - dialog.close(); - } - - function changeSelection(forward) { - var prev = selected; - if (selected) { - selected.classList.remove("selected"); - } - if (!selected) { - selected = forward - ? helper.childNodes[0] - : helper.childNodes[helper.childNodes.length]; - } else { - selected = forward - ? selected.nextSibling - : selected.previousSibling; - if (!selected) { - selected = prev; - } - } - if (!selected) { - return; - } - selected.classList.add("selected"); - selected.scrollIntoView({block: "end", behavior: "smooth"}); - } - - function refreshHelper() { - timeout = null; - var str = input.value; - first = null; - helper.innerHTML = ""; - if (!str && !options.show_all_if_empty) { - return; - } - - if (that.onSearchBox) { - var list = that.onSearchBox(helper, str, graphcanvas); - if (list) { - for (var i = 0; i < list.length; ++i) { - addResult(list[i]); - } - } - } else { - var c = 0; - str = str.toLowerCase(); - var filter = graphcanvas.filter || graphcanvas.graph.filter; - - // filter by type preprocess - if(options.do_type_filter && that.search_box){ - var sIn = that.search_box.querySelector(".slot_in_type_filter"); - var sOut = that.search_box.querySelector(".slot_out_type_filter"); - }else{ - var sIn = false; - var sOut = false; - } - - //extras - for (var i in LiteGraph.searchbox_extras) { - var extra = LiteGraph.searchbox_extras[i]; - if ((!options.show_all_if_empty || str) && extra.desc.toLowerCase().indexOf(str) === -1) { - continue; - } - var ctor = LiteGraph.registered_node_types[ extra.type ]; - if( ctor && ctor.filter != filter ) - continue; - if( ! inner_test_filter(extra.type) ) - continue; - addResult( extra.desc, "searchbox_extra" ); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - - var filtered = null; - if (Array.prototype.filter) { //filter supported - var keys = Object.keys( LiteGraph.registered_node_types ); //types - var filtered = keys.filter( inner_test_filter ); - } else { - filtered = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i) ) - filtered.push(i); - } - } - - for (var i = 0; i < filtered.length; i++) { - addResult(filtered[i]); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - - // add general type if filtering - if (options.show_general_after_typefiltered - && (sIn.value || sOut.value) - ){ - filtered_extra = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i, {inTypeOverride: sIn&&sIn.value?"*":false, outTypeOverride: sOut&&sOut.value?"*":false}) ) - filtered_extra.push(i); - } - for (var i = 0; i < filtered_extra.length; i++) { - addResult(filtered_extra[i], "generic_type"); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - } - - // check il filtering gave no results - if ((sIn.value || sOut.value) && - ( (helper.childNodes.length == 0 && options.show_general_if_none_on_typefilter) ) - ){ - filtered_extra = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i, {skipFilter: true}) ) - filtered_extra.push(i); - } - for (var i = 0; i < filtered_extra.length; i++) { - addResult(filtered_extra[i], "not_in_filter"); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - } - - function inner_test_filter( type, optsIn ) - { - var optsIn = optsIn || {}; - var optsDef = { skipFilter: false - ,inTypeOverride: false - ,outTypeOverride: false - }; - var opts = Object.assign(optsDef,optsIn); - var ctor = LiteGraph.registered_node_types[ type ]; - if(filter && ctor.filter != filter ) - return false; - if ((!options.show_all_if_empty || str) && type.toLowerCase().indexOf(str) === -1) - return false; - - // filter by slot IN, OUT types - if(options.do_type_filter && !opts.skipFilter){ - var sType = type; - - var sV = sIn.value; - if (opts.inTypeOverride!==false) sV = opts.inTypeOverride; - //if (sV.toLowerCase() == "_event_") sV = LiteGraph.EVENT; // -1 - - if(sIn && sV){ - //console.log("will check filter against "+sV); - if (LiteGraph.registered_slot_in_types[sV] && LiteGraph.registered_slot_in_types[sV].nodes){ // type is stored - //console.debug("check "+sType+" in "+LiteGraph.registered_slot_in_types[sV].nodes); - var doesInc = LiteGraph.registered_slot_in_types[sV].nodes.includes(sType); - if (doesInc!==false){ - //console.log(sType+" HAS "+sV); - }else{ - /*console.debug(LiteGraph.registered_slot_in_types[sV]); - console.log(+" DONT includes "+type);*/ - return false; - } - } - } - - var sV = sOut.value; - if (opts.outTypeOverride!==false) sV = opts.outTypeOverride; - //if (sV.toLowerCase() == "_event_") sV = LiteGraph.EVENT; // -1 - - if(sOut && sV){ - //console.log("search will check filter against "+sV); - if (LiteGraph.registered_slot_out_types[sV] && LiteGraph.registered_slot_out_types[sV].nodes){ // type is stored - //console.debug("check "+sType+" in "+LiteGraph.registered_slot_out_types[sV].nodes); - var doesInc = LiteGraph.registered_slot_out_types[sV].nodes.includes(sType); - if (doesInc!==false){ - //console.log(sType+" HAS "+sV); - }else{ - /*console.debug(LiteGraph.registered_slot_out_types[sV]); - console.log(+" DONT includes "+type);*/ - return false; - } - } - } - } - return true; - } - } - - function addResult(type, className) { - var help = document.createElement("div"); - if (!first) { - first = type; - } - help.innerText = type; - help.dataset["type"] = escape(type); - help.className = "litegraph lite-search-item"; - if (className) { - help.className += " " + className; - } - help.addEventListener("click", function(e) { - select(unescape(this.dataset["type"])); - }); - helper.appendChild(help); - } - } - - return dialog; - }; - - LGraphCanvas.prototype.showEditPropertyValue = function( node, property, options ) { - if (!node || node.properties[property] === undefined) { - return; - } - - options = options || {}; - var that = this; - - var info = node.getPropertyInfo(property); - var type = info.type; - - var input_html = ""; - - if (type == "string" || type == "number" || type == "array" || type == "object") { - input_html = ""; - } else if ( (type == "enum" || type == "combo") && info.values) { - input_html = ""; - } else if (type == "boolean" || type == "toggle") { - input_html = - ""; - } else { - console.warn("unknown type: " + type); - return; - } - - var dialog = this.createDialog( - "" + - (info.label ? info.label : property) + - "" + - input_html + - "", - options - ); - - var input = false; - if ((type == "enum" || type == "combo") && info.values) { - input = dialog.querySelector("select"); - input.addEventListener("change", function(e) { - dialog.modified(); - setValue(e.target.value); - //var index = e.target.value; - //setValue( e.options[e.selectedIndex].value ); - }); - } else if (type == "boolean" || type == "toggle") { - input = dialog.querySelector("input"); - if (input) { - input.addEventListener("click", function(e) { - dialog.modified(); - setValue(!!input.checked); - }); - } - } else { - input = dialog.querySelector("input"); - if (input) { - input.addEventListener("blur", function(e) { - this.focus(); - }); - - var v = node.properties[property] !== undefined ? node.properties[property] : ""; - if (type !== 'string') { - v = JSON.stringify(v); - } - - input.value = v; - input.addEventListener("keydown", function(e) { - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - // ENTER - inner(); // save - } else if (e.keyCode != 13) { - dialog.modified(); - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - } - } - if (input) input.focus(); - - var button = dialog.querySelector("button"); - button.addEventListener("click", inner); - - function inner() { - setValue(input.value); - } - - function setValue(value) { - - if(info && info.values && info.values.constructor === Object && info.values[value] != undefined ) - value = info.values[value]; - - if (typeof node.properties[property] == "number") { - value = Number(value); - } - if (type == "array" || type == "object") { - value = JSON.parse(value); - } - node.properties[property] = value; - if (node.graph) { - node.graph._version++; - } - if (node.onPropertyChanged) { - node.onPropertyChanged(property, value); - } - if(options.onclose) - options.onclose(); - dialog.close(); - node.setDirtyCanvas(true, true); - } - - return dialog; - }; - - // TODO refactor, theer are different dialog, some uses createDialog, some dont - LGraphCanvas.prototype.createDialog = function(html, options) { - var def_options = { checkForInput: false, closeOnLeave: true, closeOnLeave_checkModified: true }; - options = Object.assign(def_options, options || {}); - - var dialog = document.createElement("div"); - dialog.className = "graphdialog"; - dialog.innerHTML = html; - dialog.is_modified = false; - - var rect = this.canvas.getBoundingClientRect(); - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (options.position) { - offsetx += options.position[0]; - offsety += options.position[1]; - } else if (options.event) { - offsetx += options.event.clientX; - offsety += options.event.clientY; - } //centered - else { - offsetx += this.canvas.width * 0.5; - offsety += this.canvas.height * 0.5; - } - - dialog.style.left = offsetx + "px"; - dialog.style.top = offsety + "px"; - - this.canvas.parentNode.appendChild(dialog); - - // acheck for input and use default behaviour: save on enter, close on esc - if (options.checkForInput){ - var aI = []; - var focused = false; - if (aI = dialog.querySelectorAll("input")){ - aI.forEach(function(iX) { - iX.addEventListener("keydown",function(e){ - dialog.modified(); - if (e.keyCode == 27) { - dialog.close(); - } else if (e.keyCode != 13) { - return; - } - // set value ? - e.preventDefault(); - e.stopPropagation(); - }); - if (!focused) iX.focus(); - }); - } - } - - dialog.modified = function(){ - dialog.is_modified = true; - } - dialog.close = function() { - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - var dialogCloseTimer = null; - var prevent_timeout = false; - dialog.addEventListener("mouseleave", function(e) { - if (prevent_timeout) - return; - if(options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) - if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) - dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay); //dialog.close(); - }); - dialog.addEventListener("mouseenter", function(e) { - if(options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) - if(dialogCloseTimer) clearTimeout(dialogCloseTimer); - }); - var selInDia = dialog.querySelectorAll("select"); - if (selInDia){ - // if filtering, check focus changed to comboboxes and prevent closing - selInDia.forEach(function(selIn) { - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - }); - } - - return dialog; - }; - - LGraphCanvas.prototype.createPanel = function(title, options) { - options = options || {}; - - var ref_window = options.window || window; - var root = document.createElement("div"); - root.className = "litegraph dialog"; - root.innerHTML = "
"; - root.header = root.querySelector(".dialog-header"); - - if(options.width) - root.style.width = options.width + (options.width.constructor === Number ? "px" : ""); - if(options.height) - root.style.height = options.height + (options.height.constructor === Number ? "px" : ""); - if(options.closable) - { - var close = document.createElement("span"); - close.innerHTML = "✕"; - close.classList.add("close"); - close.addEventListener("click",function(){ - root.close(); - }); - root.header.appendChild(close); - } - root.title_element = root.querySelector(".dialog-title"); - root.title_element.innerText = title; - root.content = root.querySelector(".dialog-content"); - root.alt_content = root.querySelector(".dialog-alt-content"); - root.footer = root.querySelector(".dialog-footer"); - - root.close = function() - { - if (root.onClose && typeof root.onClose == "function"){ - root.onClose(); - } - if(root.parentNode) - root.parentNode.removeChild(root); - /* XXX CHECK THIS */ - if(this.parentNode){ - this.parentNode.removeChild(this); - } - /* XXX this was not working, was fixed with an IF, check this */ - } - - // function to swap panel content - root.toggleAltContent = function(force){ - if (typeof force != "undefined"){ - var vTo = force ? "block" : "none"; - var vAlt = force ? "none" : "block"; - }else{ - var vTo = root.alt_content.style.display != "block" ? "block" : "none"; - var vAlt = root.alt_content.style.display != "block" ? "none" : "block"; - } - root.alt_content.style.display = vTo; - root.content.style.display = vAlt; - } - - root.toggleFooterVisibility = function(force){ - if (typeof force != "undefined"){ - var vTo = force ? "block" : "none"; - }else{ - var vTo = root.footer.style.display != "block" ? "block" : "none"; - } - root.footer.style.display = vTo; - } - - root.clear = function() - { - this.content.innerHTML = ""; - } - - root.addHTML = function(code, classname, on_footer) - { - var elem = document.createElement("div"); - if(classname) - elem.className = classname; - elem.innerHTML = code; - if(on_footer) - root.footer.appendChild(elem); - else - root.content.appendChild(elem); - return elem; - } - - root.addButton = function( name, callback, options ) - { - var elem = document.createElement("button"); - elem.innerText = name; - elem.options = options; - elem.classList.add("btn"); - elem.addEventListener("click",callback); - root.footer.appendChild(elem); - return elem; - } - - root.addSeparator = function() - { - var elem = document.createElement("div"); - elem.className = "separator"; - root.content.appendChild(elem); - } - - root.addWidget = function( type, name, value, options, callback ) - { - options = options || {}; - var str_value = String(value); - type = type.toLowerCase(); - if(type == "number") - str_value = value.toFixed(3); - - var elem = document.createElement("div"); - elem.className = "property"; - elem.innerHTML = ""; - elem.querySelector(".property_name").innerText = options.label || name; - var value_element = elem.querySelector(".property_value"); - value_element.innerText = str_value; - elem.dataset["property"] = name; - elem.dataset["type"] = options.type || type; - elem.options = options; - elem.value = value; - - if( type == "code" ) - elem.addEventListener("click", function(e){ root.inner_showCodePad( this.dataset["property"] ); }); - else if (type == "boolean") - { - elem.classList.add("boolean"); - if(value) - elem.classList.add("bool-on"); - elem.addEventListener("click", function(){ - //var v = node.properties[this.dataset["property"]]; - //node.setProperty(this.dataset["property"],!v); this.innerText = v ? "true" : "false"; - var propname = this.dataset["property"]; - this.value = !this.value; - this.classList.toggle("bool-on"); - this.querySelector(".property_value").innerText = this.value ? "true" : "false"; - innerChange(propname, this.value ); - }); - } - else if (type == "string" || type == "number") - { - value_element.setAttribute("contenteditable",true); - value_element.addEventListener("keydown", function(e){ - if(e.code == "Enter" && (type != "string" || !e.shiftKey)) // allow for multiline - { - e.preventDefault(); - this.blur(); - } - }); - value_element.addEventListener("blur", function(){ - var v = this.innerText; - var propname = this.parentNode.dataset["property"]; - var proptype = this.parentNode.dataset["type"]; - if( proptype == "number") - v = Number(v); - innerChange(propname, v); - }); - } - else if (type == "enum" || type == "combo") { - var str_value = LGraphCanvas.getPropertyPrintableValue( value, options.values ); - value_element.innerText = str_value; - - value_element.addEventListener("click", function(event){ - var values = options.values || []; - var propname = this.parentNode.dataset["property"]; - var elem_that = this; - var menu = new LiteGraph.ContextMenu(values,{ - event: event, - className: "dark", - callback: inner_clicked - }, - ref_window); - function inner_clicked(v, option, event) { - //node.setProperty(propname,v); - //graphcanvas.dirty_canvas = true; - elem_that.innerText = v; - innerChange(propname,v); - return false; - } - }); - } - - root.content.appendChild(elem); - - function innerChange(name, value) - { - //console.log("change",name,value); - //that.dirty_canvas = true; - if(options.callback) - options.callback(name,value,options); - if(callback) - callback(name,value,options); - } - - return elem; - } - - if (root.onOpen && typeof root.onOpen == "function") root.onOpen(); - - return root; - }; - - LGraphCanvas.getPropertyPrintableValue = function(value, values) - { - if(!values) - return String(value); - - if(values.constructor === Array) - { - return String(value); - } - - if(values.constructor === Object) - { - var desc_value = ""; - for(var k in values) - { - if(values[k] != value) - continue; - desc_value = k; - break; - } - return String(value) + " ("+desc_value+")"; - } - } - - LGraphCanvas.prototype.closePanels = function(){ - var panel = document.querySelector("#node-panel"); - if(panel) - panel.close(); - var panel = document.querySelector("#option-panel"); - if(panel) - panel.close(); - } - - LGraphCanvas.prototype.showShowGraphOptionsPanel = function(refOpts, obEv, refMenu, refMenu2){ - if(this.constructor && this.constructor.name == "HTMLDivElement"){ - // assume coming from the menu event click - if (!obEv || !obEv.event || !obEv.event.target || !obEv.event.target.lgraphcanvas){ - console.warn("Canvas not found"); // need a ref to canvas obj - /*console.debug(event); - console.debug(event.target);*/ - return; - } - var graphcanvas = obEv.event.target.lgraphcanvas; - }else{ - // assume called internally - var graphcanvas = this; - } - graphcanvas.closePanels(); - var ref_window = graphcanvas.getCanvasWindow(); - panel = graphcanvas.createPanel("Options",{ - closable: true - ,window: ref_window - ,onOpen: function(){ - graphcanvas.OPTIONPANEL_IS_OPEN = true; - } - ,onClose: function(){ - graphcanvas.OPTIONPANEL_IS_OPEN = false; - graphcanvas.options_panel = null; - } - }); - graphcanvas.options_panel = panel; - panel.id = "option-panel"; - panel.classList.add("settings"); - - function inner_refresh(){ - - panel.content.innerHTML = ""; //clear - - var fUpdate = function(name, value, options){ - switch(name){ - /*case "Render mode": - // Case "".. - if (options.values && options.key){ - var kV = Object.values(options.values).indexOf(value); - if (kV>=0 && options.values[kV]){ - console.debug("update graph options: "+options.key+": "+kV); - graphcanvas[options.key] = kV; - //console.debug(graphcanvas); - break; - } - } - console.warn("unexpected options"); - console.debug(options); - break;*/ - default: - //console.debug("want to update graph options: "+name+": "+value); - if (options && options.key){ - name = options.key; - } - if (options.values){ - value = Object.values(options.values).indexOf(value); - } - //console.debug("update graph option: "+name+": "+value); - graphcanvas[name] = value; - break; - } - }; - - // panel.addWidget( "string", "Graph name", "", {}, fUpdate); // implement - - var aProps = LiteGraph.availableCanvasOptions; - aProps.sort(); - for(var pI in aProps){ - var pX = aProps[pI]; - panel.addWidget( "boolean", pX, graphcanvas[pX], {key: pX, on: "True", off: "False"}, fUpdate); - } - - var aLinks = [ graphcanvas.links_render_mode ]; - panel.addWidget( "combo", "Render mode", LiteGraph.LINK_RENDER_MODES[graphcanvas.links_render_mode], {key: "links_render_mode", values: LiteGraph.LINK_RENDER_MODES}, fUpdate); - - panel.addSeparator(); - - panel.footer.innerHTML = ""; // clear - - } - inner_refresh(); - - graphcanvas.canvas.parentNode.appendChild( panel ); - } - - LGraphCanvas.prototype.showShowNodePanel = function( node ) - { - this.SELECTED_NODE = node; - this.closePanels(); - var ref_window = this.getCanvasWindow(); - var that = this; - var graphcanvas = this; - var panel = this.createPanel(node.title || "",{ - closable: true - ,window: ref_window - ,onOpen: function(){ - graphcanvas.NODEPANEL_IS_OPEN = true; - } - ,onClose: function(){ - graphcanvas.NODEPANEL_IS_OPEN = false; - graphcanvas.node_panel = null; - } - }); - graphcanvas.node_panel = panel; - panel.id = "node-panel"; - panel.node = node; - panel.classList.add("settings"); - - function inner_refresh() - { - panel.content.innerHTML = ""; //clear - panel.addHTML(""+node.type+""+(node.constructor.desc || "")+""); - - panel.addHTML("

Properties

"); - - var fUpdate = function(name,value){ - graphcanvas.graph.beforeChange(node); - switch(name){ - case "Title": - node.title = value; - break; - case "Mode": - var kV = Object.values(LiteGraph.NODE_MODES).indexOf(value); - if (kV>=0 && LiteGraph.NODE_MODES[kV]){ - node.changeMode(kV); - }else{ - console.warn("unexpected mode: "+value); - } - break; - case "Color": - if (LGraphCanvas.node_colors[value]){ - node.color = LGraphCanvas.node_colors[value].color; - node.bgcolor = LGraphCanvas.node_colors[value].bgcolor; - }else{ - console.warn("unexpected color: "+value); - } - break; - default: - node.setProperty(name,value); - break; - } - graphcanvas.graph.afterChange(); - graphcanvas.dirty_canvas = true; - }; - - panel.addWidget( "string", "Title", node.title, {}, fUpdate); - - panel.addWidget( "combo", "Mode", LiteGraph.NODE_MODES[node.mode], {values: LiteGraph.NODE_MODES}, fUpdate); - - var nodeCol = ""; - if (node.color !== undefined){ - nodeCol = Object.keys(LGraphCanvas.node_colors).filter(function(nK){ return LGraphCanvas.node_colors[nK].color == node.color; }); - } - - panel.addWidget( "combo", "Color", nodeCol, {values: Object.keys(LGraphCanvas.node_colors)}, fUpdate); - - for(var pName in node.properties) - { - var value = node.properties[pName]; - var info = node.getPropertyInfo(pName); - var type = info.type || "string"; - - //in case the user wants control over the side panel widget - if( node.onAddPropertyToPanel && node.onAddPropertyToPanel(pName,panel) ) - continue; - - panel.addWidget( info.widget || info.type, pName, value, info, fUpdate); - } - - panel.addSeparator(); - - if(node.onShowCustomPanelInfo) - node.onShowCustomPanelInfo(panel); - - panel.footer.innerHTML = ""; // clear - panel.addButton("Delete",function(){ - if(node.block_delete) - return; - node.graph.remove(node); - panel.close(); - }).classList.add("delete"); - } - - panel.inner_showCodePad = function( propname ) - { - panel.classList.remove("settings"); - panel.classList.add("centered"); - - - /*if(window.CodeFlask) //disabled for now - { - panel.content.innerHTML = "
"; - var flask = new CodeFlask( "div.code", { language: 'js' }); - flask.updateCode(node.properties[propname]); - flask.onUpdate( function(code) { - node.setProperty(propname, code); - }); - } - else - {*/ - panel.alt_content.innerHTML = ""; - var textarea = panel.alt_content.querySelector("textarea"); - var fDoneWith = function(){ - panel.toggleAltContent(false); //if(node_prop_div) node_prop_div.style.display = "block"; // panel.close(); - panel.toggleFooterVisibility(true); - textarea.parentNode.removeChild(textarea); - panel.classList.add("settings"); - panel.classList.remove("centered"); - inner_refresh(); - } - textarea.value = node.properties[propname]; - textarea.addEventListener("keydown", function(e){ - if(e.code == "Enter" && e.ctrlKey ) - { - node.setProperty(propname, textarea.value); - fDoneWith(); - } - }); - panel.toggleAltContent(true); - panel.toggleFooterVisibility(false); - textarea.style.height = "calc(100% - 40px)"; - /*}*/ - var assign = panel.addButton( "Assign", function(){ - node.setProperty(propname, textarea.value); - fDoneWith(); - }); - panel.alt_content.appendChild(assign); //panel.content.appendChild(assign); - var button = panel.addButton( "Close", fDoneWith); - button.style.float = "right"; - panel.alt_content.appendChild(button); // panel.content.appendChild(button); - } - - inner_refresh(); - - this.canvas.parentNode.appendChild( panel ); - } - - LGraphCanvas.prototype.showSubgraphPropertiesDialog = function(node) - { - console.log("showing subgraph properties dialog"); - - var old_panel = this.canvas.parentNode.querySelector(".subgraph_dialog"); - if(old_panel) - old_panel.close(); - - var panel = this.createPanel("Subgraph Inputs",{closable:true, width: 500}); - panel.node = node; - panel.classList.add("subgraph_dialog"); - - function inner_refresh() - { - panel.clear(); - - //show currents - if(node.inputs) - for(var i = 0; i < node.inputs.length; ++i) - { - var input = node.inputs[i]; - if(input.not_subgraph_input) - continue; - var html = " "; - var elem = panel.addHTML(html,"subgraph_property"); - elem.dataset["name"] = input.name; - elem.dataset["slot"] = i; - elem.querySelector(".name").innerText = input.name; - elem.querySelector(".type").innerText = input.type; - elem.querySelector("button").addEventListener("click",function(e){ - node.removeInput( Number( this.parentNode.dataset["slot"] ) ); - inner_refresh(); - }); - } - } - - //add extra - var html = " + NameType"; - var elem = panel.addHTML(html,"subgraph_property extra", true); - elem.querySelector("button").addEventListener("click", function(e){ - var elem = this.parentNode; - var name = elem.querySelector(".name").value; - var type = elem.querySelector(".type").value; - if(!name || node.findInputSlot(name) != -1) - return; - node.addInput(name,type); - elem.querySelector(".name").value = ""; - elem.querySelector(".type").value = ""; - inner_refresh(); - }); - - inner_refresh(); - this.canvas.parentNode.appendChild(panel); - return panel; - } - LGraphCanvas.prototype.showSubgraphPropertiesDialogRight = function (node) { - - // console.log("showing subgraph properties dialog"); - var that = this; - // old_panel if old_panel is exist close it - var old_panel = this.canvas.parentNode.querySelector(".subgraph_dialog"); - if (old_panel) - old_panel.close(); - // new panel - var panel = this.createPanel("Subgraph Outputs", { closable: true, width: 500 }); - panel.node = node; - panel.classList.add("subgraph_dialog"); - - function inner_refresh() { - panel.clear(); - //show currents - if (node.outputs) - for (var i = 0; i < node.outputs.length; ++i) { - var input = node.outputs[i]; - if (input.not_subgraph_output) - continue; - var html = " "; - var elem = panel.addHTML(html, "subgraph_property"); - elem.dataset["name"] = input.name; - elem.dataset["slot"] = i; - elem.querySelector(".name").innerText = input.name; - elem.querySelector(".type").innerText = input.type; - elem.querySelector("button").addEventListener("click", function (e) { - node.removeOutput(Number(this.parentNode.dataset["slot"])); - inner_refresh(); - }); - } - } - - //add extra - var html = " + NameType"; - var elem = panel.addHTML(html, "subgraph_property extra", true); - elem.querySelector(".name").addEventListener("keydown", function (e) { - if (e.keyCode == 13) { - addOutput.apply(this) - } - }) - elem.querySelector("button").addEventListener("click", function (e) { - addOutput.apply(this) - }); - function addOutput() { - var elem = this.parentNode; - var name = elem.querySelector(".name").value; - var type = elem.querySelector(".type").value; - if (!name || node.findOutputSlot(name) != -1) - return; - node.addOutput(name, type); - elem.querySelector(".name").value = ""; - elem.querySelector(".type").value = ""; - inner_refresh(); - } - - inner_refresh(); - this.canvas.parentNode.appendChild(panel); - return panel; - } - LGraphCanvas.prototype.checkPanels = function() - { - if(!this.canvas) - return; - var panels = this.canvas.parentNode.querySelectorAll(".litegraph.dialog"); - for(var i = 0; i < panels.length; ++i) - { - var panel = panels[i]; - if( !panel.node ) - continue; - if( !panel.node.graph || panel.graph != this.graph ) - panel.close(); - } - } - - LGraphCanvas.onMenuNodeCollapse = function(value, options, e, menu, node) { - node.graph.beforeChange(/*?*/); - - var fApplyMultiNode = function(node){ - node.collapse(); - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - node.graph.afterChange(/*?*/); - }; - - LGraphCanvas.onMenuNodePin = function(value, options, e, menu, node) { - node.pin(); - }; - - LGraphCanvas.onMenuNodeMode = function(value, options, e, menu, node) { - new LiteGraph.ContextMenu( - LiteGraph.NODE_MODES, - { event: e, callback: inner_clicked, parentMenu: menu, node: node } - ); - - function inner_clicked(v) { - if (!node) { - return; - } - var kV = Object.values(LiteGraph.NODE_MODES).indexOf(v); - var fApplyMultiNode = function(node){ - if (kV>=0 && LiteGraph.NODE_MODES[kV]) - node.changeMode(kV); - else{ - console.warn("unexpected mode: "+v); - node.changeMode(LiteGraph.ALWAYS); - } - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - } - - return false; - }; - - LGraphCanvas.onMenuNodeColors = function(value, options, e, menu, node) { - if (!node) { - throw "no node for color"; - } - - var values = []; - values.push({ - value: null, - content: - "No color" - }); - - for (var i in LGraphCanvas.node_colors) { - var color = LGraphCanvas.node_colors[i]; - var value = { - value: i, - content: - "" + - i + - "" - }; - values.push(value); - } - new LiteGraph.ContextMenu(values, { - event: e, - callback: inner_clicked, - parentMenu: menu, - node: node - }); - - function inner_clicked(v) { - if (!node) { - return; - } - - var color = v.value ? LGraphCanvas.node_colors[v.value] : null; - - var fApplyColor = function(node){ - if (color) { - if (node.constructor === LiteGraph.LGraphGroup) { - node.color = color.groupcolor; - } else { - node.color = color.color; - node.bgcolor = color.bgcolor; - } - } else { - delete node.color; - delete node.bgcolor; - } - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyColor(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyColor(graphcanvas.selected_nodes[i]); - } - } - node.setDirtyCanvas(true, true); - } - - return false; - }; - - LGraphCanvas.onMenuNodeShapes = function(value, options, e, menu, node) { - if (!node) { - throw "no node passed"; - } - - new LiteGraph.ContextMenu(LiteGraph.VALID_SHAPES, { - event: e, - callback: inner_clicked, - parentMenu: menu, - node: node - }); - - function inner_clicked(v) { - if (!node) { - return; - } - node.graph.beforeChange(/*?*/); //node - - var fApplyMultiNode = function(node){ - node.shape = v; - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - node.graph.afterChange(/*?*/); //node - node.setDirtyCanvas(true); - } - - return false; - }; - - LGraphCanvas.onMenuNodeRemove = function(value, options, e, menu, node) { - if (!node) { - throw "no node passed"; - } - - var graph = node.graph; - graph.beforeChange(); - - - var fApplyMultiNode = function(node){ - if (node.removable === false) { - return; - } - graph.remove(node); - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - graph.afterChange(); - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.onMenuNodeToSubgraph = function(value, options, e, menu, node) { - var graph = node.graph; - var graphcanvas = LGraphCanvas.active_canvas; - if(!graphcanvas) //?? - return; - - var nodes_list = Object.values( graphcanvas.selected_nodes || {} ); - if( !nodes_list.length ) - nodes_list = [ node ]; - - var subgraph_node = LiteGraph.createNode("graph/subgraph"); - subgraph_node.pos = node.pos.concat(); - graph.add(subgraph_node); - - subgraph_node.buildFromNodes( nodes_list ); - - graphcanvas.deselectAllNodes(); - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.onMenuNodeClone = function(value, options, e, menu, node) { - - node.graph.beforeChange(); - - var newSelected = {}; - - var fApplyMultiNode = function(node){ - if (node.clonable == false) { - return; - } - var newnode = node.clone(); - if (!newnode) { - return; - } - newnode.pos = [node.pos[0] + 5, node.pos[1] + 5]; - node.graph.add(newnode); - newSelected[newnode.id] = newnode; - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - if(Object.keys(newSelected).length){ - graphcanvas.selectNodes(newSelected); - } - - node.graph.afterChange(); - - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.node_colors = { - red: { color: "#322", bgcolor: "#533", groupcolor: "#A88" }, - brown: { color: "#332922", bgcolor: "#593930", groupcolor: "#b06634" }, - green: { color: "#232", bgcolor: "#353", groupcolor: "#8A8" }, - blue: { color: "#223", bgcolor: "#335", groupcolor: "#88A" }, - pale_blue: { - color: "#2a363b", - bgcolor: "#3f5159", - groupcolor: "#3f789e" - }, - cyan: { color: "#233", bgcolor: "#355", groupcolor: "#8AA" }, - purple: { color: "#323", bgcolor: "#535", groupcolor: "#a1309b" }, - yellow: { color: "#432", bgcolor: "#653", groupcolor: "#b58b2a" }, - black: { color: "#222", bgcolor: "#000", groupcolor: "#444" } - }; - - LGraphCanvas.prototype.getCanvasMenuOptions = function() { - var options = null; - var that = this; - if (this.getMenuOptions) { - options = this.getMenuOptions(); - } else { - options = [ - { - content: "Add Node", - has_submenu: true, - callback: LGraphCanvas.onMenuAdd - }, - { content: "Add Group", callback: LGraphCanvas.onGroupAdd }, - //{ content: "Arrange", callback: that.graph.arrange }, - //{content:"Collapse All", callback: LGraphCanvas.onMenuCollapseAll } - ]; - /*if (LiteGraph.showCanvasOptions){ - options.push({ content: "Options", callback: that.showShowGraphOptionsPanel }); - }*/ - - if (this._graph_stack && this._graph_stack.length > 0) { - options.push(null, { - content: "Close subgraph", - callback: this.closeSubgraph.bind(this) - }); - } - } - - if (this.getExtraMenuOptions) { - var extra = this.getExtraMenuOptions(this, options); - if (extra) { - options = options.concat(extra); - } - } - - return options; - }; - - //called by processContextMenu to extract the menu list - LGraphCanvas.prototype.getNodeMenuOptions = function(node) { - var options = null; - - if (node.getMenuOptions) { - options = node.getMenuOptions(this); - } else { - options = [ - { - content: "Inputs", - has_submenu: true, - disabled: true, - callback: LGraphCanvas.showMenuNodeOptionalInputs - }, - { - content: "Outputs", - has_submenu: true, - disabled: true, - callback: LGraphCanvas.showMenuNodeOptionalOutputs - }, - null, - { - content: "Properties", - has_submenu: true, - callback: LGraphCanvas.onShowMenuNodeProperties - }, - null, - { - content: "Title", - callback: LGraphCanvas.onShowPropertyEditor - }, - { - content: "Mode", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeMode - }]; - if(node.resizable !== false){ - options.push({ - content: "Resize", callback: LGraphCanvas.onMenuResizeNode - }); - } - options.push( - { - content: "Collapse", - callback: LGraphCanvas.onMenuNodeCollapse - }, - { content: "Pin", callback: LGraphCanvas.onMenuNodePin }, - { - content: "Colors", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeColors - }, - { - content: "Shapes", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeShapes - }, - null - ); - } - - if (node.onGetInputs) { - var inputs = node.onGetInputs(); - if (inputs && inputs.length) { - options[0].disabled = false; - } - } - - if (node.onGetOutputs) { - var outputs = node.onGetOutputs(); - if (outputs && outputs.length) { - options[1].disabled = false; - } - } - - if (node.getExtraMenuOptions) { - var extra = node.getExtraMenuOptions(this, options); - if (extra) { - extra.push(null); - options = extra.concat(options); - } - } - - if (node.clonable !== false) { - options.push({ - content: "Clone", - callback: LGraphCanvas.onMenuNodeClone - }); - } - - if(0) //TODO - options.push({ - content: "To Subgraph", - callback: LGraphCanvas.onMenuNodeToSubgraph - }); - - options.push(null, { - content: "Remove", - disabled: !(node.removable !== false && !node.block_delete ), - callback: LGraphCanvas.onMenuNodeRemove - }); - - if (node.graph && node.graph.onGetNodeMenuOptions) { - node.graph.onGetNodeMenuOptions(options, node); - } - - return options; - }; - - LGraphCanvas.prototype.getGroupMenuOptions = function(node) { - var o = [ - { content: "Title", callback: LGraphCanvas.onShowPropertyEditor }, - { - content: "Color", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeColors - }, - { - content: "Font size", - property: "font_size", - type: "Number", - callback: LGraphCanvas.onShowPropertyEditor - }, - null, - { content: "Remove", callback: LGraphCanvas.onMenuNodeRemove } - ]; - - return o; - }; - - LGraphCanvas.prototype.processContextMenu = function(node, event) { - var that = this; - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - - var menu_info = null; - var options = { - event: event, - callback: inner_option_clicked, - extra: node - }; - - if(node) - options.title = node.type; - - //check if mouse is in input - var slot = null; - if (node) { - slot = node.getSlotInPosition(event.canvasX, event.canvasY); - LGraphCanvas.active_node = node; - } - - if (slot) { - //on slot - menu_info = []; - if (node.getSlotMenuOptions) { - menu_info = node.getSlotMenuOptions(slot); - } else { - if ( - slot && - slot.output && - slot.output.links && - slot.output.links.length - ) { - menu_info.push({ content: "Disconnect Links", slot: slot }); - } - var _slot = slot.input || slot.output; - if (_slot.removable){ - menu_info.push( - _slot.locked - ? "Cannot remove" - : { content: "Remove Slot", slot: slot } - ); - } - if (!_slot.nameLocked){ - menu_info.push({ content: "Rename Slot", slot: slot }); - } - - } - options.title = - (slot.input ? slot.input.type : slot.output.type) || "*"; - if (slot.input && slot.input.type == LiteGraph.ACTION) { - options.title = "Action"; - } - if (slot.output && slot.output.type == LiteGraph.EVENT) { - options.title = "Event"; - } - } else { - if (node) { - //on node - menu_info = this.getNodeMenuOptions(node); - } else { - menu_info = this.getCanvasMenuOptions(); - var group = this.graph.getGroupOnPos( - event.canvasX, - event.canvasY - ); - if (group) { - //on group - menu_info.push(null, { - content: "Edit Group", - has_submenu: true, - submenu: { - title: "Group", - extra: group, - options: this.getGroupMenuOptions(group) - } - }); - } - } - } - - //show menu - if (!menu_info) { - return; - } - - var menu = new LiteGraph.ContextMenu(menu_info, options, ref_window); - - function inner_option_clicked(v, options, e) { - if (!v) { - return; - } - - if (v.content == "Remove Slot") { - var info = v.slot; - node.graph.beforeChange(); - if (info.input) { - node.removeInput(info.slot); - } else if (info.output) { - node.removeOutput(info.slot); - } - node.graph.afterChange(); - return; - } else if (v.content == "Disconnect Links") { - var info = v.slot; - node.graph.beforeChange(); - if (info.output) { - node.disconnectOutput(info.slot); - } else if (info.input) { - node.disconnectInput(info.slot); - } - node.graph.afterChange(); - return; - } else if (v.content == "Rename Slot") { - var info = v.slot; - var slot_info = info.input - ? node.getInputInfo(info.slot) - : node.getOutputInfo(info.slot); - var dialog = that.createDialog( - "Name", - options - ); - var input = dialog.querySelector("input"); - if (input && slot_info) { - input.value = slot_info.label || ""; - } - var inner = function(){ - node.graph.beforeChange(); - if (input.value) { - if (slot_info) { - slot_info.label = input.value; - } - that.setDirty(true); - } - dialog.close(); - node.graph.afterChange(); - } - dialog.querySelector("button").addEventListener("click", inner); - input.addEventListener("keydown", function(e) { - dialog.is_modified = true; - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - inner(); // save - } else if (e.keyCode != 13 && e.target.localName != "textarea") { - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - input.focus(); - } - - //if(v.callback) - // return v.callback.call(that, node, options, e, menu, that, event ); - } - }; - - //API ************************************************* - //like rect but rounded corners - if (typeof(window) != "undefined" && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) { - window.CanvasRenderingContext2D.prototype.roundRect = function( - x, - y, - w, - h, - radius, - radius_low - ) { - var top_left_radius = 0; - var top_right_radius = 0; - var bottom_left_radius = 0; - var bottom_right_radius = 0; - - if ( radius === 0 ) - { - this.rect(x,y,w,h); - return; - } - - if(radius_low === undefined) - radius_low = radius; - - //make it compatible with official one - if(radius != null && radius.constructor === Array) - { - if(radius.length == 1) - top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0]; - else if(radius.length == 2) - { - top_left_radius = bottom_right_radius = radius[0]; - top_right_radius = bottom_left_radius = radius[1]; - } - else if(radius.length == 4) - { - top_left_radius = radius[0]; - top_right_radius = radius[1]; - bottom_left_radius = radius[2]; - bottom_right_radius = radius[3]; - } - else - return; - } - else //old using numbers - { - top_left_radius = radius || 0; - top_right_radius = radius || 0; - bottom_left_radius = radius_low || 0; - bottom_right_radius = radius_low || 0; - } - - //top right - this.moveTo(x + top_left_radius, y); - this.lineTo(x + w - top_right_radius, y); - this.quadraticCurveTo(x + w, y, x + w, y + top_right_radius); - - //bottom right - this.lineTo(x + w, y + h - bottom_right_radius); - this.quadraticCurveTo( - x + w, - y + h, - x + w - bottom_right_radius, - y + h - ); - - //bottom left - this.lineTo(x + bottom_right_radius, y + h); - this.quadraticCurveTo(x, y + h, x, y + h - bottom_left_radius); - - //top left - this.lineTo(x, y + bottom_left_radius); - this.quadraticCurveTo(x, y, x + top_left_radius, y); - }; - }//if - - function compareObjects(a, b) { - for (var i in a) { - if (a[i] != b[i]) { - return false; - } - } - return true; - } - LiteGraph.compareObjects = compareObjects; - - function distance(a, b) { - return Math.sqrt( - (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]) - ); - } - LiteGraph.distance = distance; - - function colorToString(c) { - return ( - "rgba(" + - Math.round(c[0] * 255).toFixed() + - "," + - Math.round(c[1] * 255).toFixed() + - "," + - Math.round(c[2] * 255).toFixed() + - "," + - (c.length == 4 ? c[3].toFixed(2) : "1.0") + - ")" - ); - } - LiteGraph.colorToString = colorToString; - - function isInsideRectangle(x, y, left, top, width, height) { - if (left < x && left + width > x && top < y && top + height > y) { - return true; - } - return false; - } - LiteGraph.isInsideRectangle = isInsideRectangle; - - //[minx,miny,maxx,maxy] - function growBounding(bounding, x, y) { - if (x < bounding[0]) { - bounding[0] = x; - } else if (x > bounding[2]) { - bounding[2] = x; - } - - if (y < bounding[1]) { - bounding[1] = y; - } else if (y > bounding[3]) { - bounding[3] = y; - } - } - LiteGraph.growBounding = growBounding; - - //point inside bounding box - function isInsideBounding(p, bb) { - if ( - p[0] < bb[0][0] || - p[1] < bb[0][1] || - p[0] > bb[1][0] || - p[1] > bb[1][1] - ) { - return false; - } - return true; - } - LiteGraph.isInsideBounding = isInsideBounding; - - //bounding overlap, format: [ startx, starty, width, height ] - function overlapBounding(a, b) { - var A_end_x = a[0] + a[2]; - var A_end_y = a[1] + a[3]; - var B_end_x = b[0] + b[2]; - var B_end_y = b[1] + b[3]; - - if ( - a[0] > B_end_x || - a[1] > B_end_y || - A_end_x < b[0] || - A_end_y < b[1] - ) { - return false; - } - return true; - } - LiteGraph.overlapBounding = overlapBounding; - - //Convert a hex value to its decimal value - the inputted hex must be in the - // format of a hex triplet - the kind we use for HTML colours. The function - // will return an array with three values. - function hex2num(hex) { - if (hex.charAt(0) == "#") { - hex = hex.slice(1); - } //Remove the '#' char - if there is one. - hex = hex.toUpperCase(); - var hex_alphabets = "0123456789ABCDEF"; - var value = new Array(3); - var k = 0; - var int1, int2; - for (var i = 0; i < 6; i += 2) { - int1 = hex_alphabets.indexOf(hex.charAt(i)); - int2 = hex_alphabets.indexOf(hex.charAt(i + 1)); - value[k] = int1 * 16 + int2; - k++; - } - return value; - } - - LiteGraph.hex2num = hex2num; - - //Give a array with three values as the argument and the function will return - // the corresponding hex triplet. - function num2hex(triplet) { - var hex_alphabets = "0123456789ABCDEF"; - var hex = "#"; - var int1, int2; - for (var i = 0; i < 3; i++) { - int1 = triplet[i] / 16; - int2 = triplet[i] % 16; - - hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2); - } - return hex; - } - - LiteGraph.num2hex = num2hex; - - /* LiteGraph GUI elements used for canvas editing *************************************/ - - /** - * ContextMenu from LiteGUI - * - * @class ContextMenu - * @constructor - * @param {Array} values (allows object { title: "Nice text", callback: function ... }) - * @param {Object} options [optional] Some options:\ - * - title: title to show on top of the menu - * - callback: function to call when an option is clicked, it receives the item information - * - ignore_item_callbacks: ignores the callback inside the item, it just calls the options.callback - * - event: you can pass a MouseEvent, this way the ContextMenu appears in that position - */ - function ContextMenu(values, options) { - options = options || {}; - this.options = options; - var that = this; - - //to link a menu with its parent - if (options.parentMenu) { - if (options.parentMenu.constructor !== this.constructor) { - console.error( - "parentMenu must be of class ContextMenu, ignoring it" - ); - options.parentMenu = null; - } else { - this.parentMenu = options.parentMenu; - this.parentMenu.lock = true; - this.parentMenu.current_submenu = this; - } - } - - var eventClass = null; - if(options.event) //use strings because comparing classes between windows doesnt work - eventClass = options.event.constructor.name; - if ( eventClass !== "MouseEvent" && - eventClass !== "CustomEvent" && - eventClass !== "PointerEvent" - ) { - console.error( - "Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. ("+eventClass+")" - ); - options.event = null; - } - - var root = document.createElement("div"); - root.className = "litegraph litecontextmenu litemenubar-panel"; - if (options.className) { - root.className += " " + options.className; - } - root.style.minWidth = 100; - root.style.minHeight = 100; - root.style.pointerEvents = "none"; - setTimeout(function() { - root.style.pointerEvents = "auto"; - }, 100); //delay so the mouse up event is not caught by this element - - //this prevents the default context browser menu to open in case this menu was created when pressing right button - LiteGraph.pointerListenerAdd(root,"up", - function(e) { - //console.log("pointerevents: ContextMenu up root prevent"); - e.preventDefault(); - return true; - }, - true - ); - root.addEventListener( - "contextmenu", - function(e) { - if (e.button != 2) { - //right button - return false; - } - e.preventDefault(); - return false; - }, - true - ); - - LiteGraph.pointerListenerAdd(root,"down", - function(e) { - //console.log("pointerevents: ContextMenu down"); - if (e.button == 2) { - that.close(); - e.preventDefault(); - return true; - } - }, - true - ); - - function on_mouse_wheel(e) { - var pos = parseInt(root.style.top); - root.style.top = - (pos + e.deltaY * options.scroll_speed).toFixed() + "px"; - e.preventDefault(); - return true; - } - - if (!options.scroll_speed) { - options.scroll_speed = 0.1; - } - - root.addEventListener("wheel", on_mouse_wheel, true); - root.addEventListener("mousewheel", on_mouse_wheel, true); - - this.root = root; - - //title - if (options.title) { - var element = document.createElement("div"); - element.className = "litemenu-title"; - element.innerHTML = options.title; - root.appendChild(element); - } - - //entries - var num = 0; - for (var i=0; i < values.length; i++) { - var name = values.constructor == Array ? values[i] : i; - if (name != null && name.constructor !== String) { - name = name.content === undefined ? String(name) : name.content; - } - var value = values[i]; - this.addItem(name, value, options); - num++; - } - - //close on leave? touch enabled devices won't work TODO use a global device detector and condition on that - /*LiteGraph.pointerListenerAdd(root,"leave", function(e) { - console.log("pointerevents: ContextMenu leave"); - if (that.lock) { - return; - } - if (root.closing_timer) { - clearTimeout(root.closing_timer); - } - root.closing_timer = setTimeout(that.close.bind(that, e), 500); - //that.close(e); - });*/ - - LiteGraph.pointerListenerAdd(root,"enter", function(e) { - //console.log("pointerevents: ContextMenu enter"); - if (root.closing_timer) { - clearTimeout(root.closing_timer); - } - }); - - //insert before checking position - var root_document = document; - if (options.event) { - root_document = options.event.target.ownerDocument; - } - - if (!root_document) { - root_document = document; - } - - if( root_document.fullscreenElement ) - root_document.fullscreenElement.appendChild(root); - else - root_document.body.appendChild(root); - - //compute best position - var left = options.left || 0; - var top = options.top || 0; - if (options.event) { - left = options.event.clientX - 10; - top = options.event.clientY - 10; - if (options.title) { - top -= 20; - } - - if (options.parentMenu) { - var rect = options.parentMenu.root.getBoundingClientRect(); - left = rect.left + rect.width; - } - - var body_rect = document.body.getBoundingClientRect(); - var root_rect = root.getBoundingClientRect(); - if(body_rect.height == 0) - console.error("document.body height is 0. That is dangerous, set html,body { height: 100%; }"); - - if (body_rect.width && left > body_rect.width - root_rect.width - 10) { - left = body_rect.width - root_rect.width - 10; - } - if (body_rect.height && top > body_rect.height - root_rect.height - 10) { - top = body_rect.height - root_rect.height - 10; - } - } - - root.style.left = left + "px"; - root.style.top = top + "px"; - - if (options.scale) { - root.style.transform = "scale(" + options.scale + ")"; - } - } - - ContextMenu.prototype.addItem = function(name, value, options) { - var that = this; - options = options || {}; - - var element = document.createElement("div"); - element.className = "litemenu-entry submenu"; - - var disabled = false; - - if (value === null) { - element.classList.add("separator"); - //element.innerHTML = "
" - //continue; - } else { - element.innerHTML = value && value.title ? value.title : name; - element.value = value; - - if (value) { - if (value.disabled) { - disabled = true; - element.classList.add("disabled"); - } - if (value.submenu || value.has_submenu) { - element.classList.add("has_submenu"); - } - } - - if (typeof value == "function") { - element.dataset["value"] = name; - element.onclick_callback = value; - } else { - element.dataset["value"] = value; - } - - if (value.className) { - element.className += " " + value.className; - } - } - - this.root.appendChild(element); - if (!disabled) { - element.addEventListener("click", inner_onclick); - } - if (options.autoopen) { - LiteGraph.pointerListenerAdd(element,"enter",inner_over); - } - - function inner_over(e) { - var value = this.value; - if (!value || !value.has_submenu) { - return; - } - //if it is a submenu, autoopen like the item was clicked - inner_onclick.call(this, e); - } - - //menu option clicked - function inner_onclick(e) { - var value = this.value; - var close_parent = true; - - if (that.current_submenu) { - that.current_submenu.close(e); - } - - //global callback - if (options.callback) { - var r = options.callback.call( - this, - value, - options, - e, - that, - options.node - ); - if (r === true) { - close_parent = false; - } - } - - //special cases - if (value) { - if ( - value.callback && - !options.ignore_item_callbacks && - value.disabled !== true - ) { - //item callback - var r = value.callback.call( - this, - value, - options, - e, - that, - options.extra - ); - if (r === true) { - close_parent = false; - } - } - if (value.submenu) { - if (!value.submenu.options) { - throw "ContextMenu submenu needs options"; - } - var submenu = new that.constructor(value.submenu.options, { - callback: value.submenu.callback, - event: e, - parentMenu: that, - ignore_item_callbacks: - value.submenu.ignore_item_callbacks, - title: value.submenu.title, - extra: value.submenu.extra, - autoopen: options.autoopen - }); - close_parent = false; - } - } - - if (close_parent && !that.lock) { - that.close(); - } - } - - return element; - }; - - ContextMenu.prototype.close = function(e, ignore_parent_menu) { - if (this.root.parentNode) { - this.root.parentNode.removeChild(this.root); - } - if (this.parentMenu && !ignore_parent_menu) { - this.parentMenu.lock = false; - this.parentMenu.current_submenu = null; - if (e === undefined) { - this.parentMenu.close(); - } else if ( - e && - !ContextMenu.isCursorOverElement(e, this.parentMenu.root) - ) { - ContextMenu.trigger(this.parentMenu.root, LiteGraph.pointerevents_method+"leave", e); - } - } - if (this.current_submenu) { - this.current_submenu.close(e, true); - } - - if (this.root.closing_timer) { - clearTimeout(this.root.closing_timer); - } - - // TODO implement : LiteGraph.contextMenuClosed(); :: keep track of opened / closed / current ContextMenu - // on key press, allow filtering/selecting the context menu elements - }; - - //this code is used to trigger events easily (used in the context menu mouseleave - ContextMenu.trigger = function(element, event_name, params, origin) { - var evt = document.createEvent("CustomEvent"); - evt.initCustomEvent(event_name, true, true, params); //canBubble, cancelable, detail - evt.srcElement = origin; - if (element.dispatchEvent) { - element.dispatchEvent(evt); - } else if (element.__events) { - element.__events.dispatchEvent(evt); - } - //else nothing seems binded here so nothing to do - return evt; - }; - - //returns the top most menu - ContextMenu.prototype.getTopMenu = function() { - if (this.options.parentMenu) { - return this.options.parentMenu.getTopMenu(); - } - return this; - }; - - ContextMenu.prototype.getFirstEvent = function() { - if (this.options.parentMenu) { - return this.options.parentMenu.getFirstEvent(); - } - return this.options.event; - }; - - ContextMenu.isCursorOverElement = function(event, element) { - var left = event.clientX; - var top = event.clientY; - var rect = element.getBoundingClientRect(); - if (!rect) { - return false; - } - if ( - top > rect.top && - top < rect.top + rect.height && - left > rect.left && - left < rect.left + rect.width - ) { - return true; - } - return false; - }; - - LiteGraph.ContextMenu = ContextMenu; - - LiteGraph.closeAllContextMenus = function(ref_window) { - ref_window = ref_window || window; - - var elements = ref_window.document.querySelectorAll(".litecontextmenu"); - if (!elements.length) { - return; - } - - var result = []; - for (var i = 0; i < elements.length; i++) { - result.push(elements[i]); - } - - for (var i=0; i < result.length; i++) { - if (result[i].close) { - result[i].close(); - } else if (result[i].parentNode) { - result[i].parentNode.removeChild(result[i]); - } - } - }; - - LiteGraph.extendClass = function(target, origin) { - for (var i in origin) { - //copy class properties - if (target.hasOwnProperty(i)) { - continue; - } - target[i] = origin[i]; - } - - if (origin.prototype) { - //copy prototype properties - for (var i in origin.prototype) { - //only enumerable - if (!origin.prototype.hasOwnProperty(i)) { - continue; - } - - if (target.prototype.hasOwnProperty(i)) { - //avoid overwriting existing ones - continue; - } - - //copy getters - if (origin.prototype.__lookupGetter__(i)) { - target.prototype.__defineGetter__( - i, - origin.prototype.__lookupGetter__(i) - ); - } else { - target.prototype[i] = origin.prototype[i]; - } - - //and setters - if (origin.prototype.__lookupSetter__(i)) { - target.prototype.__defineSetter__( - i, - origin.prototype.__lookupSetter__(i) - ); - } - } - } - }; - - //used by some widgets to render a curve editor - function CurveEditor( points ) - { - this.points = points; - this.selected = -1; - this.nearest = -1; - this.size = null; //stores last size used - this.must_update = true; - this.margin = 5; - } - - CurveEditor.sampleCurve = function(f,points) - { - if(!points) - return; - for(var i = 0; i < points.length - 1; ++i) - { - var p = points[i]; - var pn = points[i+1]; - if(pn[0] < f) - continue; - var r = (pn[0] - p[0]); - if( Math.abs(r) < 0.00001 ) - return p[1]; - var local_f = (f - p[0]) / r; - return p[1] * (1.0 - local_f) + pn[1] * local_f; - } - return 0; - } - - CurveEditor.prototype.draw = function( ctx, size, graphcanvas, background_color, line_color, inactive ) - { - var points = this.points; - if(!points) - return; - this.size = size; - var w = size[0] - this.margin * 2; - var h = size[1] - this.margin * 2; - - line_color = line_color || "#666"; - - ctx.save(); - ctx.translate(this.margin,this.margin); - - if(background_color) - { - ctx.fillStyle = "#111"; - ctx.fillRect(0,0,w,h); - ctx.fillStyle = "#222"; - ctx.fillRect(w*0.5,0,1,h); - ctx.strokeStyle = "#333"; - ctx.strokeRect(0,0,w,h); - } - ctx.strokeStyle = line_color; - if(inactive) - ctx.globalAlpha = 0.5; - ctx.beginPath(); - for(var i = 0; i < points.length; ++i) - { - var p = points[i]; - ctx.lineTo( p[0] * w, (1.0 - p[1]) * h ); - } - ctx.stroke(); - ctx.globalAlpha = 1; - if(!inactive) - for(var i = 0; i < points.length; ++i) - { - var p = points[i]; - ctx.fillStyle = this.selected == i ? "#FFF" : (this.nearest == i ? "#DDD" : "#AAA"); - ctx.beginPath(); - ctx.arc( p[0] * w, (1.0 - p[1]) * h, 2, 0, Math.PI * 2 ); - ctx.fill(); - } - ctx.restore(); - } - - //localpos is mouse in curve editor space - CurveEditor.prototype.onMouseDown = function( localpos, graphcanvas ) - { - var points = this.points; - if(!points) - return; - if( localpos[1] < 0 ) - return; - - //this.captureInput(true); - var w = this.size[0] - this.margin * 2; - var h = this.size[1] - this.margin * 2; - var x = localpos[0] - this.margin; - var y = localpos[1] - this.margin; - var pos = [x,y]; - var max_dist = 30 / graphcanvas.ds.scale; - //search closer one - this.selected = this.getCloserPoint(pos, max_dist); - //create one - if(this.selected == -1) - { - var point = [x / w, 1 - y / h]; - points.push(point); - points.sort(function(a,b){ return a[0] - b[0]; }); - this.selected = points.indexOf(point); - this.must_update = true; - } - if(this.selected != -1) - return true; - } - - CurveEditor.prototype.onMouseMove = function( localpos, graphcanvas ) - { - var points = this.points; - if(!points) - return; - var s = this.selected; - if(s < 0) - return; - var x = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2 ); - var y = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2 ); - var curvepos = [(localpos[0] - this.margin),(localpos[1] - this.margin)]; - var max_dist = 30 / graphcanvas.ds.scale; - this._nearest = this.getCloserPoint(curvepos, max_dist); - var point = points[s]; - if(point) - { - var is_edge_point = s == 0 || s == points.length - 1; - if( !is_edge_point && (localpos[0] < -10 || localpos[0] > this.size[0] + 10 || localpos[1] < -10 || localpos[1] > this.size[1] + 10) ) - { - points.splice(s,1); - this.selected = -1; - return; - } - if( !is_edge_point ) //not edges - point[0] = Math.clamp(x,0,1); - else - point[0] = s == 0 ? 0 : 1; - point[1] = 1.0 - Math.clamp(y,0,1); - points.sort(function(a,b){ return a[0] - b[0]; }); - this.selected = points.indexOf(point); - this.must_update = true; - } - } - - CurveEditor.prototype.onMouseUp = function( localpos, graphcanvas ) - { - this.selected = -1; - return false; - } - - CurveEditor.prototype.getCloserPoint = function(pos, max_dist) - { - var points = this.points; - if(!points) - return -1; - max_dist = max_dist || 30; - var w = (this.size[0] - this.margin * 2); - var h = (this.size[1] - this.margin * 2); - var num = points.length; - var p2 = [0,0]; - var min_dist = 1000000; - var closest = -1; - var last_valid = -1; - for(var i = 0; i < num; ++i) - { - var p = points[i]; - p2[0] = p[0] * w; - p2[1] = (1.0 - p[1]) * h; - if(p2[0] < pos[0]) - last_valid = i; - var dist = vec2.distance(pos,p2); - if(dist > min_dist || dist > max_dist) - continue; - closest = i; - min_dist = dist; - } - return closest; - } - - LiteGraph.CurveEditor = CurveEditor; - - //used to create nodes from wrapping functions - LiteGraph.getParameterNames = function(func) { - return (func + "") - .replace(/[/][/].*$/gm, "") // strip single-line comments - .replace(/\s+/g, "") // strip white space - .replace(/[/][*][^/*]*[*][/]/g, "") // strip multi-line comments /**/ - .split("){", 1)[0] - .replace(/^[^(]*[(]/, "") // extract the parameters - .replace(/=[^,]+/g, "") // strip any ES6 defaults - .split(",") - .filter(Boolean); // split & filter [""] - }; - - /* helper for interaction: pointer, touch, mouse Listeners - used by LGraphCanvas DragAndScale ContextMenu*/ - LiteGraph.pointerListenerAdd = function(oDOM, sEvIn, fCall, capture=false) { - if (!oDOM || !oDOM.addEventListener || !sEvIn || typeof fCall!=="function"){ - //console.log("cant pointerListenerAdd "+oDOM+", "+sEvent+", "+fCall); - return; // -- break -- - } - - var sMethod = LiteGraph.pointerevents_method; - var sEvent = sEvIn; - - // UNDER CONSTRUCTION - // convert pointerevents to touch event when not available - if (sMethod=="pointer" && !window.PointerEvent){ - console.warn("sMethod=='pointer' && !window.PointerEvent"); - console.log("Converting pointer["+sEvent+"] : down move up cancel enter TO touchstart touchmove touchend, etc .."); - switch(sEvent){ - case "down":{ - sMethod = "touch"; - sEvent = "start"; - break; - } - case "move":{ - sMethod = "touch"; - //sEvent = "move"; - break; - } - case "up":{ - sMethod = "touch"; - sEvent = "end"; - break; - } - case "cancel":{ - sMethod = "touch"; - //sEvent = "cancel"; - break; - } - case "enter":{ - console.log("debug: Should I send a move event?"); // ??? - break; - } - // case "over": case "out": not used at now - default:{ - console.warn("PointerEvent not available in this browser ? The event "+sEvent+" would not be called"); - } - } - } - - switch(sEvent){ - //both pointer and move events - case "down": case "up": case "move": case "over": case "out": case "enter": - { - oDOM.addEventListener(sMethod+sEvent, fCall, capture); - } - // only pointerevents - case "leave": case "cancel": case "gotpointercapture": case "lostpointercapture": - { - if (sMethod!="mouse"){ - return oDOM.addEventListener(sMethod+sEvent, fCall, capture); - } - } - // not "pointer" || "mouse" - default: - return oDOM.addEventListener(sEvent, fCall, capture); - } - } - LiteGraph.pointerListenerRemove = function(oDOM, sEvent, fCall, capture=false) { - if (!oDOM || !oDOM.removeEventListener || !sEvent || typeof fCall!=="function"){ - //console.log("cant pointerListenerRemove "+oDOM+", "+sEvent+", "+fCall); - return; // -- break -- - } - switch(sEvent){ - //both pointer and move events - case "down": case "up": case "move": case "over": case "out": case "enter": - { - if (LiteGraph.pointerevents_method=="pointer" || LiteGraph.pointerevents_method=="mouse"){ - oDOM.removeEventListener(LiteGraph.pointerevents_method+sEvent, fCall, capture); - } - } - // only pointerevents - case "leave": case "cancel": case "gotpointercapture": case "lostpointercapture": - { - if (LiteGraph.pointerevents_method=="pointer"){ - return oDOM.removeEventListener(LiteGraph.pointerevents_method+sEvent, fCall, capture); - } - } - // not "pointer" || "mouse" - default: - return oDOM.removeEventListener(sEvent, fCall, capture); - } - } - - Math.clamp = function(v, a, b) { - return a > v ? a : b < v ? b : v; - }; - - if (typeof window != "undefined" && !window["requestAnimationFrame"]) { - window.requestAnimationFrame = - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - function(callback) { - window.setTimeout(callback, 1000 / 60); - }; - } -})(this); - -if (typeof exports != "undefined") { - exports.LiteGraph = this.LiteGraph; -} - - diff --git a/examples/editing/litegraph.js/css/litegraph.css b/examples/editing/litegraph.js/css/litegraph.css deleted file mode 100644 index 918858f4..00000000 --- a/examples/editing/litegraph.js/css/litegraph.css +++ /dev/null @@ -1,680 +0,0 @@ -/* this CSS contains only the basic CSS needed to run the app and use it */ - -.lgraphcanvas { - /*cursor: crosshair;*/ - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - outline: none; - font-family: Tahoma, sans-serif; -} - -.lgraphcanvas * { - box-sizing: border-box; -} - -.litegraph.litecontextmenu { - font-family: Tahoma, sans-serif; - position: fixed; - top: 100px; - left: 100px; - min-width: 100px; - color: #aaf; - padding: 0; - box-shadow: 0 0 10px black !important; - background-color: #2e2e2e !important; - z-index: 10; -} - -.litegraph.litecontextmenu.dark { - background-color: #000 !important; -} - -.litegraph.litecontextmenu .litemenu-title img { - margin-top: 2px; - margin-left: 2px; - margin-right: 4px; -} - -.litegraph.litecontextmenu .litemenu-entry { - margin: 2px; - padding: 2px; -} - -.litegraph.litecontextmenu .litemenu-entry.submenu { - background-color: #2e2e2e !important; -} - -.litegraph.litecontextmenu.dark .litemenu-entry.submenu { - background-color: #000 !important; -} - -.litegraph .litemenubar ul { - font-family: Tahoma, sans-serif; - margin: 0; - padding: 0; -} - -.litegraph .litemenubar li { - font-size: 14px; - color: #999; - display: inline-block; - min-width: 50px; - padding-left: 10px; - padding-right: 10px; - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - cursor: pointer; -} - -.litegraph .litemenubar li:hover { - background-color: #777; - color: #eee; -} - -.litegraph .litegraph .litemenubar-panel { - position: absolute; - top: 5px; - left: 5px; - min-width: 100px; - background-color: #444; - box-shadow: 0 0 3px black; - padding: 4px; - border-bottom: 2px solid #aaf; - z-index: 10; -} - -.litegraph .litemenu-entry, -.litemenu-title { - font-size: 12px; - color: #aaa; - padding: 0 0 0 4px; - margin: 2px; - padding-left: 2px; - -moz-user-select: none; - -webkit-user-select: none; - user-select: none; - cursor: pointer; -} - -.litegraph .litemenu-entry .icon { - display: inline-block; - width: 12px; - height: 12px; - margin: 2px; - vertical-align: top; -} - -.litegraph .litemenu-entry.checked .icon { - background-color: #aaf; -} - -.litegraph .litemenu-entry .more { - float: right; - padding-right: 5px; -} - -.litegraph .litemenu-entry.disabled { - opacity: 0.5; - cursor: default; -} - -.litegraph .litemenu-entry.separator { - display: block; - border-top: 1px solid #333; - border-bottom: 1px solid #666; - width: 100%; - height: 0px; - margin: 3px 0 2px 0; - background-color: transparent; - padding: 0 !important; - cursor: default !important; -} - -.litegraph .litemenu-entry.has_submenu { - border-right: 2px solid cyan; -} - -.litegraph .litemenu-title { - color: #dde; - background-color: #111; - margin: 0; - padding: 2px; - cursor: default; -} - -.litegraph .litemenu-entry:hover:not(.disabled):not(.separator) { - background-color: #444 !important; - color: #eee; - transition: all 0.2s; -} - -.litegraph .litemenu-entry .property_name { - display: inline-block; - text-align: left; - min-width: 80px; - min-height: 1.2em; -} - -.litegraph .litemenu-entry .property_value { - display: inline-block; - background-color: rgba(0, 0, 0, 0.5); - text-align: right; - min-width: 80px; - min-height: 1.2em; - vertical-align: middle; - padding-right: 10px; -} - -.litegraph.litesearchbox { - font-family: Tahoma, sans-serif; - position: absolute; - background-color: rgba(0, 0, 0, 0.5); - padding-top: 4px; -} - -.litegraph.litesearchbox input, -.litegraph.litesearchbox select { - margin-top: 3px; - min-width: 60px; - min-height: 1.5em; - background-color: black; - border: 0; - color: white; - padding-left: 10px; - margin-right: 5px; -} - -.litegraph.litesearchbox .name { - display: inline-block; - min-width: 60px; - min-height: 1.5em; - padding-left: 10px; -} - -.litegraph.litesearchbox .helper { - overflow: auto; - max-height: 200px; - margin-top: 2px; -} - -.litegraph.lite-search-item { - font-family: Tahoma, sans-serif; - background-color: rgba(0, 0, 0, 0.5); - color: white; - padding-top: 2px; -} - -.litegraph.lite-search-item.not_in_filter{ - /*background-color: rgba(50, 50, 50, 0.5);*/ - /*color: #999;*/ - color: #B99; - font-style: italic; -} - -.litegraph.lite-search-item.generic_type{ - /*background-color: rgba(50, 50, 50, 0.5);*/ - /*color: #DD9;*/ - color: #999; - font-style: italic; -} - -.litegraph.lite-search-item:hover, -.litegraph.lite-search-item.selected { - cursor: pointer; - background-color: white; - color: black; -} - -/* DIALOGs ******/ - -.litegraph .dialog { - position: absolute; - top: 50%; - left: 50%; - margin-top: -150px; - margin-left: -200px; - - background-color: #2A2A2A; - - min-width: 400px; - min-height: 200px; - box-shadow: 0 0 4px #111; - border-radius: 6px; -} - -.litegraph .dialog.settings { - left: 10px; - top: 10px; - height: calc( 100% - 20px ); - margin: auto; - max-width: 50%; -} - -.litegraph .dialog.centered { - top: 50px; - left: 50%; - position: absolute; - transform: translateX(-50%); - min-width: 600px; - min-height: 300px; - height: calc( 100% - 100px ); - margin: auto; -} - -.litegraph .dialog .close { - float: right; - margin: 4px; - margin-right: 10px; - cursor: pointer; - font-size: 1.4em; -} - -.litegraph .dialog .close:hover { - color: white; -} - -.litegraph .dialog .dialog-header { - color: #AAA; - border-bottom: 1px solid #161616; -} - -.litegraph .dialog .dialog-header { height: 40px; } -.litegraph .dialog .dialog-footer { height: 50px; padding: 10px; border-top: 1px solid #1a1a1a;} - -.litegraph .dialog .dialog-header .dialog-title { - font: 20px "Arial"; - margin: 4px; - padding: 4px 10px; - display: inline-block; -} - -.litegraph .dialog .dialog-content, .litegraph .dialog .dialog-alt-content { - height: calc(100% - 90px); - width: 100%; - min-height: 100px; - display: inline-block; - color: #AAA; - /*background-color: black;*/ - overflow: auto; -} - -.litegraph .dialog .dialog-content h3 { - margin: 10px; -} - -.litegraph .dialog .dialog-content .connections { - flex-direction: row; -} - -.litegraph .dialog .dialog-content .connections .connections_side { - width: calc(50% - 5px); - min-height: 100px; - background-color: black; - display: flex; -} - -.litegraph .dialog .node_type { - font-size: 1.2em; - display: block; - margin: 10px; -} - -.litegraph .dialog .node_desc { - opacity: 0.5; - display: block; - margin: 10px; -} - -.litegraph .dialog .separator { - display: block; - width: calc( 100% - 4px ); - height: 1px; - border-top: 1px solid #000; - border-bottom: 1px solid #333; - margin: 10px 2px; - padding: 0; -} - -.litegraph .dialog .property { - margin-bottom: 2px; - padding: 4px; -} - -.litegraph .dialog .property:hover { - background: #545454; -} - -.litegraph .dialog .property_name { - color: #737373; - display: inline-block; - text-align: left; - vertical-align: top; - width: 160px; - padding-left: 4px; - overflow: hidden; - margin-right: 6px; -} - -.litegraph .dialog .property:hover .property_name { - color: white; -} - -.litegraph .dialog .property_value { - display: inline-block; - text-align: right; - color: #AAA; - background-color: #1A1A1A; - /*width: calc( 100% - 122px );*/ - max-width: calc( 100% - 162px ); - min-width: 200px; - max-height: 300px; - min-height: 20px; - padding: 4px; - padding-right: 12px; - overflow: hidden; - cursor: pointer; - border-radius: 3px; -} - -.litegraph .dialog .property_value:hover { - color: white; -} - -.litegraph .dialog .property.boolean .property_value { - padding-right: 30px; - color: #A88; - /*width: auto; - float: right;*/ -} - -.litegraph .dialog .property.boolean.bool-on .property_name{ - color: #8A8; -} -.litegraph .dialog .property.boolean.bool-on .property_value{ - color: #8A8; -} - -.litegraph .dialog .btn { - border: 0; - border-radius: 4px; - padding: 4px 20px; - margin-left: 0px; - background-color: #060606; - color: #8e8e8e; -} - -.litegraph .dialog .btn:hover { - background-color: #111; - color: #FFF; -} - -.litegraph .dialog .btn.delete:hover { - background-color: #F33; - color: black; -} - -.litegraph .subgraph_property { - padding: 4px; -} - -.litegraph .subgraph_property:hover { - background-color: #333; -} - -.litegraph .subgraph_property.extra { - margin-top: 8px; -} - -.litegraph .subgraph_property span.name { - font-size: 1.3em; - padding-left: 4px; -} - -.litegraph .subgraph_property span.type { - opacity: 0.5; - margin-right: 20px; - padding-left: 4px; -} - -.litegraph .subgraph_property span.label { - display: inline-block; - width: 60px; - padding: 0px 10px; -} - -.litegraph .subgraph_property input { - width: 140px; - color: #999; - background-color: #1A1A1A; - border-radius: 4px; - border: 0; - margin-right: 10px; - padding: 4px; - padding-left: 10px; -} - -.litegraph .subgraph_property button { - background-color: #1c1c1c; - color: #aaa; - border: 0; - border-radius: 2px; - padding: 4px 10px; - cursor: pointer; -} - -.litegraph .subgraph_property.extra { - color: #ccc; -} - -.litegraph .subgraph_property.extra input { - background-color: #111; -} - -.litegraph .bullet_icon { - margin-left: 10px; - border-radius: 10px; - width: 12px; - height: 12px; - background-color: #666; - display: inline-block; - margin-top: 2px; - margin-right: 4px; - transition: background-color 0.1s ease 0s; - -moz-transition: background-color 0.1s ease 0s; -} - -.litegraph .bullet_icon:hover { - background-color: #698; - cursor: pointer; -} - -/* OLD */ - -.graphcontextmenu { - padding: 4px; - min-width: 100px; -} - -.graphcontextmenu-title { - color: #dde; - background-color: #222; - margin: 0; - padding: 2px; - cursor: default; -} - -.graphmenu-entry { - box-sizing: border-box; - margin: 2px; - padding-left: 20px; - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - transition: all linear 0.3s; -} - -.graphmenu-entry.event, -.litemenu-entry.event { - border-left: 8px solid orange; - padding-left: 12px; -} - -.graphmenu-entry.disabled { - opacity: 0.3; -} - -.graphmenu-entry.submenu { - border-right: 2px solid #eee; -} - -.graphmenu-entry:hover { - background-color: #555; -} - -.graphmenu-entry.separator { - background-color: #111; - border-bottom: 1px solid #666; - height: 1px; - width: calc(100% - 20px); - -moz-width: calc(100% - 20px); - -webkit-width: calc(100% - 20px); -} - -.graphmenu-entry .property_name { - display: inline-block; - text-align: left; - min-width: 80px; - min-height: 1.2em; -} - -.graphmenu-entry .property_value, -.litemenu-entry .property_value { - display: inline-block; - background-color: rgba(0, 0, 0, 0.5); - text-align: right; - min-width: 80px; - min-height: 1.2em; - vertical-align: middle; - padding-right: 10px; -} - -.graphdialog { - position: absolute; - top: 10px; - left: 10px; - min-height: 2em; - background-color: #333; - font-size: 1.2em; - box-shadow: 0 0 10px black !important; - z-index: 10; -} - -.graphdialog.rounded { - border-radius: 12px; - padding-right: 2px; -} - -.graphdialog .name { - display: inline-block; - min-width: 60px; - min-height: 1.5em; - padding-left: 10px; -} - -.graphdialog input, -.graphdialog textarea, -.graphdialog select { - margin: 3px; - min-width: 60px; - min-height: 1.5em; - background-color: black; - border: 0; - color: white; - padding-left: 10px; - outline: none; -} - -.graphdialog textarea { - min-height: 150px; -} - -.graphdialog button { - margin-top: 3px; - vertical-align: top; - background-color: #999; - border: 0; -} - -.graphdialog button.rounded, -.graphdialog input.rounded { - border-radius: 0 12px 12px 0; -} - -.graphdialog .helper { - overflow: auto; - max-height: 200px; -} - -.graphdialog .help-item { - padding-left: 10px; -} - -.graphdialog .help-item:hover, -.graphdialog .help-item.selected { - cursor: pointer; - background-color: white; - color: black; -} - -.litegraph .dialog { - min-height: 0; -} -.litegraph .dialog .dialog-content { -display: block; -} -.litegraph .dialog .dialog-content .subgraph_property { -padding: 5px; -} -.litegraph .dialog .dialog-footer { -margin: 0; -} -.litegraph .dialog .dialog-footer .subgraph_property { -margin-top: 0; -display: flex; -align-items: center; -padding: 5px; -} -.litegraph .dialog .dialog-footer .subgraph_property .name { -flex: 1; -} -.litegraph .graphdialog { -display: flex; -align-items: center; -border-radius: 20px; -padding: 4px 10px; -position: fixed; -} -.litegraph .graphdialog .name { -padding: 0; -min-height: 0; -font-size: 16px; -vertical-align: middle; -} -.litegraph .graphdialog .value { -font-size: 16px; -min-height: 0; -margin: 0 10px; -padding: 2px 5px; -} -.litegraph .graphdialog input[type="checkbox"] { -width: 16px; -height: 16px; -} -.litegraph .graphdialog button { -padding: 4px 18px; -border-radius: 20px; -cursor: pointer; -} - diff --git a/examples/editing/litegraph.js/package.json b/examples/editing/litegraph.js/package.json deleted file mode 100644 index 6a298d6a..00000000 --- a/examples/editing/litegraph.js/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "litegraph.js", - "version": "0.7.14", - "description": "A graph node editor similar to PD or UDK Blueprints. It works in an HTML5 Canvas and allows to export graphs to be included in applications.", - "main": "build/litegraph.core.js", - "types": "src/litegraph.d.ts", - "directories": { - "doc": "doc" - }, - "private": false, - "scripts": { - "prebuild": "rimraf build", - "build": "grunt build", - "start": "nodemon utils/server.js", - "test": "jest", - "test:allVersions": "./utils/test.sh", - "prettier": "npx prettier --write src/**/*.* css/**/*.*", - "lint": "npx eslint src", - "lint:fix": "npx eslint --fix src" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/jagenjo/litegraph.js.git" - }, - "author": "jagenjo", - "license": "MIT", - "files": [ - "build", - "css/litegraph.css", - "src/litegraph.d.ts" - ], - "bugs": { - "url": "https://github.com/jagenjo/litegraph.js/issues" - }, - "homepage": "https://github.com/jagenjo/litegraph.js#readme", - "devDependencies": { - "@types/jest": "^28.1.3", - "eslint": "^8.37.0 ", - "eslint-plugin-jest": "^27.2.1", - "express": "^4.17.1", - "google-closure-compiler": "^20171112.0.0", - "grunt": "^1.1.0", - "grunt-cli": "^1.2.0", - "grunt-closure-tools": "^1.0.0", - "grunt-contrib-concat": "^1.0.1", - "jest": "^28.1.3", - "nodemon": "^1.19.4", - "rimraf": "^2.7.1" - } -} diff --git a/examples/editing/litegraph.js/src/litegraph.d.ts b/examples/editing/litegraph.js/src/litegraph.d.ts deleted file mode 100644 index 6629e779..00000000 --- a/examples/editing/litegraph.js/src/litegraph.d.ts +++ /dev/null @@ -1,1506 +0,0 @@ -// Type definitions for litegraph.js 0.7.0 -// Project: litegraph.js -// Definitions by: NateScarlet - -export type Vector2 = [number, number]; -export type Vector4 = [number, number, number, number]; -export type widgetTypes = - | "number" - | "slider" - | "combo" - | "text" - | "toggle" - | "button"; -export type SlotShape = - | typeof LiteGraph.BOX_SHAPE - | typeof LiteGraph.CIRCLE_SHAPE - | typeof LiteGraph.ARROW_SHAPE - | typeof LiteGraph.SQUARE_SHAPE - | number; // For custom shapes - -/** https://github.com/jagenjo/litegraph.js/tree/master/guides#node-slots */ -export interface INodeSlot { - name: string; - type: string | -1; - label?: string; - dir?: - | typeof LiteGraph.UP - | typeof LiteGraph.RIGHT - | typeof LiteGraph.DOWN - | typeof LiteGraph.LEFT; - color_on?: string; - color_off?: string; - shape?: SlotShape; - locked?: boolean; - nameLocked?: boolean; -} - -export interface INodeInputSlot extends INodeSlot { - link: LLink["id"] | null; -} -export interface INodeOutputSlot extends INodeSlot { - links: LLink["id"][] | null; -} - -export type WidgetCallback = ( - this: T, - value: T["value"], - graphCanvas: LGraphCanvas, - node: LGraphNode, - pos: Vector2, - event?: MouseEvent -) => void; - -export interface IWidget { - name: string | null; - value: TValue; - options?: TOptions; - type?: widgetTypes; - y?: number; - property?: string; - last_y?: number; - clicked?: boolean; - marker?: boolean; - callback?: WidgetCallback; - /** Called by `LGraphCanvas.drawNodeWidgets` */ - draw?( - ctx: CanvasRenderingContext2D, - node: LGraphNode, - width: number, - posY: number, - height: number - ): void; - /** - * Called by `LGraphCanvas.processNodeWidgets` - * https://github.com/jagenjo/litegraph.js/issues/76 - */ - mouse?( - event: MouseEvent, - pos: Vector2, - node: LGraphNode - ): boolean; - /** Called by `LGraphNode.computeSize` */ - computeSize?(width: number): [number, number]; -} -export interface IButtonWidget extends IWidget { - type: "button"; -} -export interface IToggleWidget - extends IWidget { - type: "toggle"; -} -export interface ISliderWidget - extends IWidget { - type: "slider"; -} -export interface INumberWidget extends IWidget { - type: "number"; -} -export interface IComboWidget - extends IWidget< - string[], - { - values: - | string[] - | ((widget: IComboWidget, node: LGraphNode) => string[]); - } - > { - type: "combo"; -} - -export interface ITextWidget extends IWidget { - type: "text"; -} - -export interface IContextMenuItem { - content: string; - callback?: ContextMenuEventListener; - /** Used as innerHTML for extra child element */ - title?: string; - disabled?: boolean; - has_submenu?: boolean; - submenu?: { - options: ContextMenuItem[]; - } & IContextMenuOptions; - className?: string; -} -export interface IContextMenuOptions { - callback?: ContextMenuEventListener; - ignore_item_callbacks?: Boolean; - event?: MouseEvent | CustomEvent; - parentMenu?: ContextMenu; - autoopen?: boolean; - title?: string; - extra?: any; -} - -export type ContextMenuItem = IContextMenuItem | null; -export type ContextMenuEventListener = ( - value: ContextMenuItem, - options: IContextMenuOptions, - event: MouseEvent, - parentMenu: ContextMenu | undefined, - node: LGraphNode -) => boolean | void; - -export const LiteGraph: { - VERSION: number; - - CANVAS_GRID_SIZE: number; - - NODE_TITLE_HEIGHT: number; - NODE_TITLE_TEXT_Y: number; - NODE_SLOT_HEIGHT: number; - NODE_WIDGET_HEIGHT: number; - NODE_WIDTH: number; - NODE_MIN_WIDTH: number; - NODE_COLLAPSED_RADIUS: number; - NODE_COLLAPSED_WIDTH: number; - NODE_TITLE_COLOR: string; - NODE_TEXT_SIZE: number; - NODE_TEXT_COLOR: string; - NODE_SUBTEXT_SIZE: number; - NODE_DEFAULT_COLOR: string; - NODE_DEFAULT_BGCOLOR: string; - NODE_DEFAULT_BOXCOLOR: string; - NODE_DEFAULT_SHAPE: string; - DEFAULT_SHADOW_COLOR: string; - DEFAULT_GROUP_FONT: number; - - LINK_COLOR: string; - EVENT_LINK_COLOR: string; - CONNECTING_LINK_COLOR: string; - - MAX_NUMBER_OF_NODES: number; //avoid infinite loops - DEFAULT_POSITION: Vector2; //default node position - VALID_SHAPES: ["default", "box", "round", "card"]; //,"circle" - - //shapes are used for nodes but also for slots - BOX_SHAPE: 1; - ROUND_SHAPE: 2; - CIRCLE_SHAPE: 3; - CARD_SHAPE: 4; - ARROW_SHAPE: 5; - SQUARE_SHAPE: 6; - - //enums - INPUT: 1; - OUTPUT: 2; - - EVENT: -1; //for outputs - ACTION: -1; //for inputs - - ALWAYS: 0; - ON_EVENT: 1; - NEVER: 2; - ON_TRIGGER: 3; - - UP: 1; - DOWN: 2; - LEFT: 3; - RIGHT: 4; - CENTER: 5; - - STRAIGHT_LINK: 0; - LINEAR_LINK: 1; - SPLINE_LINK: 2; - - NORMAL_TITLE: 0; - NO_TITLE: 1; - TRANSPARENT_TITLE: 2; - AUTOHIDE_TITLE: 3; - - node_images_path: string; - - debug: boolean; - catch_exceptions: boolean; - throw_errors: boolean; - /** if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits */ - allow_scripts: boolean; - /** node types by string */ - registered_node_types: Record; - /** used for dropping files in the canvas */ - node_types_by_file_extension: Record; - /** node types by class name */ - Nodes: Record; - - /** used to add extra features to the search box */ - searchbox_extras: Record< - string, - { - data: { outputs: string[][]; title: string }; - desc: string; - type: string; - } - >; - - createNode(type: string): T; - /** Register a node class so it can be listed when the user wants to create a new one */ - registerNodeType(type: string, base: { new (): LGraphNode }): void; - /** removes a node type from the system */ - unregisterNodeType(type: string): void; - /** Removes all previously registered node's types. */ - clearRegisteredTypes(): void; - /** - * Create a new node type by passing a function, it wraps it with a proper class and generates inputs according to the parameters of the function. - * Useful to wrap simple methods that do not require properties, and that only process some input to generate an output. - * @param name node name with namespace (p.e.: 'math/sum') - * @param func - * @param param_types an array containing the type of every parameter, otherwise parameters will accept any type - * @param return_type string with the return type, otherwise it will be generic - * @param properties properties to be configurable - */ - wrapFunctionAsNode( - name: string, - func: (...args: any[]) => any, - param_types?: string[], - return_type?: string, - properties?: object - ): void; - - /** - * Adds this method to all node types, existing and to be created - * (You can add it to LGraphNode.prototype but then existing node types wont have it) - */ - addNodeMethod(name: string, func: (...args: any[]) => any): void; - - /** - * Create a node of a given type with a name. The node is not attached to any graph yet. - * @param type full name of the node class. p.e. "math/sin" - * @param name a name to distinguish from other nodes - * @param options to set options - */ - createNode( - type: string, - title: string, - options: object - ): T; - - /** - * Returns a registered node type with a given name - * @param type full name of the node class. p.e. "math/sin" - */ - getNodeType(type: string): LGraphNodeConstructor; - - /** - * Returns a list of node types matching one category - * @method getNodeTypesInCategory - * @param {String} category category name - * @param {String} filter only nodes with ctor.filter equal can be shown - * @return {Array} array with all the node classes - */ - getNodeTypesInCategory( - category: string, - filter: string - ): LGraphNodeConstructor[]; - - /** - * Returns a list with all the node type categories - * @method getNodeTypesCategories - * @param {String} filter only nodes with ctor.filter equal can be shown - * @return {Array} array with all the names of the categories - */ - getNodeTypesCategories(filter: string): string[]; - - /** debug purposes: reloads all the js scripts that matches a wildcard */ - reloadNodes(folder_wildcard: string): void; - - getTime(): number; - LLink: typeof LLink; - LGraph: typeof LGraph; - DragAndScale: typeof DragAndScale; - compareObjects(a: object, b: object): boolean; - distance(a: Vector2, b: Vector2): number; - colorToString(c: string): string; - isInsideRectangle( - x: number, - y: number, - left: number, - top: number, - width: number, - height: number - ): boolean; - growBounding(bounding: Vector4, x: number, y: number): Vector4; - isInsideBounding(p: Vector2, bb: Vector4): boolean; - hex2num(hex: string): [number, number, number]; - num2hex(triplet: [number, number, number]): string; - ContextMenu: typeof ContextMenu; - extendClass(target: A, origin: B): A & B; - getParameterNames(func: string): string[]; -}; - -export type serializedLGraph< - TNode = ReturnType, - // https://github.com/jagenjo/litegraph.js/issues/74 - TLink = [number, number, number, number, number, string], - TGroup = ReturnType -> = { - last_node_id: LGraph["last_node_id"]; - last_link_id: LGraph["last_link_id"]; - nodes: TNode[]; - links: TLink[]; - groups: TGroup[]; - config: LGraph["config"]; - version: typeof LiteGraph.VERSION; -}; - -export declare class LGraph { - static supported_types: string[]; - static STATUS_STOPPED: 1; - static STATUS_RUNNING: 2; - - constructor(o?: object); - - filter: string; - catch_errors: boolean; - /** custom data */ - config: object; - elapsed_time: number; - fixedtime: number; - fixedtime_lapse: number; - globaltime: number; - inputs: any; - iteration: number; - last_link_id: number; - last_node_id: number; - last_update_time: number; - links: Record; - list_of_graphcanvas: LGraphCanvas[]; - outputs: any; - runningtime: number; - starttime: number; - status: typeof LGraph.STATUS_RUNNING | typeof LGraph.STATUS_STOPPED; - - private _nodes: LGraphNode[]; - private _groups: LGraphGroup[]; - private _nodes_by_id: Record; - /** nodes that are executable sorted in execution order */ - private _nodes_executable: - | (LGraphNode & { onExecute: NonNullable }[]) - | null; - /** nodes that contain onExecute */ - private _nodes_in_order: LGraphNode[]; - private _version: number; - - getSupportedTypes(): string[]; - /** Removes all nodes from this graph */ - clear(): void; - /** Attach Canvas to this graph */ - attachCanvas(graphCanvas: LGraphCanvas): void; - /** Detach Canvas to this graph */ - detachCanvas(graphCanvas: LGraphCanvas): void; - /** - * Starts running this graph every interval milliseconds. - * @param interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate - */ - start(interval?: number): void; - /** Stops the execution loop of the graph */ - stop(): void; - /** - * Run N steps (cycles) of the graph - * @param num number of steps to run, default is 1 - */ - runStep(num?: number, do_not_catch_errors?: boolean): void; - /** - * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than - * nodes with only inputs. - */ - updateExecutionOrder(): void; - /** This is more internal, it computes the executable nodes in order and returns it */ - computeExecutionOrder(only_onExecute: boolean, set_level: any): T; - /** - * Returns all the nodes that could affect this one (ancestors) by crawling all the inputs recursively. - * It doesn't include the node itself - * @return an array with all the LGraphNodes that affect this node, in order of execution - */ - getAncestors(node: LGraphNode): LGraphNode[]; - /** - * Positions every node in a more readable manner - */ - arrange(margin?: number,layout?: string): void; - /** - * Returns the amount of time the graph has been running in milliseconds - * @return number of milliseconds the graph has been running - */ - getTime(): number; - - /** - * Returns the amount of time accumulated using the fixedtime_lapse var. This is used in context where the time increments should be constant - * @return number of milliseconds the graph has been running - */ - getFixedTime(): number; - - /** - * Returns the amount of time it took to compute the latest iteration. Take into account that this number could be not correct - * if the nodes are using graphical actions - * @return number of milliseconds it took the last cycle - */ - getElapsedTime(): number; - /** - * Sends an event to all the nodes, useful to trigger stuff - * @param eventName the name of the event (function to be called) - * @param params parameters in array format - */ - sendEventToAllNodes(eventName: string, params: any[], mode?: any): void; - - sendActionToCanvas(action: any, params: any[]): void; - /** - * Adds a new node instance to this graph - * @param node the instance of the node - */ - add(node: LGraphNode, skip_compute_order?: boolean): void; - /** - * Called when a new node is added - * @param node the instance of the node - */ - onNodeAdded(node: LGraphNode): void; - /** Removes a node from the graph */ - remove(node: LGraphNode): void; - /** Returns a node by its id. */ - getNodeById(id: number): LGraphNode | undefined; - /** - * Returns a list of nodes that matches a class - * @param classObject the class itself (not an string) - * @return a list with all the nodes of this type - */ - findNodesByClass( - classObject: LGraphNodeConstructor - ): T[]; - /** - * Returns a list of nodes that matches a type - * @param type the name of the node type - * @return a list with all the nodes of this type - */ - findNodesByType(type: string): T[]; - /** - * Returns the first node that matches a name in its title - * @param title the name of the node to search - * @return the node or null - */ - findNodeByTitle(title: string): T | null; - /** - * Returns a list of nodes that matches a name - * @param title the name of the node to search - * @return a list with all the nodes with this name - */ - findNodesByTitle(title: string): T[]; - /** - * Returns the top-most node in this position of the canvas - * @param x the x coordinate in canvas space - * @param y the y coordinate in canvas space - * @param nodes_list a list with all the nodes to search from, by default is all the nodes in the graph - * @return the node at this position or null - */ - getNodeOnPos( - x: number, - y: number, - node_list?: LGraphNode[], - margin?: number - ): T | null; - /** - * Returns the top-most group in that position - * @param x the x coordinate in canvas space - * @param y the y coordinate in canvas space - * @return the group or null - */ - getGroupOnPos(x: number, y: number): LGraphGroup | null; - - onAction(action: any, param: any): void; - trigger(action: any, param: any): void; - /** Tell this graph it has a global graph input of this type */ - addInput(name: string, type: string, value?: any): void; - /** Assign a data to the global graph input */ - setInputData(name: string, data: any): void; - /** Returns the current value of a global graph input */ - getInputData(name: string): T; - /** Changes the name of a global graph input */ - renameInput(old_name: string, name: string): false | undefined; - /** Changes the type of a global graph input */ - changeInputType(name: string, type: string): false | undefined; - /** Removes a global graph input */ - removeInput(name: string): boolean; - /** Creates a global graph output */ - addOutput(name: string, type: string, value: any): void; - /** Assign a data to the global output */ - setOutputData(name: string, value: string): void; - /** Returns the current value of a global graph output */ - getOutputData(name: string): T; - - /** Renames a global graph output */ - renameOutput(old_name: string, name: string): false | undefined; - /** Changes the type of a global graph output */ - changeOutputType(name: string, type: string): false | undefined; - /** Removes a global graph output */ - removeOutput(name: string): boolean; - triggerInput(name: string, value: any): void; - setCallback(name: string, func: (...args: any[]) => any): void; - beforeChange(info?: LGraphNode): void; - afterChange(info?: LGraphNode): void; - connectionChange(node: LGraphNode): void; - /** returns if the graph is in live mode */ - isLive(): boolean; - /** clears the triggered slot animation in all links (stop visual animation) */ - clearTriggeredSlots(): void; - /* Called when something visually changed (not the graph!) */ - change(): void; - setDirtyCanvas(fg: boolean, bg: boolean): void; - /** Destroys a link */ - removeLink(link_id: number): void; - /** Creates a Object containing all the info about this graph, it can be serialized */ - serialize(): T; - /** - * Configure a graph from a JSON string - * @param data configure a graph from a JSON string - * @returns if there was any error parsing - */ - configure(data: object, keep_old?: boolean): boolean | undefined; - load(url: string): void; -} - -export type SerializedLLink = [number, string, number, number, number, number]; -export declare class LLink { - id: number; - type: string; - origin_id: number; - origin_slot: number; - target_id: number; - target_slot: number; - constructor( - id: number, - type: string, - origin_id: number, - origin_slot: number, - target_id: number, - target_slot: number - ); - configure(o: LLink | SerializedLLink): void; - serialize(): SerializedLLink; -} - -export type SerializedLGraphNode = { - id: T["id"]; - type: T["type"]; - pos: T["pos"]; - size: T["size"]; - flags: T["flags"]; - mode: T["mode"]; - inputs: T["inputs"]; - outputs: T["outputs"]; - title: T["title"]; - properties: T["properties"]; - widgets_values?: IWidget["value"][]; -}; - -/** https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#lgraphnode */ -export declare class LGraphNode { - static title_color: string; - static title: string; - static type: null | string; - static widgets_up: boolean; - constructor(title?: string); - - title: string; - type: null | string; - size: Vector2; - graph: null | LGraph; - graph_version: number; - pos: Vector2; - is_selected: boolean; - mouseOver: boolean; - - id: number; - - //inputs available: array of inputs - inputs: INodeInputSlot[]; - outputs: INodeOutputSlot[]; - connections: any[]; - - //local data - properties: Record; - properties_info: any[]; - - flags: Partial<{ - collapsed: boolean - }>; - - color: string; - bgcolor: string; - boxcolor: string; - shape: - | typeof LiteGraph.BOX_SHAPE - | typeof LiteGraph.ROUND_SHAPE - | typeof LiteGraph.CIRCLE_SHAPE - | typeof LiteGraph.CARD_SHAPE - | typeof LiteGraph.ARROW_SHAPE; - - serialize_widgets: boolean; - skip_list: boolean; - - /** Used in `LGraphCanvas.onMenuNodeMode` */ - mode?: - | typeof LiteGraph.ON_EVENT - | typeof LiteGraph.ON_TRIGGER - | typeof LiteGraph.NEVER - | typeof LiteGraph.ALWAYS; - - /** If set to true widgets do not start after the slots */ - widgets_up: boolean; - /** widgets start at y distance from the top of the node */ - widgets_start_y: number; - /** if you render outside the node, it will be clipped */ - clip_area: boolean; - /** if set to false it wont be resizable with the mouse */ - resizable: boolean; - /** slots are distributed horizontally */ - horizontal: boolean; - /** if true, the node will show the bgcolor as 'red' */ - has_errors?: boolean; - - /** configure a node from an object containing the serialized info */ - configure(info: SerializedLGraphNode): void; - /** serialize the content */ - serialize(): SerializedLGraphNode; - /** Creates a clone of this node */ - clone(): this; - /** serialize and stringify */ - toString(): string; - /** get the title string */ - getTitle(): string; - /** sets the value of a property */ - setProperty(name: string, value: any): void; - /** sets the output data */ - setOutputData(slot: number, data: any): void; - /** sets the output data */ - setOutputDataType(slot: number, type: string): void; - /** - * Retrieves the input data (data traveling through the connection) from one slot - * @param slot - * @param force_update if set to true it will force the connected node of this slot to output data into this link - * @return data or if it is not connected returns undefined - */ - getInputData(slot: number, force_update?: boolean): T; - /** - * Retrieves the input data type (in case this supports multiple input types) - * @param slot - * @return datatype in string format - */ - getInputDataType(slot: number): string; - /** - * Retrieves the input data from one slot using its name instead of slot number - * @param slot_name - * @param force_update if set to true it will force the connected node of this slot to output data into this link - * @return data or if it is not connected returns null - */ - getInputDataByName(slot_name: string, force_update?: boolean): T; - /** tells you if there is a connection in one input slot */ - isInputConnected(slot: number): boolean; - /** tells you info about an input connection (which node, type, etc) */ - getInputInfo( - slot: number - ): { link: number; name: string; type: string | 0 } | null; - /** returns the node connected in the input slot */ - getInputNode(slot: number): LGraphNode | null; - /** returns the value of an input with this name, otherwise checks if there is a property with that name */ - getInputOrProperty(name: string): T; - /** tells you the last output data that went in that slot */ - getOutputData(slot: number): T | null; - /** tells you info about an output connection (which node, type, etc) */ - getOutputInfo( - slot: number - ): { name: string; type: string; links: number[] } | null; - /** tells you if there is a connection in one output slot */ - isOutputConnected(slot: number): boolean; - /** tells you if there is any connection in the output slots */ - isAnyOutputConnected(): boolean; - /** retrieves all the nodes connected to this output slot */ - getOutputNodes(slot: number): LGraphNode[]; - /** Triggers an event in this node, this will trigger any output with the same name */ - trigger(action: string, param: any): void; - /** - * Triggers an slot event in this node - * @param slot the index of the output slot - * @param param - * @param link_id in case you want to trigger and specific output link in a slot - */ - triggerSlot(slot: number, param: any, link_id?: number): void; - /** - * clears the trigger slot animation - * @param slot the index of the output slot - * @param link_id in case you want to trigger and specific output link in a slot - */ - clearTriggeredSlot(slot: number, link_id?: number): void; - /** - * add a new property to this node - * @param name - * @param default_value - * @param type string defining the output type ("vec3","number",...) - * @param extra_info this can be used to have special properties of the property (like values, etc) - */ - addProperty( - name: string, - default_value: any, - type: string, - extra_info?: object - ): T; - /** - * add a new output slot to use in this node - * @param name - * @param type string defining the output type ("vec3","number",...) - * @param extra_info this can be used to have special properties of an output (label, special color, position, etc) - */ - addOutput( - name: string, - type: string | -1, - extra_info?: Partial - ): INodeOutputSlot; - /** - * add a new output slot to use in this node - * @param array of triplets like [[name,type,extra_info],[...]] - */ - addOutputs( - array: [string, string | -1, Partial | undefined][] - ): void; - /** remove an existing output slot */ - removeOutput(slot: number): void; - /** - * add a new input slot to use in this node - * @param name - * @param type string defining the input type ("vec3","number",...), it its a generic one use 0 - * @param extra_info this can be used to have special properties of an input (label, color, position, etc) - */ - addInput( - name: string, - type: string | -1, - extra_info?: Partial - ): INodeInputSlot; - /** - * add several new input slots in this node - * @param array of triplets like [[name,type,extra_info],[...]] - */ - addInputs( - array: [string, string | -1, Partial | undefined][] - ): void; - /** remove an existing input slot */ - removeInput(slot: number): void; - /** - * add an special connection to this node (used for special kinds of graphs) - * @param name - * @param type string defining the input type ("vec3","number",...) - * @param pos position of the connection inside the node - * @param direction if is input or output - */ - addConnection( - name: string, - type: string, - pos: Vector2, - direction: string - ): { - name: string; - type: string; - pos: Vector2; - direction: string; - links: null; - }; - setValue(v: any): void; - /** computes the size of a node according to its inputs and output slots */ - computeSize(): [number, number]; - /** - * https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#node-widgets - * @return created widget - */ - addWidget( - type: T["type"], - name: string, - value: T["value"], - callback?: WidgetCallback | string, - options?: T["options"] - ): T; - - addCustomWidget(customWidget: T): T; - - /** - * returns the bounding of the object, used for rendering purposes - * @return [x, y, width, height] - */ - getBounding(): Vector4; - /** checks if a point is inside the shape of a node */ - isPointInside( - x: number, - y: number, - margin?: number, - skipTitle?: boolean - ): boolean; - /** checks if a point is inside a node slot, and returns info about which slot */ - getSlotInPosition( - x: number, - y: number - ): { - input?: INodeInputSlot; - output?: INodeOutputSlot; - slot: number; - link_pos: Vector2; - }; - /** - * returns the input slot with a given name (used for dynamic slots), -1 if not found - * @param name the name of the slot - * @return the slot (-1 if not found) - */ - findInputSlot(name: string): number; - /** - * returns the output slot with a given name (used for dynamic slots), -1 if not found - * @param name the name of the slot - * @return the slot (-1 if not found) - */ - findOutputSlot(name: string): number; - /** - * connect this node output to the input of another node - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param targetNode the target node - * @param targetSlot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger) - * @return {Object} the link_info is created, otherwise null - */ - connect( - slot: number | string, - targetNode: LGraphNode, - targetSlot: number | string - ): T | null; - /** - * disconnect one output to an specific node - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param target_node the target node to which this slot is connected [Optional, if not target_node is specified all nodes will be disconnected] - * @return if it was disconnected successfully - */ - disconnectOutput(slot: number | string, targetNode?: LGraphNode): boolean; - /** - * disconnect one input - * @param slot (could be the number of the slot or the string with the name of the slot) - * @return if it was disconnected successfully - */ - disconnectInput(slot: number | string): boolean; - /** - * returns the center of a connection point in canvas coords - * @param is_input true if if a input slot, false if it is an output - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param out a place to store the output, to free garbage - * @return the position - **/ - getConnectionPos( - is_input: boolean, - slot: number | string, - out?: Vector2 - ): Vector2; - /** Force align to grid */ - alignToGrid(): void; - /** Console output */ - trace(msg: string): void; - /** Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ - setDirtyCanvas(fg: boolean, bg: boolean): void; - loadImage(url: string): void; - /** Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus */ - captureInput(v: any): void; - /** Collapse the node to make it smaller on the canvas */ - collapse(force: boolean): void; - /** Forces the node to do not move or realign on Z */ - pin(v?: boolean): void; - localToScreen(x: number, y: number, graphCanvas: LGraphCanvas): Vector2; - - // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-appearance - onDrawBackground?( - ctx: CanvasRenderingContext2D, - canvas: HTMLCanvasElement - ): void; - onDrawForeground?( - ctx: CanvasRenderingContext2D, - canvas: HTMLCanvasElement - ): void; - - // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-behaviour - onMouseDown?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseMove?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseUp?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseEnter?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseLeave?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onKey?(event: KeyboardEvent, pos: Vector2, graphCanvas: LGraphCanvas): void; - - /** Called by `LGraphCanvas.selectNodes` */ - onSelected?(): void; - /** Called by `LGraphCanvas.deselectNode` */ - onDeselected?(): void; - /** Called by `LGraph.runStep` `LGraphNode.getInputData` */ - onExecute?(): void; - /** Called by `LGraph.serialize` */ - onSerialize?(o: SerializedLGraphNode): void; - /** Called by `LGraph.configure` */ - onConfigure?(o: SerializedLGraphNode): void; - /** - * when added to graph (warning: this is called BEFORE the node is configured when loading) - * Called by `LGraph.add` - */ - onAdded?(graph: LGraph): void; - /** - * when removed from graph - * Called by `LGraph.remove` `LGraph.clear` - */ - onRemoved?(): void; - /** - * if returns false the incoming connection will be canceled - * Called by `LGraph.connect` - * @param inputIndex target input slot number - * @param outputType type of output slot - * @param outputSlot output slot object - * @param outputNode node containing the output - * @param outputIndex index of output slot - */ - onConnectInput?( - inputIndex: number, - outputType: INodeOutputSlot["type"], - outputSlot: INodeOutputSlot, - outputNode: LGraphNode, - outputIndex: number - ): boolean; - /** - * if returns false the incoming connection will be canceled - * Called by `LGraph.connect` - * @param outputIndex target output slot number - * @param inputType type of input slot - * @param inputSlot input slot object - * @param inputNode node containing the input - * @param inputIndex index of input slot - */ - onConnectOutput?( - outputIndex: number, - inputType: INodeInputSlot["type"], - inputSlot: INodeInputSlot, - inputNode: LGraphNode, - inputIndex: number - ): boolean; - - /** - * Called just before connection (or disconnect - if input is linked). - * A convenient place to switch to another input, or create new one. - * This allow for ability to automatically add slots if needed - * @param inputIndex - * @return selected input slot index, can differ from parameter value - */ - onBeforeConnectInput?( - inputIndex: number - ): number; - - /** a connection changed (new one or removed) (LiteGraph.INPUT or LiteGraph.OUTPUT, slot, true if connected, link_info, input_info or output_info ) */ - onConnectionsChange( - type: number, - slotIndex: number, - isConnected: boolean, - link: LLink, - ioSlot: (INodeOutputSlot | INodeInputSlot) - ): void; - - /** - * if returns false, will abort the `LGraphNode.setProperty` - * Called when a property is changed - * @param property - * @param value - * @param prevValue - */ - onPropertyChanged?(property: string, value: any, prevValue: any): void | boolean; - - /** Called by `LGraphCanvas.processContextMenu` */ - getMenuOptions?(graphCanvas: LGraphCanvas): ContextMenuItem[]; - getSlotMenuOptions?(slot: INodeSlot): ContextMenuItem[]; -} - -export type LGraphNodeConstructor = { - new (): T; -}; - -export type SerializedLGraphGroup = { - title: LGraphGroup["title"]; - bounding: LGraphGroup["_bounding"]; - color: LGraphGroup["color"]; - font: LGraphGroup["font"]; -}; -export declare class LGraphGroup { - title: string; - private _bounding: Vector4; - color: string; - font: string; - - configure(o: SerializedLGraphGroup): void; - serialize(): SerializedLGraphGroup; - move(deltaX: number, deltaY: number, ignoreNodes?: boolean): void; - recomputeInsideNodes(): void; - isPointInside: LGraphNode["isPointInside"]; - setDirtyCanvas: LGraphNode["setDirtyCanvas"]; -} - -export declare class DragAndScale { - constructor(element?: HTMLElement, skipEvents?: boolean); - offset: [number, number]; - scale: number; - max_scale: number; - min_scale: number; - onredraw: Function | null; - enabled: boolean; - last_mouse: Vector2; - element: HTMLElement | null; - visible_area: Vector4; - bindEvents(element: HTMLElement): void; - computeVisibleArea(): void; - onMouse(e: MouseEvent): void; - toCanvasContext(ctx: CanvasRenderingContext2D): void; - convertOffsetToCanvas(pos: Vector2): Vector2; - convertCanvasToOffset(pos: Vector2): Vector2; - mouseDrag(x: number, y: number): void; - changeScale(value: number, zooming_center?: Vector2): void; - changeDeltaScale(value: number, zooming_center?: Vector2): void; - reset(): void; -} - -/** - * This class is in charge of rendering one graph inside a canvas. And provides all the interaction required. - * Valid callbacks are: onNodeSelected, onNodeDeselected, onShowNodePanel, onNodeDblClicked - * - * @param canvas the canvas where you want to render (it accepts a selector in string format or the canvas element itself) - * @param graph - * @param options { skip_rendering, autoresize } - */ -export declare class LGraphCanvas { - static node_colors: Record< - string, - { - color: string; - bgcolor: string; - groupcolor: string; - } - >; - static link_type_colors: Record; - static gradients: object; - static search_limit: number; - - static getFileExtension(url: string): string; - static decodeHTML(str: string): string; - - static onMenuCollapseAll(): void; - static onMenuNodeEdit(): void; - static onShowPropertyEditor( - item: any, - options: any, - e: any, - menu: any, - node: any - ): void; - /** Create menu for `Add Group` */ - static onGroupAdd: ContextMenuEventListener; - /** Create menu for `Add Node` */ - static onMenuAdd: ContextMenuEventListener; - static showMenuNodeOptionalInputs: ContextMenuEventListener; - static showMenuNodeOptionalOutputs: ContextMenuEventListener; - static onShowMenuNodeProperties: ContextMenuEventListener; - static onResizeNode: ContextMenuEventListener; - static onMenuNodeCollapse: ContextMenuEventListener; - static onMenuNodePin: ContextMenuEventListener; - static onMenuNodeMode: ContextMenuEventListener; - static onMenuNodeColors: ContextMenuEventListener; - static onMenuNodeShapes: ContextMenuEventListener; - static onMenuNodeRemove: ContextMenuEventListener; - static onMenuNodeClone: ContextMenuEventListener; - - constructor( - canvas: HTMLCanvasElement | string, - graph?: LGraph, - options?: { - skip_render?: boolean; - autoresize?: boolean; - } - ); - - static active_canvas: HTMLCanvasElement; - - allow_dragcanvas: boolean; - allow_dragnodes: boolean; - /** allow to control widgets, buttons, collapse, etc */ - allow_interaction: boolean; - /** allows to change a connection with having to redo it again */ - allow_reconnect_links: boolean; - /** allow selecting multi nodes without pressing extra keys */ - multi_select: boolean; - /** No effect */ - allow_searchbox: boolean; - always_render_background: boolean; - autoresize?: boolean; - background_image: string; - bgcanvas: HTMLCanvasElement; - bgctx: CanvasRenderingContext2D; - canvas: HTMLCanvasElement; - canvas_mouse: Vector2; - clear_background: boolean; - connecting_node: LGraphNode | null; - connections_width: number; - ctx: CanvasRenderingContext2D; - current_node: LGraphNode | null; - default_connection_color: { - input_off: string; - input_on: string; - output_off: string; - output_on: string; - }; - default_link_color: string; - dirty_area: Vector4 | null; - dirty_bgcanvas?: boolean; - dirty_canvas?: boolean; - drag_mode: boolean; - dragging_canvas: boolean; - dragging_rectangle: Vector4 | null; - ds: DragAndScale; - /** used for transition */ - editor_alpha: number; - filter: any; - fps: number; - frame: number; - graph: LGraph; - highlighted_links: Record; - highquality_render: boolean; - inner_text_font: string; - is_rendering: boolean; - last_draw_time: number; - last_mouse: Vector2; - /** - * Possible duplicated with `last_mouse` - * https://github.com/jagenjo/litegraph.js/issues/70 - */ - last_mouse_position: Vector2; - /** Timestamp of last mouse click, defaults to 0 */ - last_mouseclick: number; - links_render_mode: - | typeof LiteGraph.STRAIGHT_LINK - | typeof LiteGraph.LINEAR_LINK - | typeof LiteGraph.SPLINE_LINK; - live_mode: boolean; - node_capturing_input: LGraphNode | null; - node_dragged: LGraphNode | null; - node_in_panel: LGraphNode | null; - node_over: LGraphNode | null; - node_title_color: string; - node_widget: [LGraphNode, IWidget] | null; - /** Called by `LGraphCanvas.drawBackCanvas` */ - onDrawBackground: - | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) - | null; - /** Called by `LGraphCanvas.drawFrontCanvas` */ - onDrawForeground: - | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) - | null; - onDrawOverlay: ((ctx: CanvasRenderingContext2D) => void) | null; - /** Called by `LGraphCanvas.processMouseDown` */ - onMouse: ((event: MouseEvent) => boolean) | null; - /** Called by `LGraphCanvas.drawFrontCanvas` and `LGraphCanvas.drawLinkTooltip` */ - onDrawLinkTooltip: ((ctx: CanvasRenderingContext2D, link: LLink, _this: this) => void) | null; - /** Called by `LGraphCanvas.selectNodes` */ - onNodeMoved: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeSelected` */ - onNodeSelected: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.deselectNode` */ - onNodeDeselected: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeDblClicked` */ - onShowNodePanel: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeDblClicked` */ - onNodeDblClicked: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.selectNodes` */ - onSelectionChange: ((nodes: Record) => void) | null; - /** Called by `LGraphCanvas.showSearchBox` */ - onSearchBox: - | (( - helper: Element, - value: string, - graphCanvas: LGraphCanvas - ) => string[]) - | null; - onSearchBoxSelection: - | ((name: string, event: MouseEvent, graphCanvas: LGraphCanvas) => void) - | null; - pause_rendering: boolean; - render_canvas_border: boolean; - render_collapsed_slots: boolean; - render_connection_arrows: boolean; - render_connections_border: boolean; - render_connections_shadows: boolean; - render_curved_connections: boolean; - render_execution_order: boolean; - render_only_selected: boolean; - render_shadows: boolean; - render_title_colored: boolean; - round_radius: number; - selected_group: null | LGraphGroup; - selected_group_resizing: boolean; - selected_nodes: Record; - show_info: boolean; - title_text_font: string; - /** set to true to render title bar with gradients */ - use_gradients: boolean; - visible_area: DragAndScale["visible_area"]; - visible_links: LLink[]; - visible_nodes: LGraphNode[]; - zoom_modify_alpha: boolean; - - /** clears all the data inside */ - clear(): void; - /** assigns a graph, you can reassign graphs to the same canvas */ - setGraph(graph: LGraph, skipClear?: boolean): void; - /** opens a graph contained inside a node in the current graph */ - openSubgraph(graph: LGraph): void; - /** closes a subgraph contained inside a node */ - closeSubgraph(): void; - /** assigns a canvas */ - setCanvas(canvas: HTMLCanvasElement, skipEvents?: boolean): void; - /** binds mouse, keyboard, touch and drag events to the canvas */ - bindEvents(): void; - /** unbinds mouse events from the canvas */ - unbindEvents(): void; - - /** - * this function allows to render the canvas using WebGL instead of Canvas2D - * this is useful if you plant to render 3D objects inside your nodes, it uses litegl.js for webgl and canvas2DtoWebGL to emulate the Canvas2D calls in webGL - **/ - enableWebGL(): void; - - /** - * marks as dirty the canvas, this way it will be rendered again - * @param fg if the foreground canvas is dirty (the one containing the nodes) - * @param bg if the background canvas is dirty (the one containing the wires) - */ - setDirty(fg: boolean, bg: boolean): void; - - /** - * Used to attach the canvas in a popup - * @return the window where the canvas is attached (the DOM root node) - */ - getCanvasWindow(): Window; - /** starts rendering the content of the canvas when needed */ - startRendering(): void; - /** stops rendering the content of the canvas (to save resources) */ - stopRendering(): void; - - processMouseDown(e: MouseEvent): boolean | undefined; - processMouseMove(e: MouseEvent): boolean | undefined; - processMouseUp(e: MouseEvent): boolean | undefined; - processMouseWheel(e: MouseEvent): boolean | undefined; - - /** returns true if a position (in graph space) is on top of a node little corner box */ - isOverNodeBox(node: LGraphNode, canvasX: number, canvasY: number): boolean; - /** returns true if a position (in graph space) is on top of a node input slot */ - isOverNodeInput( - node: LGraphNode, - canvasX: number, - canvasY: number, - slotPos: Vector2 - ): boolean; - - /** process a key event */ - processKey(e: KeyboardEvent): boolean | undefined; - - copyToClipboard(): void; - pasteFromClipboard(): void; - processDrop(e: DragEvent): void; - checkDropItem(e: DragEvent): void; - processNodeDblClicked(n: LGraphNode): void; - processNodeSelected(n: LGraphNode, e: MouseEvent): void; - processNodeDeselected(node: LGraphNode): void; - - /** selects a given node (or adds it to the current selection) */ - selectNode(node: LGraphNode, add?: boolean): void; - /** selects several nodes (or adds them to the current selection) */ - selectNodes(nodes?: LGraphNode[], add?: boolean): void; - /** removes a node from the current selection */ - deselectNode(node: LGraphNode): void; - /** removes all nodes from the current selection */ - deselectAllNodes(): void; - /** deletes all nodes in the current selection from the graph */ - deleteSelectedNodes(): void; - - /** centers the camera on a given node */ - centerOnNode(node: LGraphNode): void; - /** changes the zoom level of the graph (default is 1), you can pass also a place used to pivot the zoom */ - setZoom(value: number, center: Vector2): void; - /** brings a node to front (above all other nodes) */ - bringToFront(node: LGraphNode): void; - /** sends a node to the back (below all other nodes) */ - sendToBack(node: LGraphNode): void; - /** checks which nodes are visible (inside the camera area) */ - computeVisibleNodes(nodes: LGraphNode[]): LGraphNode[]; - /** renders the whole canvas content, by rendering in two separated canvas, one containing the background grid and the connections, and one containing the nodes) */ - draw(forceFG?: boolean, forceBG?: boolean): void; - /** draws the front canvas (the one containing all the nodes) */ - drawFrontCanvas(): void; - /** draws some useful stats in the corner of the canvas */ - renderInfo(ctx: CanvasRenderingContext2D, x: number, y: number): void; - /** draws the back canvas (the one containing the background and the connections) */ - drawBackCanvas(): void; - /** draws the given node inside the canvas */ - drawNode(node: LGraphNode, ctx: CanvasRenderingContext2D): void; - /** draws graphic for node's slot */ - drawSlotGraphic(ctx: CanvasRenderingContext2D, pos: number[], shape: SlotShape, horizontal: boolean): void; - /** draws the shape of the given node in the canvas */ - drawNodeShape( - node: LGraphNode, - ctx: CanvasRenderingContext2D, - size: [number, number], - fgColor: string, - bgColor: string, - selected: boolean, - mouseOver: boolean - ): void; - /** draws every connection visible in the canvas */ - drawConnections(ctx: CanvasRenderingContext2D): void; - /** - * draws a link between two points - * @param a start pos - * @param b end pos - * @param link the link object with all the link info - * @param skipBorder ignore the shadow of the link - * @param flow show flow animation (for events) - * @param color the color for the link - * @param startDir the direction enum - * @param endDir the direction enum - * @param numSublines number of sublines (useful to represent vec3 or rgb) - **/ - renderLink( - a: Vector2, - b: Vector2, - link: object, - skipBorder: boolean, - flow: boolean, - color?: string, - startDir?: number, - endDir?: number, - numSublines?: number - ): void; - - computeConnectionPoint( - a: Vector2, - b: Vector2, - t: number, - startDir?: number, - endDir?: number - ): void; - - drawExecutionOrder(ctx: CanvasRenderingContext2D): void; - /** draws the widgets stored inside a node */ - drawNodeWidgets( - node: LGraphNode, - posY: number, - ctx: CanvasRenderingContext2D, - activeWidget: object - ): void; - /** process an event on widgets */ - processNodeWidgets( - node: LGraphNode, - pos: Vector2, - event: Event, - activeWidget: object - ): void; - /** draws every group area in the background */ - drawGroups(canvas: any, ctx: CanvasRenderingContext2D): void; - adjustNodesSize(): void; - /** resizes the canvas to a given size, if no size is passed, then it tries to fill the parentNode */ - resize(width?: number, height?: number): void; - /** - * switches to live mode (node shapes are not rendered, only the content) - * this feature was designed when graphs where meant to create user interfaces - **/ - switchLiveMode(transition?: boolean): void; - onNodeSelectionChange(): void; - touchHandler(event: TouchEvent): void; - - showLinkMenu(link: LLink, e: any): false; - prompt( - title: string, - value: any, - callback: Function, - event: any - ): HTMLDivElement; - showSearchBox(event?: MouseEvent): void; - showEditPropertyValue(node: LGraphNode, property: any, options: any): void; - createDialog( - html: string, - options?: { position?: Vector2; event?: MouseEvent } - ): void; - - convertOffsetToCanvas: DragAndScale["convertOffsetToCanvas"]; - convertCanvasToOffset: DragAndScale["convertCanvasToOffset"]; - /** converts event coordinates from canvas2D to graph coordinates */ - convertEventToCanvasOffset(e: MouseEvent): Vector2; - /** adds some useful properties to a mouse event, like the position in graph coordinates */ - adjustMouseEvent(e: MouseEvent): void; - - getCanvasMenuOptions(): ContextMenuItem[]; - getNodeMenuOptions(node: LGraphNode): ContextMenuItem[]; - getGroupMenuOptions(): ContextMenuItem[]; - /** Called by `getCanvasMenuOptions`, replace default options */ - getMenuOptions?(): ContextMenuItem[]; - /** Called by `getCanvasMenuOptions`, append to default options */ - getExtraMenuOptions?(): ContextMenuItem[]; - /** Called when mouse right click */ - processContextMenu(node: LGraphNode, event: Event): void; -} - -declare class ContextMenu { - static trigger( - element: HTMLElement, - event_name: string, - params: any, - origin: any - ): void; - static isCursorOverElement(event: MouseEvent, element: HTMLElement): void; - static closeAllContextMenus(window: Window): void; - constructor(values: ContextMenuItem[], options?: IContextMenuOptions, window?: Window); - options: IContextMenuOptions; - parentMenu?: ContextMenu; - lock: boolean; - current_submenu?: ContextMenu; - addItem( - name: string, - value: ContextMenuItem, - options?: IContextMenuOptions - ): void; - close(e?: MouseEvent, ignore_parent_menu?: boolean): void; - getTopMenu(): void; - getFirstEvent(): void; -} - -declare global { - interface CanvasRenderingContext2D { - /** like rect but rounded corners */ - roundRect( - x: number, - y: number, - width: number, - height: number, - radius: number, - radiusLow: number - ): void; - } - - interface Math { - clamp(v: number, min: number, max: number): number; - } -} diff --git a/examples/editing/litegraphScripts.ts b/examples/editing/litegraphScripts.ts deleted file mode 100644 index e30e3dea..00000000 --- a/examples/editing/litegraphScripts.ts +++ /dev/null @@ -1,670 +0,0 @@ -import {ConnectionInfo, EventHandler, Graph, GraphNode, - GraphNodeProperties, Listener, WorkerInfo, getCallbackFromString, - wchtmlloader -} from '../../index' -import { replaceListenerArg } from './listenerManip'; - -import { LiteGraph, LGraph, LGraphCanvas, LGraphNode} from './litegraph.js' - -export type LGraphNodeProps = { - __renderHTML?:boolean, //do we want to visualize elements inside the node or on a blank page area (like a typical document vs in-editor) Make this toggle between where it renders in the page/editor - __widget?:{ - //we can use the built-in widgets and/or we can renderHtml, just figure out how to access the html to set them next to each other somehow - } - __position?:{ - //will be set by default otherwise based on proximity to connections - } -} & GraphNodeProperties; - -export type LGraphNodeM = LGraphNode & { - triggers:any, - __node:GraphNode, - __graph:Graph, - __unique:string,//GraphNode unique Id for event lookup - editor:LGraph, tag:string, key?:string, - subs:{[key:string]:{ sub:number, listener:Listener }} - __settings?:{ - mode?:'nodeMethod' //default, a node just runs a function method or a getter for a variable - | 'nodeInstance' //alternatively, we can break out several variables on node - | 'subGraph', //or this is a node on a subgraph for a node, so implicitly all variable are "this", i.e. for internal listeners to states for containing logic (ala blueprints) - - nodeOutputs?:string[], - [key:string]:any - }, - - firstConnect:boolean //internal -} - - -const execPin = '►'; //for modded litegraph - -//https://stackoverflow.com/questions/9091838/get-function-parameter-names-for-interface-purposes -export function getFnParamNames(fn){ - if(typeof fn !== 'string') fn = fn.toString(); - const arrowMatch = fn.match(/\(?[^]*?\)?\s*=>/) - if (arrowMatch) return arrowMatch[0].replace(/[()\s]/gi,'').replace('=>','').split(',') - const match = fn.match(/\([^]*?\)/) - return match ? match[0].replace(/[()\s]/gi,'').split(',') : [] -} - - -export let registered = new Map(); -export let created = new Map(); - -export function addNodeToLGraph(node, graph, editor:LGraph) { - let roots = graph.__node.roots; - let hasNode = registered.get(node.__node.tag) as LGraphNodeM; - if (!hasNode) { - registerNode(node, roots[node.__node.tag],undefined,editor); - for(const key in node) { - if(key !== 'get' && !key.startsWith('__')) - registerNode(node, roots[node.__node.tag], key, editor); - } - - } -} - -export function registerLGraphNodesFromGraph(graph:Graph, editor:LGraph) { - graph.__node.nodes.forEach((node) => { - addNodeToLGraph(node,graph, editor); - }); -} - -//the positioning stuff is incorrect (I broke it then forgot what it did) -export const updateNodePosition = (current, sourceNode, lastNode) => { - const previous = lastNode ? lastNode : sourceNode; - const [ x, y ] = previous.pos; - const [ width, height ] = previous.size; - - current.pos = [x + width + 50, y + height + 50]; // Update position at the end -} - -//fix!!! -export function updateArgNodePosition (target, nodes, lastNode) { - - const [ targetX ] = lastNode ? lastNode.pos : target.pos - const [ targetWidth ] = lastNode ? lastNode.size : target.size - - nodes.forEach((n:LGraphNodeM) => { - const [ _, y ] = n.pos - const [ __, height ] = n.size - - //let bb = n.getBounding(); //include bounding box? - - n.pos = [targetX - targetWidth - 50, y + height + 50]; - }); -} - -export function createNode(name:string, LGraph:LGraph, duplicate = false) { - const got = created.get(name); - if (!duplicate && got) return got as LGraphNodeM; - const node = LiteGraph.createNode(name); - created.set(name, node as LGraphNodeM) - LGraph.add(node); - return node as LGraphNodeM; -} - - - - -export function renderLGraphFromExistingEvents( - listeners:EventHandler['triggers'], - LGraph:LGraph -) { - - let minY = 0; - let lastNode; - for(const key in listeners) { - let tarr = listeners[key] as any as Listener[]; - let nodes = [] as any[]; - for(const trigger of tarr) { - //console.log(trigger); - if(!trigger.tkey) continue; - //create each node in the arg stack if exists, connect by arg position, exec pins only at listener level - - const name = trigger.tkey ? trigger.target+'.'+trigger.tkey : trigger.target as string; - let node = createNode(name,LGraph,true); - let srcname = trigger.key ? trigger.source+'.'+trigger.key : trigger.source as string; - - let hasNode = created.get(srcname); - let srcnode = createNode(srcname, LGraph, false); - - - //console.log(name,node,srcname,srcnode); - - updateNodePosition(node, srcnode, lastNode); - lastNode = hasNode; - - if(!hasNode) { - srcnode.pos[1] = minY + 25; - } - - node.pos[0] = srcnode.pos[0] + 50; - if(minY > node.pos[1]) node.pos[1] = minY + 50; - else node.pos[1] = srcnode.pos[1] + 50; - minY = node.pos[1]; - - //set x and y offset - - if(trigger.__args) { - let lastargnode; - const iterateArg = (arg, node, i) => { - if(typeof arg === 'object') { - let cb = arg.__callback ? arg.__callback : arg.__input; - if(cb) { - let argnode = createNode(cb as string,LGraph, true); - argnode.connect(1, node, i); //todo: several argument slots? - if(arg.__args) { - let argnodes = [] as any[]; - arg.__args.forEach((a,j) => { - argnodes.push(iterateArg(a,argnode,j+1)); - }); - if(argnodes.length > 0) { - updateArgNodePosition(argnode, argnodes, lastargnode); - argnodes.forEach((n) => { - if(minY > n.pos[1]) minY = n.pos[1]; - }); - } - } - lastargnode = argnode; - return argnode; - } - } else if (typeof arg === 'string') { - let argnode = createNode(arg, LGraph, true); - argnode.connect(1, node, i); //todo: several argument slots? - lastargnode = argnode; - return argnode; - } - } - - let argnodes = [] as any[]; - trigger.__args.forEach((arg,i) => { - argnodes.push(iterateArg(arg,node,i+1)); - }); - - if(argnodes.length > 0) { - updateArgNodePosition(node, argnodes, lastargnode); - argnodes.forEach((n) => { - if(minY > n.pos[1]) minY = n.pos[1]; - }); - } - } - - srcnode.connect(0,node,0); - node.subs[Object.keys(node.subs).length] = { sub:trigger.sub, listener:trigger }; - nodes.push(node); - } - for(const node of nodes) { - node.firstConnect = false; //future connections will trigger the subscription swapping - } - } -} - - //creates a new nested arg array from visual connections -const getArgsFromNode = (editor:LGraph, - currentOutputNode:LGraphNodeM, args=[] as any[], previousNode?:LGraphNodeM, curDepth = 0, wasAdded = {} //prevent circular infinite looping -) => { - currentOutputNode.inputs.forEach((inp,i) => { - if(i>0) { //don't use first slot, which we labeled as an exec pin - if(inp.link) { //all arg inputs only have one link (not the case for exec links which may have .extraLinks) - if(editor) { - let link = editor.links[inp.link]; - let inputNodei = editor.getNodeById(link.origin_id); - let origin = link.origin_slot; - if(inputNodei) { - if(inputNodei.outputs[origin].name === 'Get') { - args[i - 1] = inputNodei.title; //the title is the node or method key - //stop it here - } else { - args[i - 1] = { __callback:inputNodei.title }; - curDepth++; - if(wasAdded[link.origin_id]) { //prevent infinite recursion - args[i - 1].__args[i-1] = wasAdded[link.origin_id]; - } else { //go get em otherwise - inputNodei.inputs.forEach((inpj, j) => { - if(j > 0) { - if(inpj.link) { - if(!args[i-1].__args) { - args[i-1].__args = []; - wasAdded[link.origin_id] = args[i - 1].__args; - } - let linkj = editor.links[inpj.link]; - let inputNodej = editor.getNodeById(linkj.origin_id); - let originj = linkj.origin_slot; - if(inputNodej) { - args[i - 1].__args = getArgsFromNode( - editor, - inputNodej as LGraphNodeM, - args[i - 1].__args, - inputNodei as LGraphNodeM, - curDepth, - wasAdded - ); - } - } - } - }); - } - } - } - } - } else args[i-1] = undefined; - } - }); - - return args; -} - - -const checkNodeForSubscriptionUpdate = ( - self:LGraphNodeM, editor:LGraph, inputIndex, outputType, outputSlot, outputNode, outputIndex -) => { - - let execChanged = false; //do we need to update subscriptions? - - if( - (self.inputs[inputIndex].name === execPin && outputSlot.name !== execPin) - || - (self.inputs[inputIndex].name !== execPin && outputSlot.name === execPin) - ) { - return false; //reject a non-event connection - } else { - //these are both exec inputs - execChanged = true; - } - - //a link is updated so check if we have an exec on this node - if(!execChanged && !(Object.keys(self.inputs).find((v) => { if(self.inputs[v].name === execPin && self.inputs[v].link) return true; }) || (self.inputs[0] as any).extraLinks)) - execChanged = true; - - if(execChanged) { - //these are subscriptions - //graph.subscribe() - //and/oor modify the listener - } else { - - /* - * - * - * On connecting to an arg input, - * - * - */ - - let args = getArgsFromNode(editor, self as LGraphNodeM); - - const subNode = (i, sourceNode) => { - if(self.subs[i]) { - let listener = self.subs[i].listener; - let sub = self.subs[i].sub; - self.__graph.unsubscribe(listener.target as string, sub, listener.tkey, listener.subInput); - } else { - - } - let sub = self.__graph.subscribe( - sourceNode.tag, self.tag, args - ); - self.subs[i] = { - sub, - listener:self.__graph.__node.state.getEvent( - sourceNode.__unique + sourceNode.key ? '.'+sourceNode.key : '', - sub - ) as any as Listener - }; - } - - if((self.inputs[0] as any).link) { - let sourceNode = editor.getNodeById((self.inputs[0] as any).link.origin_id) as LGraphNodeM; - if(sourceNode) subNode(0,sourceNode); - } - if((self.inputs[0] as any).extraLinks) { - let i = 0; - for(const key in (self.inputs[0] as any).extraLinks) { - i++; - let sourceNode = editor.getNodeById(editor.links[key].origin_id) as LGraphNodeM; - if(sourceNode) subNode(i,sourceNode); - } - } - - //now propagate upstream if any outputs on the outputNode continue on - if(self.outputs) { - let checked = {} as any; - self.outputs.forEach((output) => { - //rebuild/swap args in active listeners - if(editor && output.links) { - output.links.forEach((link) => { - let outputNode = editor.getNodeById(editor.links[link].target_id); - if(!checked[editor.links[link].target_id]) { - checked[editor.links[link].target_id] = true; - //update subs - if(outputNode) - checkNodeForSubscriptionUpdate(outputNode as LGraphNodeM,editor,editor.links[link].target_slot,undefined,self.outputs[editor.links[link].origin_slot],undefined,undefined); - } - }); - - } - }); - } - - } -} - - - - -export function registerNode( - node: GraphNode, - root?:Function|GraphNodeProperties, - key?: string, - editor?:LGraph -) { - - - const tag = node.__node.tag; - const name = key ? `${tag}.${key}` : tag; - - let hasNode = registered.get(name) as LGraphNodeM; - if (hasNode) return name; - - - const NewNode = function() { - let self = this as LGraphNodeM; - self.title = name; - - self.triggers = node.__listeners ? node.__listeners : {}; - self.__node = node; - self.tag = tag; - self.key = key; - self.__unique = node.__node.unique; - self.__graph = node.__node.graph; - self.editor = editor as LGraph; - self.subs = {}; - self.firstConnect = true; - - let params; - - let setOutputNameFromFunction = (fn) => { - let str = typeof fn === 'string' ? fn : fn.toString() as string; - let isNative = str.indexOf('[native code]') > -1; - if(isNative) { - self.addInput('', 0 as any); - self.addOutput('', 0 as any); - return; - } - let idx = str.lastIndexOf('return'); - if(idx !== str.indexOf('return')) { //multiple return statements so we can't determine which one, just use a blank output - self.addOutput('', 0 as any); - return; - } - if(idx > -1) {//if exits - idx+=5; - //get output name - let lastIndex = str.lastIndexOf(';'); - if(lastIndex === -1 && lastIndex > idx) { - lastIndex = str.lastIndexOf('}'); - } - let substr; - if(lastIndex > -1 && lastIndex > idx) substr = str.substring(idx+1,lastIndex); - if(substr) self.addOutput(substr, 0 as any); //todo: can we type this at all? else do it dynamically - else self.addOutput('', 0 as any); - } - } - - self.addInput(execPin,-1); //fix to be able to add/remove contextually - self.addOutput(execPin,-1); //fix to be able to add/remove contextually - - if(key && root?.[key]) { - if(typeof root[key] === 'function') { - setOutputNameFromFunction(root[key]) - params = getFnParamNames(root[key]); - } else { - let typ = typeof root[key] as string; - if(typ === 'undefined') typ = 0 as any; - self.addInput('Set', typ); - self.addOutput('Get', typ); - } - } - if(typeof root === 'function') { - setOutputNameFromFunction(root); - params = getFnParamNames(root); - } else if(root?.__operator || root?.default) { - setOutputNameFromFunction(root.__operator ? root.__operator : root.default); - params = getFnParamNames(root.__operator ? root.__operator : root.default); - } - if(params) { - params.forEach((p,i) => { - if(p || params.length > 1) self.addInput(p,0 as any); - }); - } - - // for (let key in self) this.addInput(key) - - self.onExecute = function() { - //this can trigger the node operator here or the method of a node to cause downstream effects - } - - self.onAdded = function(graph:LGraph) { - // - } - - self.onRemoved = function() { - //graph.unsubscribe - } - - //when an input (left side) is connected on this node from an output (right side) on another node - self.onConnectInput = function(inputIndex, outputType, outputSlot, outputNode, outputIndex) { - - if(!self.firstConnect) - checkNodeForSubscriptionUpdate(self, editor as LGraph, inputIndex, outputType, outputSlot, outputNode, outputIndex); - - console.log('onConnectInput',{inputIndex, outputType, outputSlot, outputNode, outputIndex}); - - return true; - } - - //when an output is connected on this node, can just use onConnectInput - self.onConnectOutput = function(outputIndex, inputType, inputSlot, inputNode, inputIndex) { - //graph.subscribe(); - //console.log('onConnectOutput',{outputIndex, inputType, inputSlot, inputNode, inputIndex}); - - return true; - } - - self.onConnectionsChange = function(type, slotIndex, isConnected, link, ioSlot) { - //console.log('onConnectionsChange',{type, slotIndex, isConnected, link, ioSlot}); - if(!isConnected) { - //graph.unsubscribe(); - } - } - - // if(node?.__listeners) for(const key in node.__listeners) { - // //add outputs - // } - - // if(node?.__args) for(const key in node.__args) { - // //adds inputs - // } - - //self.addWidget('slider',...); //todo - - if(node?.__element && node?.__renderHTML) { - //we should be able to render the element over the node. The editor is in a canvas so we need to use the - // position X and Y of the canvas element (relative to the pageX and pageY), - // then set the HTML over the top of it and account for the size in the canvas elmeent using the html bounding box - } - - } as any as (new () => LGraphNodeM); - - LiteGraph.registerNodeType(name, NewNode); //now registered in system - - registered.set(name, NewNode); - - return name; - -} - - - - - -export function getListenersFromWorker(worker:WorkerInfo) { - return worker.run('getListenerJSON'); -} //build the graph from this result - -export function setSubscriptionOnWorker(worker:WorkerInfo, nodeEvent:string, onEvent:any, args?:any[], key?:string, subInput?:boolean, blocking?:boolean) { - return worker.subscribe(nodeEvent, onEvent, args, key, subInput, blocking); -} - -export function subscribeNodeToWorker(worker:WorkerInfo, node:LGraphNodeM) { - -} - -//todo: create a worker node - - - -export function registerRemoteNode( - root:Function|GraphNodeProperties|string, - tag:string, - endpoint:ConnectionInfo, - key?: string, - editor?:LGraph -) { - - const name = key ? `${tag}.${key}` : tag; - - let hasNode = registered.get(name) as LGraphNodeM; - if (hasNode) return name; - - - const NewNode = function() { - let self = this as LGraphNodeM; - self.title = name; - - self.tag = tag; - self.key = key; - self.editor = editor as LGraph; - self.subs = {}; - self.firstConnect = true; - - let params; - - let setOutputNameFromFunction = (fn) => { - let str = typeof fn === 'string' ? fn : fn.toString() as string; - let isNative = str.indexOf('[native code]') > -1; - if(isNative) { - self.addInput('', 0 as any); - self.addOutput('', 0 as any); - return; - } - let idx = str.lastIndexOf('return'); - if(idx !== str.indexOf('return')) { //multiple return statements so we can't determine which one, just use a blank output - self.addOutput('', 0 as any); - return; - } - if(idx > -1) {//if exits - idx+=5; - //get output name - let lastIndex = str.lastIndexOf(';'); - if(lastIndex === -1 && lastIndex > idx) { - lastIndex = str.lastIndexOf('}'); - } - let substr; - if(lastIndex > -1 && lastIndex > idx) substr = str.substring(idx+1,lastIndex); - if(substr) self.addOutput(substr, 0 as any); //todo: can we type this at all? else do it dynamically - else self.addOutput('', 0 as any); - } - } - - self.addInput(execPin,-1); //fix to be able to add/remove contextually - self.addOutput(execPin,-1); //fix to be able to add/remove contextually - - if(key && root?.[key]) { - if(typeof root[key] === 'function') { - setOutputNameFromFunction(root[key]) - params = getFnParamNames(root[key]); - } else { - let typ = typeof root[key] as string; - if(typ === 'undefined') typ = 0 as any; - self.addInput('Set', typ); - self.addOutput('Get', typ); - } - } - if(typeof root === 'function') { - setOutputNameFromFunction(root); - params = getFnParamNames(root); - } else if(typeof root === 'object' && (root?.__operator || root?.default)) { - setOutputNameFromFunction(root.__operator ? root.__operator : root.default); - params = getFnParamNames(root.__operator ? root.__operator : root.default); - } - if(params) { - params.forEach((p,i) => { - if(p || params.length > 1) self.addInput(p,0 as any); - }); - } - - // for (let key in self) this.addInput(key) - - self.onExecute = function() { - //this can trigger the node operator here or the method of a node to cause downstream effects - } - - self.onAdded = function(graph:LGraph) { - // - } - - self.onRemoved = function() { - //graph.unsubscribe - } - - //when an input (left side) is connected on this node from an output (right side) on another node - self.onConnectInput = function(inputIndex, outputType, outputSlot, outputNode, outputIndex) { - - if(!self.firstConnect) - checkNodeForSubscriptionUpdate(self, editor as LGraph, inputIndex, outputType, outputSlot, outputNode, outputIndex); - - console.log('onConnectInput',{inputIndex, outputType, outputSlot, outputNode, outputIndex}); - - return true; - } - - //when an output is connected on this node, can just use onConnectInput - self.onConnectOutput = function(outputIndex, inputType, inputSlot, inputNode, inputIndex) { - //graph.subscribe(); - //console.log('onConnectOutput',{outputIndex, inputType, inputSlot, inputNode, inputIndex}); - - return true; - } - - self.onConnectionsChange = function(type, slotIndex, isConnected, link, ioSlot) { - //console.log('onConnectionsChange',{type, slotIndex, isConnected, link, ioSlot}); - if(!isConnected) { - //graph.unsubscribe(); - } - } - - // if(node?.__listeners) for(const key in node.__listeners) { - // //add outputs - // } - - // if(node?.__args) for(const key in node.__args) { - // //adds inputs - // } - - //self.addWidget('slider',...); //todo - - // if(node?.__element && node?.__renderHTML) { - // //we should be able to render the element over the node. The editor is in a canvas so we need to use the - // // position X and Y of the canvas element (relative to the pageX and pageY), - // // then set the HTML over the top of it and account for the size in the canvas elmeent using the html bounding box - // } - - } as any as (new () => LGraphNodeM); - - LiteGraph.registerNodeType(name, NewNode); //now registered in system - - registered.set(name, NewNode); - - return name; - -} \ No newline at end of file diff --git a/examples/editing/old/WebComponent.ts b/examples/editing/old/WebComponent.ts deleted file mode 100644 index 293f739d..00000000 --- a/examples/editing/old/WebComponent.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { Graph, GraphNode, GraphNodeProperties } from "../../src/core/Graph"; -import { wchtmlloader } from '../../src/loaders/html/wc.loader'; - -export class WebComponent { - - [x: keyof GraphNodeProperties]: GraphNodeProperties[keyof GraphNodeProperties] - - node: GraphNode - useShadow = true - - - constructor(properties: GraphNodeProperties) { - - // ----------------- Handle Web Component Properties ----------------- - Object.assign(this, properties); - } - - connect (properties: GraphNodeProperties, graph?: Graph, parent?: GraphNode) { - - if (graph) { - const node = graph.add(properties, parent) - if (node) { - this.node = node - this.__props = this.node.__props - } else console.error('Could not add node to graph', properties) - } else { - this.graph = new Graph({ - properties, - loaders: { wchtmlloader } - }) - - this.node = this.graph.get(this.graph.__node.tag) - } - - this.__props = this.node.__props - - return this.node - } - -} - -export default WebComponent \ No newline at end of file diff --git a/examples/editing/old/context/ContextMenu.ts b/examples/editing/old/context/ContextMenu.ts deleted file mode 100644 index c2b95b99..00000000 --- a/examples/editing/old/context/ContextMenu.ts +++ /dev/null @@ -1,99 +0,0 @@ -import WebComponent from "../WebComponent"; - -import style from './styles.css' -import html from './index.html' - -type MenuItem = { - text: string; - onclick: (e:any, returned: any) => any - } - - - type Response = { - condition: (target: HTMLElement[]) => boolean | any - contents: (ev: MouseEvent) => MenuItem[]; - } - - -export class ContextMenu extends WebComponent { - - responses: Map = new Map() - - constructor() { - super({ - __element: 'escode-context-menu', - __template: html, - __css: style - }) - - this.connect(this) - } - - __onrender () { - this.list = (this.shadowRoot ?? this).querySelector('ul') - - /** close the right click context menu on click */ - window.addEventListener('click', this.onClick) - - /** - present the right click context menu ONLY for the elements having the right class - */ - window.addEventListener('contextmenu', this.onContextMenu) - - } - - - onClick() { - this.style.display = 'none'; - if (this.style.display === 'block') document.body.style.overflow = '' - } - - setResponse = (id, info: Response) => this.responses.set(id, info) - - delete = (id) => this.responses.delete(id) - - onContextMenu = (e) => { - - document.body.style.overflow = 'hidden' - - - this.list.innerHTML = '' // Clear - - - let count = 0; - this.responses.forEach((o) => { - // console.log(o, o.condition(selected)) - - const isMatch = o.condition(e.path ?? [e.target]) - if (isMatch) { - e.preventDefault(); - - // Correct for Parent Window Offset - let parent = (this.parentNode as any) - if (parent.host) parent = parent.host // LitElement correction - var rect = parent.getBoundingClientRect() - this.style.left = e.clientX - rect.left + 'px' - this.style.top = e.clientY - rect.top + 'px' - this.style.display = 'block' - const list = o.contents(e) ?? [] - - if (list.length > 0) { - - if (count > 0) this.list.appendChild(document.createElement('hr')) // Split - - list.forEach(item => { - const li = document.createElement('li') - li.innerHTML = item.text - li.onclick = (ev) => { - item.onclick(ev, isMatch) - } - this.list.appendChild(li) - }) - - count++ - } - } - }) - } - -} \ No newline at end of file diff --git a/examples/editing/old/context/index.html b/examples/editing/old/context/index.html deleted file mode 100644 index e2d1b049..00000000 --- a/examples/editing/old/context/index.html +++ /dev/null @@ -1 +0,0 @@ -
    \ No newline at end of file diff --git a/examples/editing/old/context/styles.css b/examples/editing/old/context/styles.css deleted file mode 100644 index 3b54c68a..00000000 --- a/examples/editing/old/context/styles.css +++ /dev/null @@ -1,52 +0,0 @@ -:host { - border-radius: 10px; - box-shadow: 0 1px 5px 0 rgb(0 0 0 / 20%); - position: absolute; - display: none; - z-index: 10000; - padding: 5px; - color: black; - font-size: 80%; - min-width: 200px; - background: rgba(255, 255, 255, 0.8); - backdrop-filter: blur(6px); -} - -ul, -li { - list-style: none; - margin: 0; - padding: 0; - border-radius: 3px; - user-select: none; -} - -li { - /* border-bottom:solid 1px #CCC; */ - padding: 5px 10px; -} - -li:last-child { - border: none; -} - -li:hover { - background: #EEE; -} - -hr { - margin: 5px; -} - -@media (prefers-color-scheme: dark) { - - :host { - background: rgba(100, 100, 100, 0.8); - color: white; - } - - li:hover { - background: #AAA; - } - -} \ No newline at end of file diff --git a/examples/editing/old/editor/Editor.ts b/examples/editing/old/editor/Editor.ts deleted file mode 100644 index 343b0fd7..00000000 --- a/examples/editing/old/editor/Editor.ts +++ /dev/null @@ -1,934 +0,0 @@ -import { Graph, GraphNode, GraphNodeProperties } from "../../../src/core/Graph" -import { WebComponent } from "../WebComponent"; -import style from './styles.css' -import html from './index.html' -import context from "./context"; -import { Node, NodeProps } from "./node/Node"; -import { Listener } from "./listener/Listener"; -import drag from './utils/drag' - -export default class Editor extends WebComponent { - - - - // GraphScript Behaviors - __onrender = (el) => { - - // ------------------------- Track Elements from the Template ------------------------- - const grid = (el.shadowRoot ?? el).querySelector('#grid') - - this.elements = { grid } - - // ------------------------- Handle Events ------------------------- - el.addEventListener('mousedown', e => { - this.context.start = { x: e.clientX - this.context.point.x, y: e.clientY - this.context.point.y }; - this.mouseDown = true - }) - - window.addEventListener('mouseup', e => { this.mouseDown = false} ) - el.addEventListener('wheel', this.scale) - el.addEventListener('mousemove', this.pan) - - const rect = grid.getBoundingClientRect() - - this.middle = { - x: rect.width / 2, - y: rect.height / 2 - } - - } - - // UI Editing - context: { - zoom: number, - - minZoom: number, - maxZoom: number, - - start: { - x: number, - y: number - }, - point: { - x: number, - y: number - } - } = { - zoom: 1, - minZoom: 0.6 / window.devicePixelRatio, - maxZoom: 3.0, - start: {x: 0, y: 0}, - point: {x: 0, y: 0} - - } - editing: HTMLElement | null = null - mouseDown:boolean = false - #loaded: boolean = false - - nodes: Map = new Map() - listeners: Map = new Map() - toResolve: Function[] = [] - - // GraphScript Management - graphs: { - context: Graph - active: Graph | GraphNode - } - - // listeners: any = {} - ui?: Element - - #selectElements: any = [] - - propertiesToSubscribe: Set = new Set() - nodePaths: Set = new Set() - - #fIter = 0 - - elements: { - context?: Element, - create?: Element, - grid: HTMLElement - } - - constructor (graph, parentNode?: GraphNodeProperties['parentNode']) { - - // -------------- Create a Hidden Internal Graph -------------- - super({ - __element: 'escode-editor', - __template: html, - __css: style, - useShadow: true, - parentNode - }) - - // this.graph = new Graph({ root: this }) - - this.connect(this) - - // -------------- Setup Keyboard Shortcuts -------------- - document.onkeydown = (e) => { - if (e.ctrlKey && e.code == 'KeyS') { - e.preventDefault() - console.error('Save not defined...') - // app.save() // Global save. - } - }; - - // Set graphs blank if not defined - const contextGraph = new Graph() - this.graphs = { context: contextGraph, active: contextGraph } - // -------------- Set Context Graph -------------- - this.setGraph(graph ?? contextGraph) - - this.createContextMenu() - } - - createContextMenu = () => { - // --------------------------------------------------------------------------------------------------------- - // ------------------------------------- Setting Context Menu Response ------------------------------------- - // --------------------------------------------------------------------------------------------------------- - - if (!context.parentNode) document.body.appendChild(context.__props) - - // Setting Context Menu Responses - context.setResponse(`escode-graph-editor_nodes_${Math.random()}`, { - condition: (path) => { - let returned: any = false - this.nodes.forEach(n => { - if (path.includes(n.__props)) returned = n - }) - return returned - }, - contents: () => { - return [ - { - text: 'Delete', - onclick: (_, node) => { - this.removeNode(node) - } - } - ] - - } - }) - - - context.setResponse(`escode-graph-editor_${Math.random()}`, { - condition: (path) => path.includes(this.__props), - contents: (ev) => { - return [ - { - text: 'Add Component', - onclick: async () => { - - const grid = this.elements.grid - if (grid) { - var rect = grid.getBoundingClientRect(); - var x = ev.clientX - rect.left; //x position within the element. - var y = ev.clientY - rect.top; //y position within the element. - - - console.error('Cannot add a component!') - // // Blur the Background - // const overlay = new Overlay() - - // // Create a Modal - // const modal = new Modal({open: true, header: 'Components', footer: 'All ES Components can be found on the ESCode repository.'}) - // overlay.appendChild(modal) - - // modal.onClose = () => { - // overlay.open = false - // } - - // // Show Node Options in a List - // const result = await new Promise((resolve) => { - - // const list = new Tree({ - // target: this.plugins, - // conditions: { - // value: (o) => !!o.__ // Check if a component - // }, - // onClick: (tag, thing:any) => { - // resolve({tag, info: Object.assign({}, thing)}) // Copying thing so that it doesn't get modified globally - // } // pass a shallow copy onwards - // }) - // modal.appendChild(list) - // document.body.appendChild(overlay) - // // this.workspace.parentNode.appendChild(overlay) - // overlay.open = true - - // }) as any // TODO: Add ES Component types... - - // // Add essential info - // const info = result.info - - // const tag = `${result.tag}_${Math.floor(1000*Math.random())}` // generate tag from plugin - - // // extend info for escode - // delete info?.__escode // delete existing instance-specific info - - // this.workspace.addNode({ tag, info, x, y }) - // modal.open = false - // overlay.open = false - } - }, - }, - // { - // text: 'Do another thing', - // onclick: () => { - // console.warn('MUST DO SOMETHING') - // } - // } - ] - } - }) - } - - - // Set Graph on the Editor and React to Listeners - setGraph = (graph: Editor['graphs']['context']) => { - if (graph) { - - this.graphs.context = graph - this.setActive(graph) - - const nodes = Array.from(graph.__node.nodes.values()) - - this.nodePaths = new Set(nodes.map(o => o.__node.tag)) - this.propertiesToSubscribe = new Set(this.nodePaths) - - nodes.forEach(o => { - const listeners = o.__listeners - if (listeners) { - for (let key in listeners) this.#onListenerAdded(key, listeners[key], o) - } - }) - } else { - this.listeners = new Map() - } - } - - setActive = (node: Editor['graphs']['active']) => { - this.#loaded = false - const active = this.graphs.active = node - const nodes = active.__node.nodes as Editor['graphs']['active']['__node']['nodes'] - - nodes.forEach((n,key) => { - let gN = this.nodes.get(n.__node.tag); - - if (!gN){ - gN = this.addNode({ - tag: key, - info: n, - editor: this - }) - } - }) - - // for (let key in this.graph.edges) { - - // let nodeEdges = this.graph.edges[key] - - // // String shortcut - // if (typeof nodeEdges === 'string') nodeEdges = {[nodeEdges]: true} - - // for (let targetKey in nodeEdges) { - // const info = nodeEdges[targetKey] - // const output = (this.edgeMode === 'from') ? this.match(key) : this.match(targetKey, info) - // const input = (this.edgeMode === 'from') ? this.match(targetKey, info) : this.match(key) - - // const edges = {} - - // // Don't duplicate on construction - // const outTag = output.port.tag - // if (!edges[outTag]) edges[outTag] = [] - // if (!edges[outTag].includes(input.port.tag)){ - - // await this.resolveEdge({ - // info, - // input: input.port, - // output: output.port - // }); - - // edges[outTag].push(input.port.tag) - // } - - // } - // } - // } - - - - - // ---------------------- Auto Layout New Nodes ---------------------- // - let notMoved: any[] = [] - this.nodes.forEach((node) => { - if (node.info.__escode) { - const info = node.info.__escode; - if (info.x === 0 && info.y === 0) notMoved.push(node); - else notMoved.push(node); - } - }); - - this.autolayout(notMoved) - this.#transform() // Move to center - this.#loaded = true - } - - // Exposed method for removing a listener - removeListener = (key, value, bound) => { - console.error('Remove Listener to the graph here...') - this.#onListenerRemoved(key, value, bound) - } - - // Exposed method for adding a listener - addListener = (from, to, bound) => { - console.error('Add Listener to the graph here...') - this.#onListenerAdded(from, to, bound) - } - - // InitializE the editor UI when the UI is ready - setUI = (ui: Element=document.body) => { - if (this.ui) Array.from(this.ui.children).forEach(c => c.remove()) - this.ui = ui - - if (this.ui) { - - const createListenerInfo = this.#createListenerUI() - // Create Listener UI - const create = document.createElement('div') - create.appendChild(createListenerInfo.element) - this.ui.appendChild(create) - this.elements.create = create - - // Show context Listeners - const context = document.createElement('div') - context.id = 'context' - const contextHeader = document.createElement('h3') - contextHeader.innerText = 'context Listeners' - context.appendChild(contextHeader) - this.ui.appendChild(context) - this.elements.context = context - - // Add all listeners to the UI - for (let bound in this.listeners) { - for (let key in this.listeners[bound]) this.listeners[bound][key].forEach(value => this.#addListenerToUI(key, value, bound)) - } - } - } - - // -------------- Internal Event Managers -------------- - #onListenerAdded = (key, value, bound) => { - - bound = (typeof bound !== 'string') ? bound.__node.tag : bound - if (!this.listeners[bound]) this.listeners[bound] = {} - if (!this.listeners[bound][key]) this.listeners[bound][key] = [] - this.listeners[bound][key].push(value) - - if (this.ui) this.#addListenerToUI(key, value, bound) - } - - #onListenerRemoved = (key, value, bound) => { - console.error('Remove Listener from UI' , key, value, bound) - } - - - - // ----------------------------------------------------------- // - // ----------------- Ugly UI Management Code ----------------- // - // ----------------------------------------------------------- // - - #createListenerUI = (from?, value: any = {}, bound?) => { - const noArgs = !from && Object.keys(value).length === 0 && !bound - - const options = this.propertiesToSubscribe - let to = typeof value === 'string' ? value : undefined //value.__output - - const ogOptionsSize = options.size - - // Resolve Callback - const resolvePath = (path) => { - if (!this.nodePaths.has(path)) { - if (typeof path === 'string' && path.includes('FUNCTION_')) path = `${bound}.${path}` - } - return path - } - - const isValid = (path) => typeof path !== 'function' && typeof path !== 'boolean' && typeof path !== 'object' - - const addPathToOptions = (path) => { - if (path && !options.has(path) && isValid(path)) { - path = resolvePath(path) - options.add(path) // Ignore Function or Boolean Callbacks - } - } - - let callback = value.__callback - - if (callback && typeof callback === 'function') { - callback.gsEditorId = this.#fIter - callback = `FUNCTION_${this.#fIter}` // NOTE: These functions are all the same! - this.#fIter++ - } - else if (typeof callback === 'boolean') callback = bound - - // Assign To and Callback - if (callback && to) console.error('Has Both', callback && to) - if (!to) to = callback - addPathToOptions(to) - - const states = {from, to, bound, value} - - const div = document.createElement('div') - div.style.border = '1px solid black' - div.style.padding = '10px' - div.style.position = 'relative' - - let button = document.createElement('button') - if (noArgs) { - button.innerText = 'Create' - button.onclick = () => { - const {from, to, bound, value} = states - if (bound && from) { - console.error('Actually subscribe to the listener here', states) - this.#onListenerAdded(from, value, bound) - } - } - - } else { - button.innerText = 'Remove' - button.onclick = () => { - div.remove() - this.removeListener(from, to, bound) - } - } - - button.style.position = 'absolute' - button.style.top = '0' - button.style.right = '0' - - div.appendChild(button) - - - const fromContainer = document.createElement('div') - const fromLabel = document.createElement('label') - fromLabel.innerText = 'From' - const fromSelect = document.createElement('select') - fromSelect.id = 'from' - fromContainer.appendChild(fromLabel) - fromContainer.appendChild(fromSelect) - - const boundContainer = document.createElement('div') - const boundLabel = document.createElement('label') - boundLabel.innerText = 'Bound To' - const boundSelect = document.createElement('select') - boundSelect.id = 'bound' - boundContainer.appendChild(boundLabel) - boundContainer.appendChild(boundSelect) - - const toContainer = document.createElement('div') - const toLabel = document.createElement('label') - toLabel.innerText = 'To' - const toSelect = document.createElement('select') - toSelect.id = 'to' - toContainer.appendChild(toLabel) - toContainer.appendChild(toSelect) - - const createIO = (value) => { - - const ioStates = {} - const inputContainer = document.createElement('div') - const inputHeader = document.createElement('h4') - inputHeader.innerText = 'Input' - inputContainer.appendChild(inputHeader) - const inputSelect = document.createElement('select') - inputSelect.id = 'input' - inputContainer.appendChild(inputSelect) - - this.#addSelectElement(inputSelect, { - value: value.__input, - onchange: (ev) => { - const value = ev.target.value - this.#onSelectChange(ev, states) - states.value.__input = value - } - }, this.propertiesToSubscribe, true) - - - // array[ind] = output(input(args)) - const argsContainer = document.createElement('div') - const argsHeader = document.createElement('h4') - argsHeader.innerText = 'Arguments' - argsContainer.appendChild(argsHeader) - const argsContained = document.createElement('div') - argsContainer.appendChild(argsContained) - argsContained.style.display = 'flex' - - const createArgs = (args) => { - args.forEach((arg, i) => { - if (typeof arg === 'object') { - const io = createIO(arg) - states.value.__args[i] = io.states - argsContained.appendChild(io.element) - } else { - const argContainer = document.createElement('div') - const argSelect = document.createElement('select') - argContainer.appendChild(argSelect) - argsContained.appendChild(argContainer) - addPathToOptions(arg) - this.#addSelectElement(argSelect, { - value: arg, - onchange: (ev) => { - const value = ev.target.value - this.#onSelectChange(ev, states) - if (!states.value.__args) states.value.__args = [] - states.value.__args[i] = value - } - }, this.propertiesToSubscribe, true) - } - }) - } - - if (value.__args) createArgs(value.__args) - else createArgs([undefined]) - - const output = value.__output - const isSimple = !(output && typeof output === 'object') - - const outputContainer = document.createElement('div') - const outputHeader = document.createElement('h4') - outputHeader.innerText = 'Output' - outputContainer.appendChild(outputHeader) - - let outputValue; - if (isSimple) outputValue = document.createElement('div') - else { - const ioInfo = createIO(output) - outputValue = ioInfo.element - states.value.__output = ioInfo.states - } - - outputContainer.appendChild(outputValue) - if (isSimple) { - - const select = document.createElement('select') - select.id = 'output' - outputContainer.appendChild(select) - - this.#addSelectElement(select, { - value: output, - onchange: (ev) => { - const value = ev.target.value - this.#onSelectChange(ev, states) - states.value.__output = value - } - }, this.propertiesToSubscribe, true) - - // if (hasOutput) outputValue.innerText = output - // else outputValue.innerText = 'N/A' - } else { - states.value.__output - } - - - const ioContainer = document.createElement('div') - ioContainer.appendChild(inputContainer) - ioContainer.appendChild(argsContainer) - ioContainer.appendChild(outputContainer) - return { - element: ioContainer, - states: ioStates - } - } - - const io = createIO(value) - - - div.appendChild(fromContainer) - div.appendChild(boundContainer) - div.appendChild(toContainer) - div.appendChild(io.element) - - if (ogOptionsSize !== options.size) this.#updateSelectElements() - - this.#addSelectElement(fromSelect, { - value: from, - onchange: (ev) => this.#onSelectChange(ev, states, 'from') - }) - - this.#addSelectElement(toSelect, { - value: to, - onchange: (ev) => this.#onSelectChange(ev, states, 'to') - }) - - this.#addSelectElement(boundSelect,{ - value: bound, - onchange: (ev) => this.#onSelectChange(ev, states, 'bound') - }, this.nodePaths) - - return { - element: div, - states - } - } - - #addListenerToUI = (from, value, bound) => { - - const info = this.#createListenerUI(from, value, bound) - - this.elements.context?.appendChild(info.element) - } - - #addSelectElement = (el, configuration, options=this.propertiesToSubscribe, includeOutput = false) => { - - if (typeof configuration !== 'object') configuration = {value: configuration} - - const info = { - el, - configuration, - options, - includeOutput - } - this.#selectElements.push(info) - this.#updateSelectElement(info) - } - - #updateSelectElements = () => this.#selectElements.forEach(o => this.#updateSelectElement(o)) - - #onSelectChange = (ev, states, key?) => { - const value = ev.target.value - const node = this.graphs.active.__node.nodes.get(states.from) - if (node) { - const unique =node.__node.unique - const triggers = this.graphs.active.__node.state.triggers[unique] - if (states.value.sub !== undefined) { - const trigger = triggers[states.value.sub] - console.error('To Update Trigger', value, trigger) - } - } else { - console.error('No Node Found', states) - } - - if (key) states[key] = value - - } - - #updateSelectElement = (info) => { - - const configuration = info.configuration - const value = configuration.value - const el = info.el as HTMLSelectElement - if (el.children.length) Array.from(el.children).forEach(c => c.remove()) - - // Create grayed out selection - const option = document.createElement('option') - option.value = '' - option.innerText = 'N/A' - option.selected = true - option.disabled = true - el.appendChild(option) - - const opts = [...info.options] - if (info.includeOutput) opts.unshift('__output') - - - - opts.forEach(key => { - const option = document.createElement('option') - if (key === value) option.selected = true - option.value = key - option.innerText = key - el.appendChild(option) - }) - - if (configuration.onchange) el.onchange = configuration.onchange - - } - - - // // Events - // onedgeadded?: (edge:GraphEdge) => void = () => {} - // onedgeremoved?: (edge:GraphEdge) => void = () => {} - // onnodeadded?: (node:GraphNode) => void = () => {} - // onnoderemoved?: (node:GraphNode) => void = () => {} - - drag = (item: GraphNode | any) => { - // add drag handler - drag(this, item, () => { - this.resize([item]) - }, () => { - if (!this.editing) this.editing = item - }, () => { - if (this.editing instanceof Node) this.editing = null - }) - } - - resize = (nodes = Array.from(this.nodes.values())) => { - nodes.forEach(node => node.edges.forEach(e => e.resize())) - } - -// Currently laying out nodes in a rough square with more nodes in the columns -autolayout = (nodes: Map | Node[] = this.nodes) => { - let offset = 50 - - nodes = (nodes instanceof Map ? Array.from(nodes.values()) : nodes) as Node[] - - let nPerRow = Math.floor(Math.sqrt(nodes.length)) - - let rowSizes: any[] = [] - let colSizes: any[] = [] - let info: any[] = [] - - nodes.forEach((n, i) => { - - const col = i % nPerRow - const row = Math.floor(i/nPerRow) - - const dimensions = [ - { - value: col, - sizes: colSizes, - dimension: 'height' - }, - { - value: row, - sizes: rowSizes, - dimension: 'width' - } - ] - - const rect = n.node.__props.getBoundingClientRect() - info.push({ - rect, - col, - row - }) - - dimensions.forEach(o => { - let isNew = false - if (o.sizes[o.value] === undefined) { - isNew = true - o.sizes[o.value] = 0 - } - - o.sizes[o.value] += rect[o.dimension] - if (!isNew) o.sizes[o.value] += offset - }) - - }) - - // Set top-left viewport location - const width = this.context.point.x = rowSizes.length ? Math.max(...rowSizes) : 0 - const height = this.context.point.y = colSizes.length ? Math.max(...colSizes) : 0 - - // Actually move nodes - let rowAcc: any[] = [] - let colAcc: any[] = [] - nodes.forEach((n, i) => { - const nInfo = info[i] - - if (colAcc[nInfo.col] === undefined) colAcc[nInfo.col] = 0 - else colAcc[nInfo.col] += offset - - if (rowAcc[nInfo.row] === undefined) rowAcc[nInfo.row] = 0 - else rowAcc[nInfo.row] += offset - - const x = this.middle.x + colAcc[nInfo.col] - width // Set Column - const y = this.middle.y + rowAcc[nInfo.row] - height // Set Row - n.updatePosition(x, y) - - // Update with Shift - rowAcc[nInfo.row] += nInfo.rect.height - colAcc[nInfo.col] += nInfo.rect.width - }) - - - } - - // Behavior - scale = (e) => { - e.preventDefault() - let xs = (e.clientX - this.context.point.x) / this.context.zoom; - let ys = (e.clientY - this.context.point.y) / this.context.zoom; - let delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY); - this.context.zoom = (delta > 0) ? (this.context.zoom * 1.2) : (this.context.zoom / 1.2); - if (this.context.zoom < this.context.minZoom) this.context.zoom = this.context.minZoom // clamp - if (this.context.zoom > this.context.maxZoom) this.context.zoom = this.context.maxZoom // clamp - - - this.context.point.x = e.clientX - xs * this.context.zoom; - this.context.point.y = e.clientY - ys * this.context.zoom; - - this.#transform() - } - - #transform = () => { - const grid = this.elements.grid - if (grid) grid.style['transform'] = `translate(calc(-50% + ${this.context.point.x}px), calc(-50% + ${this.context.point.y}px)) scale(${this.context.zoom*100}%)` - } - - - - pan = (e) => { - - // e.preventDefault(); - - if (!this.editing){ - - if (e.target.parentNode){ - - // Transform relative to Parent - let rectParent = e.target.parentNode.getBoundingClientRect(); - let curXParent = (e.clientX - rectParent.left)/rectParent.width; //x position within the element. - let curYParent = (e.clientY - rectParent.top)/rectParent.height; //y position within the element. - - if (this.mouseDown){ - - this.context.point.x = (e.clientX - this.context.start.x); - this.context.point.y = (e.clientY - this.context.start.y); - this.#transform() - } - this.relXParent = curXParent - this.relYParent = curYParent - } - } - } - - - // ---------------------- Add Nodes and Listeners ---------------------- // - removeNode = (node: string | Node) => { - node = ((typeof node === 'string') ? this.nodes.get(node) : node) as Node - - if ( - this.onnoderemoved instanceof Function // callback is a function - ) this.onnoderemoved(node) - - - // update ui - node.deinit(false) - this.nodes.delete(node.tag) - - } - - addNode = (props: NodeProps) => { - - if (!props.editor) props.editor = this - - // shift position to the middle - if (props.info?.__escode?.x) props.x = props.info.__escode.x - if (props.info?.__escode?.y) props.y = props.info.__escode.y - - // Only run autolayout after UI has rendered - const gN = new Node(props, this.elements.grid) - - this.nodes.set(gN.tag, gN) - - if (this.onnodeadded instanceof Function) this.onnodeadded(gN) - - return gN - } - - resolveEdge = async (info, willAwait=true) => { - - if (this.editing?.tagName === 'escode-listener') { - const component = this.editing as any as Listener // TODO: Fix this - await component.link(info) - return component - } else { - - const tempId = `${Math.round( 10000 * Math.random())}` - const edge = new Listener({editor: this, ...info}, this.elements.grid) - this.editing = edge.graph.__props - - this.edges.setNode(tempId, edge) // Place temp into DOM to trigger edge.rendered - - edge.ready.then(res => { - if (res){ - this.edges.delete(tempId) - this.edges.setNode(edge.id, edge) - edge.resize() - } - }).catch(() => {}) - - if (willAwait) await edge.ready // Wait until the edge is complete - - this.editing = null - return edge - } - } - - - match = (route:string, edgeInfo: any = {}) => { - - let tags = route.split('.') - let match = this.nodes.get(tags[0]); - - if (!match) throw new Error('Node not found: ' + route) - - // If no port name, choose between operator and default - const portName = (tags.length === 1) ? (match.info.__operator ? '__operator' : 'default') : tags.slice(1).join('.'); // fallback to default port - - tags.forEach(t => { - const temp = this.nodes.get(t) - if (temp) match = temp - }) - - let port; - try { - port = match.ports.get(portName); - if (!port) { - // alert('Port not found: ' + route) - port = match.addPort({tag: portName, node: match, value: edgeInfo.target}) - } - } catch (e) { - console.error('failed to get port', e, route, this.nodes) - } - - return { - port, - match - } -} - -} \ No newline at end of file diff --git a/examples/editing/old/editor/context.ts b/examples/editing/old/editor/context.ts deleted file mode 100644 index 6b3b4861..00000000 --- a/examples/editing/old/editor/context.ts +++ /dev/null @@ -1,4 +0,0 @@ -import '../context/ContextMenu' -import { ContextMenu } from '../context/ContextMenu' -export const context = new ContextMenu() -export default context \ No newline at end of file diff --git a/examples/editing/old/editor/index.html b/examples/editing/old/editor/index.html deleted file mode 100644 index 4cb72bce..00000000 --- a/examples/editing/old/editor/index.html +++ /dev/null @@ -1,5 +0,0 @@ -
    -
    - -
    -
    \ No newline at end of file diff --git a/examples/editing/old/editor/listener/Listener.ts b/examples/editing/old/editor/listener/Listener.ts deleted file mode 100644 index 0a559ae8..00000000 --- a/examples/editing/old/editor/listener/Listener.ts +++ /dev/null @@ -1,26 +0,0 @@ -import WebComponent from "../../WebComponent"; - -import style from './styles.css' - -export class Listener extends WebComponent { - - - constructor(props: any, parentNode?: HTMLElement) { - - const html = `` - - super({ - __element: 'escode-listener', - __template: html, - __css: style, - parentNode - }) - - this.connect( - this, - // props.editor.graph - ) - - } - -} \ No newline at end of file diff --git a/examples/editing/old/editor/listener/styles.css b/examples/editing/old/editor/listener/styles.css deleted file mode 100644 index ff40988b..00000000 --- a/examples/editing/old/editor/listener/styles.css +++ /dev/null @@ -1,50 +0,0 @@ -:host * { - box-sizing: border-box; - } - - :host { - display: block; - pointer-events: none; - --grid-color: rgb(210, 210, 210); - } - - :host > div { - width: 100%; - display: flex; - align-items: center; - justify-content: space-between; - font-size:7px; - } - - .input { - transform: translateX(-50%); - left: 0; - } - - .output { - transform: translateX(50%); - right: 0; - } - - .output.hidden { - pointer-events: none; - background: transparent; - } - - .port { - pointer-events: all; - width: 10px; - height: 10px; - background: gray; - cursor: pointer; - border-radius: 10px; - z-index: -1; - } - - @media (prefers-color-scheme: dark) { - - :host { - --grid-color: rgb(45, 45, 45); - } - - } \ No newline at end of file diff --git a/examples/editing/old/editor/node/Node.ts b/examples/editing/old/editor/node/Node.ts deleted file mode 100644 index ddd9016a..00000000 --- a/examples/editing/old/editor/node/Node.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { GraphNode, GraphNodeProperties } from "../../../../../src/core/Graph"; -import WebComponent from "../../../WebComponent"; -import Editor from "../Editor"; -import { Listener } from "../listener/Listener"; -import { PortProps, Port } from "./port/Port"; - -import style from './styles.css' - -export const isPrivate = (key) => key[0] === '_' // NOTE: Is redeclared from common/standards.js - - export type NodeProps = { - editor: Editor - x?: number; - y?: number; - tag?: string, - info: GraphNode; // Add ES Component types... - - __onrender?: GraphNodeProperties['__onrender'] - } - - - -export class Node extends WebComponent { - - // workspace: GraphNodeProps['workspace']; - tag: string; - x: number = 0; - y: number = 0; - info: NodeProps['info']; - edges: Map = new Map() - ports: Map = new Map() - portCategories: { - properties: Map, - components: Map, - default: Map, - } = { - properties: new Map(), - components: new Map(), - default: new Map(), - } - - editor: Editor - portOrder = ['default', 'components', 'properties'] - - elements: { - main: HTMLDivElement - } = { - main: document.createElement('div') - } - - - __onrender(el) { - if (this.info) this.updatePorts() - - // if (!this.editor) this.editor = (this.parentNode.parentNode as any).host - - // add drag handler - this.editor.drag(this) - - this.edges.forEach(e => e.resize()) // resize all edges after - } - - constructor(node: NodeProps, parentNode?: HTMLElement) { - - const html = ` -
    - -
    - ` - - super({ - __element: 'escode-node', - __template: html, - __css: style, - // useShadow: true, - parentNode - }) - - this.elements.main.id = 'ports' - this.elements.main.innerHTML = `
    ` - - // if (node.__onrender) { - // const onrender = this.__onrender - // this.__onrender = (el) => { - // onrender(el) // Old onrender - // node.__onrender(el) - // } - // } - - - this.editor = node.editor - - this.connect( - this, - this.editor.graph - ) - - const container = (this.node.shadowRoot).querySelector('div') - container.appendChild(this.elements.main) - this.setNode(node.info) - } - - updatePosition (x, y) { - if (x !== undefined) this.x = x - if (y !== undefined) this.y = y - this.__props.style.transform = `translate(${this.x}px, ${this.y}px)` - } - - setNode (info) { - this.info = info - if (!this.info.__escode) this.info.__escode = { x: 0, y:0 } // Save ESCode Properties - - this.tag = this.info.__node.tag - this.id = this.info.__node.unique - - this.info.__escode.x = this.x = this.info.__escode.x ?? 0 - this.info.__escode.y = this.y = this.info.__escode.y ?? 0 - this.updatePorts(info) - } - - async updatePorts(info=this.info) { - const notify = (tag, value, type) => { - const got = this.portCategories[type].get(tag) - - if (got === value) console.warn('Redeclared port: ', `${this.tag}.${tag}`) - else { - console.error('Port conflict: ', `${this.tag}.${tag}`) - } - } - - const type = 'properties' - - let n = 0 - Object.keys(info).forEach((tag, i) => { - if (tag.slice(0,2) === '__') return // no __ special properties - if (isPrivate(tag)) return // no underscore (pseudo-private) properties - - let thisType = type - if (tag === 'default' || tag === '__operator') thisType = 'default' - if (this.portCategories?.[thisType]?.has(tag)) { - notify(tag, this.ports.get(tag), thisType) - return - } - console.log('Trying to add', tag, i) - if (n < 20) { - this.addPort({ tag, node: this, type: thisType as 'properties' || 'default'}) - n++ - } - }) - - // Add Port for Each Active ES Component instance (i.e. the internal graph) - const components = info.__children as {[x:string]: GraphNode} - if (components) { - const type = 'children' - Object.keys(components).forEach((tag) => { - if (this.portCategories?.[type]?.has(tag)) { - notify(tag, this.ports.get(tag), type) - return - } - console.log('Adding Port: ', tag, type, this) - this.addPort({ tag, type, node: this }) - }) - } - - } - - willUpdate (updatedProps) { - - if ((updatedProps.has('x') || updatedProps.has('y')) && this.info.__escode){ - this.info.__escode.x = this.x // brainsatplay extension - this.info._escode.y = this.y // brainsatplay extension - } - - if (updatedProps.has('info')) this.updatePorts() - } - - - setEdge (edge) { this.edges.set(edge.id, edge) } - - deleteEdge(id) { - this.edges.delete(id) - } - - #addPortCategory (type: string) { - - let ports = this.elements[type] - - if (!ports) { - this.elements[type] = ports = document.createElement('div') - ports.id = `${type}Ports` - - const idx = this.portOrder.findIndex(str => str === type) - const beforeChild = this.elements.main.children[idx] - if (beforeChild) this.elements.main.insertBefore(ports, beforeChild); - else this.elements.main.appendChild(ports) - } - - return ports - } - - addPort (info: PortProps) { - - const type = info.type ?? 'default' - - const categoryDiv = this.#addPortCategory(type) - const category = this.portCategories[type] ?? this.portCategories.default // Set in type-specific registry - - const port = new Port({ ...info, node: this}) - this.ports.set(port.tag, port) - category.set(port.tag, port) - - console.log('Appending', port) - categoryDiv.appendChild(port.__props) // Append to port category - - - return port - } - - deinit (triggerInWorkspace = true) { - if (triggerInWorkspace) this.editor.removeNode(this) - this.edges.forEach(e => e.deinit()) // Remove edges - this.remove() - } - -} \ No newline at end of file diff --git a/examples/editing/old/editor/node/port/Port.ts b/examples/editing/old/editor/node/port/Port.ts deleted file mode 100644 index d1030ff0..00000000 --- a/examples/editing/old/editor/node/port/Port.ts +++ /dev/null @@ -1,103 +0,0 @@ -import WebComponent from "../../../../WebComponent"; -import { Node } from "../Node"; -export const isListenerPort = (key) => !!key.match(/\[Function_[[0-9]+]/) // TODO: Register in standards somewhere... - -import style from './styles.css' - -export const isPrivate = (key) => key[0] === '_' // NOTE: Is redeclared from common/standards.js - -export type PortProps = { - // tree: {[x:string]: any} - // plot?: Function[], - // onPlot?: Function - // preprocess?: Function, - tag: string - node: Node, - value?: any, - type?: 'properties' | 'children' | 'default' -} - - -export class Port extends WebComponent { - - - node: PortProps['node'] - tag: PortProps['tag'] - type: PortProps['type'] - value: PortProps['value'] - - element: HTMLDivElement - output: HTMLDivElement - input: HTMLDivElement - - - resolving: boolean = false - edges: Map = new Map() - - constructor(port: PortProps, parentNode?: HTMLElement) { - - const tag = port.tag - - const html = ` -
    - ${tag} -
    - ` - - super({ - __element: 'escode-port', - __template: html, - __css: style, - // useShadow: false, - parentNode - }) - - this.node = port.node - this.tag = tag - this.value = port.value - this.type = port.type ?? 'properties' - - this.connect( - this, - this.node.editor.graph, - this.node.node - ) - } - - // updated(changedProperties) { - // this.element = this.shadowRoot.querySelector("div") - // if (!this.node) this.node = (this.parentNode.parentNode.parentNode as any).host - // } - - setEdge = (edge) => { - this.edges.set(edge.id, edge) - this.node.setEdge(edge) // Nodify node - } - - deleteEdge = (id) => { - this.edges.delete(id) - this.node.deleteEdge(id) // Nodify node - } - - resolveEdge = async (ev) => { - if (!this.resolving){ - this.resolving = true - const type = (ev.path[0].classList.contains('input')) ? 'input' : 'output' - if (this.node.workspace) await this.node.workspace.resolveEdge({[type]: this}).catch(e => console.warn(`[escode]: ${e}`)) - this.resolving = false - } - } - - onmousedown = this.resolveEdge - - onmouseup = (ev) => { - const maybeEdge = this.node.workspace.editing - if ( - 'node' in maybeEdge - && 'box' in maybeEdge - && 'svgInfo' in maybeEdge - ) this.resolveEdge(ev) - } - - -} \ No newline at end of file diff --git a/examples/editing/old/editor/node/port/styles.css b/examples/editing/old/editor/node/port/styles.css deleted file mode 100644 index 1f87a85a..00000000 --- a/examples/editing/old/editor/node/port/styles.css +++ /dev/null @@ -1,37 +0,0 @@ -:host * { - box-sizing: border-box; - } - - :host { - pointer-events: none; - width: 100%; - display: flex; - align-items: center; - justify-content: space-between; - font-size:7px; - } - - .input { - transform: translateX(-50%); - left: 0; - } - - .output { - transform: translateX(50%); - right: 0; - } - - .output.hidden { - pointer-events: none; - background: transparent; - } - - .port { - pointer-events: all; - width: 10px; - height: 10px; - background: gray; - cursor: pointer; - border-radius: 10px; - z-index: -1; - } diff --git a/examples/editing/old/editor/node/styles.css b/examples/editing/old/editor/node/styles.css deleted file mode 100644 index bd2cebd2..00000000 --- a/examples/editing/old/editor/node/styles.css +++ /dev/null @@ -1,45 +0,0 @@ -:host { - font-family: var(--escode-font-family, sans-serif); - position: absolute; - box-sizing: border-box; - top: 10px; - left: 10px; - user-select: none; - z-index: 1; -} - -:host>div { - min-width: 50px; - background: rgb(60, 60, 60); -} - -#header { - color: var(--escode-primary-font-color, white); - font-size: 8px; - background: var(--escode-primary-color, black); - padding: 5px; - padding-right: 25px; - font-weight: 800; -} - - -#ports { - min-height: 10px; - color: var(--escode-secondary-font-color, white); - background: var(--escode-secondary-color); -} - -#ports>div:not(:last-child) { - border-bottom: 1px solid var(--escode-secondary-font-color, gray); -} - -#ports escode-graph-port { - padding: 2px 0px; -} - -@media (prefers-color-scheme: dark) { - #header { - color: var(--escode-primary-font-color-dark, var(--escode-primary-font-color, black)); - background: var(--escode-primary-color-dark, var(--escode-primary-color, white)); - } -} \ No newline at end of file diff --git a/examples/editing/old/editor/styles.css b/examples/editing/old/editor/styles.css deleted file mode 100644 index 0419c52b..00000000 --- a/examples/editing/old/editor/styles.css +++ /dev/null @@ -1,54 +0,0 @@ - -:host * { - box-sizing: border-box; - } - - :host { - --escode-dark-background-color: rgb(30, 30, 30); - } - - #container { - width: 100%; - align-items: center; - justify-content: center; - position: relative; - height: 100%; - overflow: hidden; - background: rgb(245, 245, 245); - } - - #grid { - overflow: hidden; - height: 100%; - display: block; - --grid-size: 5000px; - --grid-color: rgb(210, 210, 210); - background: white; - - position: relative; - background-image: - repeating-linear-gradient(var(--grid-color) 0 1px, transparent 1px 100%), - repeating-linear-gradient(90deg, var(--grid-color) 0 1px, transparent 1px 100%); - background-size: 20px 20px; - width: var(--grid-size); - height: var(--grid-size); - } - - #grid:active:hover { - cursor: move; - } - - escode-node { - cursor: move; - } - - @media (prefers-color-scheme: dark) { - :host > * { - background-color: rgb(40, 40, 40); - } - - #grid { - --grid-color: rgb(80, 80, 80); - background: var(--escode-dark-background-color); - } - } \ No newline at end of file diff --git a/examples/editing/old/editor/utils/drag.ts b/examples/editing/old/editor/utils/drag.ts deleted file mode 100644 index c7e2208e..00000000 --- a/examples/editing/old/editor/utils/drag.ts +++ /dev/null @@ -1,91 +0,0 @@ -import Editor from "../Editor"; -import { Node } from "../node/Node"; -import { Port } from "../node/port/Port"; - -const dragElement = (workspace:Editor, dragItem: Node, onMove, onDown,onUp) => { - var active = false; - var currentX; - var currentY; - var initialX; - var initialY; - var xOffset = 0; - var yOffset = 0; - var defaultScale = 1.0 - - // container.addEventListener("touchstart", dragStart, false); - // container.addEventListener("touchend", dragEnd, false); - // container.addEventListener("touchmove", drag, false); - - (dragItem.shadowRoot ?? dragItem).addEventListener("mousedown", dragStart, false); - window.addEventListener("mouseup", dragEnd, false); - window.addEventListener("mousemove", drag, false); - - // let transform = dragItem.style.cssText.match(/transform: ([^;].+);\s?/) // TODO: Check persistence - // let transformString: string - // if (transform) transformString = transform[1] - - // if (transformString) { - // // let scale = transformString.match(/scale\(([^\)].+)\)\s?/) - // // if (scale) scale = scale[1] - // // else scale = 1 - - // let translateString = transformString.match(/translate\(([^\)].+)\)\s?/) - // if (translateString){ - // let arr = translateString[1].split(',') - // xOffset = parseFloat(arr[0].split('px')[0]) - // yOffset = parseFloat(arr[1].split('px')[0]) - // } - // } else { - // dragItem.style.transform = `scale(${defaultScale})`; - // } - - function dragStart(e) { - - const x = dragItem.x - const y = dragItem.y - - if (e.type === "touchstart") { - initialX = (e.touches[0].clientX - (workspace.context.zoom*defaultScale)*x); - initialY = (e.touches[0].clientY - (workspace.context.zoom*defaultScale)*y); - } else { - initialX = (e.clientX - (workspace.context.zoom*defaultScale)*x); - initialY = (e.clientY - (workspace.context.zoom*defaultScale)*y); - } - - // Account For Nested Control Objects - if (dragItem.shadowRoot.contains(e.target)){ - if (!(e.target instanceof Port)) active = true; - onDown() - } - } - - function dragEnd() { - initialX = currentX; - initialY = currentY; - - active = false; - onUp() - } - - function drag(e) { - if (active) { - - e.preventDefault(); - - if (e.type === "touchmove") { - currentX = (e.touches[0].clientX - initialX)/(workspace.context.zoom*defaultScale); - currentY = (e.touches[0].clientY - initialY)/(workspace.context.zoom*defaultScale); - } else { - currentX = (e.clientX - initialX)/(workspace.context.zoom*defaultScale); - currentY = (e.clientY - initialY)/(workspace.context.zoom*defaultScale); - } - - - dragItem.updatePosition(currentX, currentY) - - onMove() - } - } -} - -export default dragElement \ No newline at end of file diff --git a/examples/editing/old/index.html b/examples/editing/old/index.html deleted file mode 100644 index 43496878..00000000 --- a/examples/editing/old/index.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - -
    - -
    - -
    -
    - - - - - \ No newline at end of file diff --git a/examples/editing/old/index.ts b/examples/editing/old/index.ts deleted file mode 100644 index be7d4055..00000000 --- a/examples/editing/old/index.ts +++ /dev/null @@ -1,134 +0,0 @@ -import {Graph} from '../../../src/core/Graph' -import { htmlloader } from '../../../src/loaders/html/html.loader'; -import Editor from './editor/Editor'; -const ui = document.getElementById('ui') // NOTE: This is not becoming the parent node... - -let graph = new Graph({ - loaders:{ - htmlloader - }, - roots:{ - - nodeA:{ - __operator:function add(a,b) { - console.log('run nodeA', a, b); - return a+b; - }, - toAdd:2, - __listeners:{ - 'nodeA':'toAdd' - } - }, - - nodeB:{ - __operator:function multiply(a,b) { - console.log('run nodeB', a, b); - return a*b; - }, - __listeners:{ - 'nodeA':{ __callback:true, __args:['__output', 'nodeA.toAdd'] } - } - }, - - nodeC:{ - __operator:function exponent(a,b) { - console.log('run nodeC', a, b); - return Math.pow(a,b); - }, - __listeners:{ - 'nodeB':{ __callback:true, __args: ['__output',{ - __input:'Math.cos', - __output:{ - __input:'Math.pow', //this returns the final output for the argument list - //__output:(inp)=>{ return inp; } //function or object, etc - __args:['__output', 4] - } - }] } - } - }, - - nodeD:{ - parentNode: ui, // NOTE: This is not rendering... - __element:'div', - innerHTML:'operator output (from child): ', - __operator:function divide(a,b) { - console.log('run nodeD', a, b); - console.log('output:',a/b); - return a/b; - }, - log10:function (a) { - console.log('run nodeD.log10', a); - return Math.log10(a); - }, - __children:{ - output: { - __element:'span', - __operator:function(outp) { - console.log('child node received: ', outp); - this.innerHTML = outp; - }, - } - }, - __listeners:{ - 'nodeC':'log10', - 'nodeD.log10':{ __callback:true, __args:['__output', 3] } - } - }, - - Math - - } -}); - -const list = document.querySelector('#list'); -const editDiv = document.querySelector('#editor'); -const editor = new Editor(graph, editDiv); -if (list) editor.setUI(list) - -// let nodeAInternalSub = graph.subscribe( -// 'nodeA', -// 'nodeA.toAdd' -// ); - -// let nodeBSub = graph.subscribe( -// 'nodeA', -// 'nodeB', -// ['__output','nodeA.toAdd'], -// ); - -// let nodeCSub = graph.subscribe( -// 'nodeB', -// 'nodeC', -// ['__output', { -// __input:'Math.cos', -// __output:{ -// __input:'Math.pow', //this returns the final output for the argument list -// __args:['__output', 4] -// } -// }] -// ); - -// let nodeDSub = graph.subscribe( -// 'nodeC', -// 'nodeD.log10' -// ); - -// let nodeDInternalSub = graph.subscribe( -// 'nodeD.log10', -// 'nodeD', -// ['__output', 3] -// ); - -graph.run('nodeA', 3,4); - -graph.clearListeners('nodeC','nodeB'); - -graph.run('nodeA', 4,5) //should only call nodeB now - - -// const animate = () => { -// graph.run('nodeA', 3,4) //should only call nodeB now -// setTimeout(animate, 100); -// } - -// animate() \ No newline at end of file diff --git a/examples/editing/old/package-lock.json b/examples/editing/old/package-lock.json deleted file mode 100644 index fd55bd66..00000000 --- a/examples/editing/old/package-lock.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "escode", - "version": "0.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "escode", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "devDependencies": {} - } - } -} diff --git a/examples/editing/old/package.json b/examples/editing/old/package.json deleted file mode 100644 index 118c5bc1..00000000 --- a/examples/editing/old/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "escode", - "version": "0.0.0", - "description": "An IDE built in GraphScript", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "Garrett Flynn", - "license": "LGPL-3.0-or-later", - "dependencies": {}, - "devDependencies": {}, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} \ No newline at end of file diff --git a/examples/editing/old/tinybuild.config.js b/examples/editing/old/tinybuild.config.js deleted file mode 100644 index 616f1938..00000000 --- a/examples/editing/old/tinybuild.config.js +++ /dev/null @@ -1,37 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: false, - sourcemap: false, - loader: { '.css':'text', '.html':'text'} - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/editing/package-lock.json b/examples/editing/package-lock.json deleted file mode 100644 index 59fcbc34..00000000 --- a/examples/editing/package-lock.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "tinybuildapp5363", - "version": "0.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "tinybuildapp5363", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "dependencies": { - "litegraph.js": "^0.7.14", - "web-worker": "^1.2.0" - } - }, - "../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.202", - "extraneous": true, - "license": "LGPL-3.0-or-later", - "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.17.10", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.9.5" - } - }, - "node_modules/litegraph.js": { - "version": "0.7.14", - "resolved": "https://registry.npmjs.org/litegraph.js/-/litegraph.js-0.7.14.tgz", - "integrity": "sha512-xVC0a/D3uLZkpdV/HxyrruDIWM0vMOoIhgaUQXYymQ8pKgbeQZKR0OfuI0c7IpQxC+M/uoc9BRDl2Fm0Q3bW0w==" - }, - "node_modules/web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - } - }, - "dependencies": { - "litegraph.js": { - "version": "0.7.14", - "resolved": "https://registry.npmjs.org/litegraph.js/-/litegraph.js-0.7.14.tgz", - "integrity": "sha512-xVC0a/D3uLZkpdV/HxyrruDIWM0vMOoIhgaUQXYymQ8pKgbeQZKR0OfuI0c7IpQxC+M/uoc9BRDl2Fm0Q3bW0w==" - }, - "web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - } - } -} diff --git a/examples/editing/proxyMenu.ts b/examples/editing/proxyMenu.ts deleted file mode 100644 index 906646e4..00000000 --- a/examples/editing/proxyMenu.ts +++ /dev/null @@ -1,340 +0,0 @@ -//add proxy menu - -import { Graph, getAllProperties } from "../../src/core/Graph"; -import { parseFunctionFromText } from "../../src/services/utils"; -import { LGraph } from "./litegraph.js/src/litegraph"; -import { addNodeToLGraph } from "./litegraphScripts"; - -let inpTypes = { - "string":(p,k,v)=>{ - p[k] = v - return p[k]; - }, - "boolean":(p,k,v)=>{if(v.toLowerCase() === "false" || v === "0" || v === "null") p[k] = false; else p[k] = true; return p[k];}, - "number":(p,k,v)=>{p[k] = parseFloat(v); return p[k];}, - "function":(p,k,v)=>{p[k] = parseFunctionFromText(v); return p[k];}, //evals - "object":(p,k,v)=>{ v.replace("'",'"'); p[k] = JSON.parse(v);}, - "array":(p,k,v)=>{ if(!v.startsWith('[')) v = `[${v}]`; v.replace("'",'"'); p[k]=JSON.parse(v); return p[k]; }, //encapsulate strings in an array - "functionSpreadArgs":(p,k,v)=>{ - if(typeof p[k] === 'function') { - let split = v.split(','); - split.forEach((s,i) => { - if(s.startsWith('function') || s.startsWith('(')) { - parsed[i] = parseFunctionFromText(s); - } - }); - let joined = `[${split.join(',')}]`; - joined.replace("'",'"'); - let parsed = JSON.parse(joined) as any[]; - return p[k](...parsed); - } - } -}; - -export let makeProxyMenu = (proxyable:{[key:string]:any}, graph:Graph, editor:LGraph) => { - let instantiateProxy = (key, args:any[]=[]) => { - let proxy = new proxyable[key](...args); - let keys = getAllProperties(proxy); - return {proxy, keys}; - } - - let container = document.createElement('div'); - let nameInput = document.createElement('input'); - let keydropdown = document.createElement('select'); - let constructorInput = document.createElement('input'); - let constructButton = document.createElement('button'); - constructButton.innerHTML = "Construct"; - - let proxySetupContainer = document.createElement('div'); - let propertydropdown = document.createElement('select'); - let propertyInput = document.createElement('input'); - let setProp = document.createElement('button'); - setProp.innerHTML = "Eval" - let propertyInputType = document.createElement('select'); - let createProxy = document.createElement('button'); - createProxy.innerHTML = "Create Node"; - - - Object.keys(inpTypes).forEach((t,i) => { - propertyInputType.insertAdjacentHTML('beforeend',``) - }); - - container.insertAdjacentHTML('beforeend',`
    Class to instantiate: `); - container.appendChild(keydropdown); - container.insertAdjacentHTML('beforeend',`
    Class constructor args (evals as a spread array): `); - container.appendChild(constructorInput); - container.appendChild(constructButton); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Name Node: `); - proxySetupContainer.appendChild(nameInput); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Class Property: `); - proxySetupContainer.appendChild(propertydropdown); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Property Type: `); - proxySetupContainer.appendChild(propertyInputType); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Input: `); - proxySetupContainer.appendChild(propertyInput); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Set: `); - proxySetupContainer.appendChild(setProp); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Add to Graph: `); - proxySetupContainer.appendChild(createProxy); - proxySetupContainer.style.display = "none"; - container.appendChild(proxySetupContainer); - - for(const key in proxyable) { - keydropdown.insertAdjacentHTML('beforeend',``); - } - keydropdown.value = ""; - - keydropdown.onchange = (ev) => { - let value = keydropdown.value; - proxySetupContainer.style.display = "none"; - constructButton.onclick = () => { - let args = constructorInput.value as any; - let split = args.split(','); - split.forEach((s,i) => { - if(s.startsWith('function') || s.startsWith('(')) { - parsed[i] = parseFunctionFromText(s); - } - }); - let joined = `[${split.join(',')}]`; - joined = joined.replace(/'/g,'"'); - let parsed = JSON.parse(joined) as any[]; - - let {proxy, keys} = instantiateProxy(value, parsed); - - nameInput.value = `${value}${Math.floor(Math.random()*1000000000000000)}`; - - propertydropdown.innerHTML = ""; - keys.forEach((k) => { - propertydropdown.insertAdjacentHTML('beforeend',``); - }); - propertydropdown.onchange = (ev) => { - let t = typeof proxy[propertydropdown.value]; - propertyInputType.value = t === "undefined" ? "string" : t; - if(t !== 'function') { - propertyInput.value = proxy[propertydropdown.value]; - } else propertyInput.value = ""; - } - setProp.onclick = (ev) => { - if(inpTypes[propertyInputType.value]) - inpTypes[propertyInputType.value](proxy, propertydropdown.value, propertyInput.value) - } - createProxy.onclick = (ev) => { - let props = { - __node:nameInput.value ? { - tag:nameInput.value - } : undefined, - __props:proxy - //todo: could instead list all the non-functional values from proxy here so they get set on the proxy when the node is created - }; - let node = graph.add(props); - addNodeToLGraph(node, graph, editor); - nameInput.value = `${value}${Math.floor(Math.random()*1000000000000000)}`; - } - - proxySetupContainer.style.display = ""; - } - - } - - return container; - -} - - -export let makeNodePropsCreator = (graph:Graph, editor:LGraph) => { - - let container = document.createElement('div'); - let nameInput = document.createElement('input'); - let propsContainer = document.createElement('div'); - let addButton = document.createElement('button'); - addButton.innerHTML = "Add Prop"; - let createButton = document.createElement('button'); - createButton.innerHTML = "Create Node"; - let clearButton = document.createElement('button'); - clearButton.innerHTML = "Clear Props"; - - container.insertAdjacentHTML('beforeend',`
    Name Node: `); - container.appendChild(nameInput); - container.insertAdjacentHTML('beforeend',` -
    Node Properties: {
    key : value
    - `); - container.appendChild(propsContainer); - container.appendChild(addButton); - container.insertAdjacentHTML('beforeend',` -
    }
    - `); - container.appendChild(clearButton); - container.appendChild(createButton); - - clearButton.onclick = () => { - propsContainer.innerHTML = ""; //clear options - } - - let addProp = () => { - let prop = document.createElement('div'); - let keyInput = document.createElement('input'); - keyInput.id = 'key'; - let propInput = document.createElement('input'); - let propInputType = document.createElement('select'); - let delProp = document.createElement('button'); - delProp.innerHTML = 'X'; - delProp.onclick = () => { - prop.remove(); - } - propInputType.id = 'ptype'; - Object.keys(inpTypes).forEach((t,i) => { - if(t !== 'functionSpreadArgs') - propInputType.insertAdjacentHTML('beforeend',``) - }); - propInput.id = 'value'; - prop.appendChild(keyInput); - prop.insertAdjacentHTML('beforeend',':'); - prop.appendChild(propInput); - prop.appendChild(propInputType); - prop.appendChild(delProp); - prop.insertAdjacentHTML('beforeend','
    '); - propsContainer.appendChild(prop); - } - - nameInput.value = `node${Math.floor(Math.random()*1000000000000000)}`; - - addButton.onclick = () => { - addProp(); - } - - createButton.onclick = () => { - let keys = Array.from(propsContainer.querySelectorAll('#key')) as any; - let values = Array.from(propsContainer.querySelectorAll('#value')) as any; - let types = Array.from(propsContainer.querySelectorAll('#ptype')) as any; - - let obj = {} as any; - - keys.forEach((k:any,i) => { - if(k.value) { - if((values[i]).value) { - inpTypes[types[i].value](obj, k.value, values[i].value); - } - } - }); - - let node = graph.add(obj); - addNodeToLGraph(node, graph, editor); - - nameInput.value = `node${Math.floor(Math.random()*1000000000000000)}`; - } - - addProp(); - - return container; - -} - - -export let makeNodeEditorMenu = (graph:Graph, editor?:LGraph) => { - - let container = document.createElement('div'); - let nameInput = document.createElement('input'); - let keydropdown = document.createElement('select'); - let constructorInput = document.createElement('input'); - let constructButton = document.createElement('button'); - constructButton.innerHTML = "Set"; - - let nodeEditorContainer = document.createElement('div'); - let propertydropdown = document.createElement('select'); - let propertyInput = document.createElement('input'); - let setProp = document.createElement('button'); - setProp.innerHTML = "Eval" - let propertyInputType = document.createElement('select'); - //let createProxy = document.createElement('button'); - //createProxy.innerHTML = "Create Node"; - - - Object.keys(inpTypes).forEach((t,i) => { - propertyInputType.insertAdjacentHTML('beforeend',``) - }); - - container.insertAdjacentHTML('beforeend',`
    Select existing node: `); - container.appendChild(keydropdown); - //nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Name Node: `); - //nodeEditorContainer.appendChild(nameInput); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Class Property: `); - nodeEditorContainer.appendChild(propertydropdown); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Property Type: `); - nodeEditorContainer.appendChild(propertyInputType); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Input: `); - nodeEditorContainer.appendChild(propertyInput); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Set: `); - nodeEditorContainer.appendChild(setProp); - // nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Add to Graph: `); - // nodeEditorContainer.appendChild(createProxy); - nodeEditorContainer.style.display = "none"; - container.appendChild(nodeEditorContainer); - - - let keys = Array.from(graph.__node.nodes.keys()); - for(const key of keys) { - keydropdown.insertAdjacentHTML('beforeend',``); - } - keydropdown.value = ""; - - keydropdown.onchange = (ev) => { - let value = keydropdown.value; - //nodeEditorContainer.style.display = "none"; - //constructButton.onclick = () => { - let args = constructorInput.value as any; - let split = args.split(','); - split.forEach((s,i) => { - if(s.startsWith('function') || s.startsWith('(')) { - parsed[i] = parseFunctionFromText(s); - } - }); - let joined = `[${split.join(',')}]`; - joined = joined.replace(/'/g,'"'); - let parsed = JSON.parse(joined) as any[]; - - //let {proxy, keys} = instantiateProxy(value, parsed); - - let proxy = graph.get(value); - let pkeys = Object.keys(proxy); - - - - propertydropdown.innerHTML = ""; - pkeys.forEach((k) => { - propertydropdown.insertAdjacentHTML('beforeend',``); - }); - - - propertydropdown.onchange = (ev) => { - let t = typeof proxy[propertydropdown.value]; - propertyInputType.value = t === "undefined" ? "string" : t; - if(t !== 'function') { - propertyInput.value = proxy[propertydropdown.value]; - } else propertyInput.value = ""; - } - setProp.onclick = (ev) => { - if(inpTypes[propertyInputType.value]) - inpTypes[propertyInputType.value](proxy, propertydropdown.value, propertyInput.value) - } - // createProxy.onclick = (ev) => { - // let props = { - // __node:nameInput.value ? { - // tag:nameInput.value - // } : undefined, - // __props:proxy - // //todo: could instead list all the non-functional values from proxy here so they get set on the proxy when the node is created - // }; - // let node = graph.add(props); - // addNodeToLGraph(node, graph, editor); - // nameInput.value = `${value}${Math.floor(Math.random()*1000000000000000)}`; - // } - //} - - nodeEditorContainer.style.display = ""; - - } - - return container; - - -} \ No newline at end of file diff --git a/examples/editing/styles.css b/examples/editing/styles.css deleted file mode 100644 index fd5f015b..00000000 --- a/examples/editing/styles.css +++ /dev/null @@ -1,31 +0,0 @@ -body { - margin: 0; - font-family: Arial, sans-serif; - } - - #editor { - position: relative; - width: 100%; - height: 100vh; - background-color: #eee; - } - - .node { - position: absolute; - padding: 10px; - border: 1px solid #444; - background-color: #fff; - cursor: move; - } - - .connection { - position: absolute; - width: 100%; - height: 100%; - } - - .connection-path { - stroke: #555; - stroke-width: 2px; - fill: none; - } \ No newline at end of file diff --git a/examples/editing/worker.ts b/examples/editing/worker.ts deleted file mode 100644 index 2d624555..00000000 --- a/examples/editing/worker.ts +++ /dev/null @@ -1,29 +0,0 @@ - -//functionality -import { WorkerService, workerCanvasRoutes, remoteGraphRoutes } from '../../index'; - -//wonder if we can have a scheme to dynamic import within the services? e.g. to bring in node-only or browser-only services without additional workers - -declare var WorkerGlobalScope; - -if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { - (self as any).SERVICE = new WorkerService({ - roots:{ - ...workerCanvasRoutes, - ...remoteGraphRoutes, //allows dynamic route loading - console, - mul:function(a,b) { return a * b; }, - - __listeners:{ - console:{ - mul:{ - __callback:'console.log' - } - } - } - } - }); -} - -export default self as any; - diff --git a/examples/advanced/eegnfb/index.css b/examples/eegnfb/index.css similarity index 100% rename from examples/advanced/eegnfb/index.css rename to examples/eegnfb/index.css diff --git a/examples/basics/graph/index.html b/examples/eegnfb/index.html similarity index 100% rename from examples/basics/graph/index.html rename to examples/eegnfb/index.html diff --git a/examples/advanced/eegnfb/index.ts b/examples/eegnfb/index.ts similarity index 99% rename from examples/advanced/eegnfb/index.ts rename to examples/eegnfb/index.ts index 0bfe0778..c822d6dc 100644 --- a/examples/advanced/eegnfb/index.ts +++ b/examples/eegnfb/index.ts @@ -1,7 +1,7 @@ //@ts-nocheck //resources -import { Service, WorkerCanvas, GraphNodeProperties, loaders, htmlloader, HTMLNodeProperties } from '../..//index'; +import { Service, WorkerCanvas, GraphNodeProperties, loaders, htmlloader, HTMLNodeProperties } from '../../build/main/index'; import { initDevice, workers, @@ -190,7 +190,8 @@ const webappHtml = { //let recording = false; let info = await initDevice( - Devices[mode][selected], + mode as 'BLE'|'USB'|'BLE_OTHER'|'USB_OTHER'|'OTHER', + selected, { devices:Devices, workerUrl:gsworker, diff --git a/examples/advanced/eegnfb/package-lock.json b/examples/eegnfb/package-lock.json similarity index 97% rename from examples/advanced/eegnfb/package-lock.json rename to examples/eegnfb/package-lock.json index f86a1b4a..b5dba6be 100644 --- a/examples/advanced/eegnfb/package-lock.json +++ b/examples/eegnfb/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp6104", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "browserfs": "^1.4.3", "device-decoder": "~0.3.3", @@ -90,7 +90,7 @@ "integrity": "sha512-69MgzxkeCemOFqDIbzux7RuDGp08fcChMYAPaIdKBceO1S4RTEwtjrXwJqbRZIRMSXQBU1ZYsJtfGuXVjKRDZw==", "dependencies": { "@capacitor-community/bluetooth-le": "~2.0.1", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "graphscript": "~0.2.24", "graphscript-services": "~0.2.25", "graphscript-services.gpu": "~0.2.24", @@ -117,7 +117,7 @@ "integrity": "sha512-uyHUrEb5tobSq4t1kgeNn6f9UEoTSLCA9XHCWbl60A0o228MBb6KXowwN0ZD+Bj0cPbguxldih6aXvXhUvMpmw==", "dependencies": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.11.0" @@ -128,7 +128,7 @@ "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.25.tgz", "integrity": "sha512-ZEREWh0AUKbRdwCsvSgonRN3IhF5+x+oWFFHUwHUWFvu2vruI0xiJXXp7hfBIbgUMGpEy9h2OUU6Doe/AELV5w==", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", @@ -141,7 +141,7 @@ "resolved": "https://registry.npmjs.org/graphscript-services.gpu/-/graphscript-services.gpu-0.2.24.tgz", "integrity": "sha512-ktwiPDFgxc7eRRrBwCgaiBD29IvstQS41S4MpbmLLzDj2r1P+R9AUMaTGnBqmi/u1NEfY1+lIVU0mU6U4QYoUA==", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.3", "gpujsutils": "~1.0.12", @@ -153,7 +153,7 @@ "resolved": "https://registry.npmjs.org/graphscript-services.storage/-/graphscript-services.storage-0.2.24.tgz", "integrity": "sha512-qqyJUHDD52Y3uZCmXRGh/oCxLDDzElknK4DShJRmalqqI+ajy81DMGkWeJOqGW450k3IrQDlaD5naxNxGBKd9g==", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", @@ -287,7 +287,7 @@ "integrity": "sha512-69MgzxkeCemOFqDIbzux7RuDGp08fcChMYAPaIdKBceO1S4RTEwtjrXwJqbRZIRMSXQBU1ZYsJtfGuXVjKRDZw==", "requires": { "@capacitor-community/bluetooth-le": "~2.0.1", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "graphscript": "~0.2.24", "graphscript-services": "~0.2.25", "graphscript-services.gpu": "~0.2.24", @@ -314,7 +314,7 @@ "integrity": "sha512-uyHUrEb5tobSq4t1kgeNn6f9UEoTSLCA9XHCWbl60A0o228MBb6KXowwN0ZD+Bj0cPbguxldih6aXvXhUvMpmw==", "requires": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.11.0" @@ -325,7 +325,7 @@ "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.25.tgz", "integrity": "sha512-ZEREWh0AUKbRdwCsvSgonRN3IhF5+x+oWFFHUwHUWFvu2vruI0xiJXXp7hfBIbgUMGpEy9h2OUU6Doe/AELV5w==", "requires": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", @@ -338,7 +338,7 @@ "resolved": "https://registry.npmjs.org/graphscript-services.gpu/-/graphscript-services.gpu-0.2.24.tgz", "integrity": "sha512-ktwiPDFgxc7eRRrBwCgaiBD29IvstQS41S4MpbmLLzDj2r1P+R9AUMaTGnBqmi/u1NEfY1+lIVU0mU6U4QYoUA==", "requires": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.3", "gpujsutils": "~1.0.12", @@ -350,7 +350,7 @@ "resolved": "https://registry.npmjs.org/graphscript-services.storage/-/graphscript-services.storage-0.2.24.tgz", "integrity": "sha512-qqyJUHDD52Y3uZCmXRGh/oCxLDDzElknK4DShJRmalqqI+ajy81DMGkWeJOqGW450k3IrQDlaD5naxNxGBKd9g==", "requires": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", diff --git a/examples/advanced/eegnfb/package.json b/examples/eegnfb/package.json similarity index 79% rename from examples/advanced/eegnfb/package.json rename to examples/eegnfb/package.json index acee93e6..2ad0b3ba 100644 --- a/examples/advanced/eegnfb/package.json +++ b/examples/eegnfb/package.json @@ -20,13 +20,16 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { + "@capacitor-community/bluetooth-le": "^2.0.1", "browserfs": "^1.4.3", - "device-decoder": "~0.4.3", - "device-decoder.third-party": "~0.2.2", - "graphscript": "~0.2.26", - "howler": "~2.2.3" + "device-decoder": "~0.3.4", + "device-decoder.third-party": "~0.1.24", + "graphscript": "^0.2.28", + "howler": "~2.2.3", + "web-worker": "^1.2.0", + "webgl-plot-utils": "^0.3.15" }, "nodemonConfig": { "env": { diff --git a/examples/advanced/eegnfb/src/assets/kalimba.wav b/examples/eegnfb/src/assets/kalimba.wav similarity index 100% rename from examples/advanced/eegnfb/src/assets/kalimba.wav rename to examples/eegnfb/src/assets/kalimba.wav diff --git a/examples/advanced/eegnfb/src/assets/phonk.wav b/examples/eegnfb/src/assets/phonk.wav similarity index 100% rename from examples/advanced/eegnfb/src/assets/phonk.wav rename to examples/eegnfb/src/assets/phonk.wav diff --git a/examples/advanced/eegnfb/src/assets/synthflute.wav b/examples/eegnfb/src/assets/synthflute.wav similarity index 100% rename from examples/advanced/eegnfb/src/assets/synthflute.wav rename to examples/eegnfb/src/assets/synthflute.wav diff --git a/examples/advanced/eegnfb/tinybuild.config.js b/examples/eegnfb/tinybuild.config.js similarity index 100% rename from examples/advanced/eegnfb/tinybuild.config.js rename to examples/eegnfb/tinybuild.config.js diff --git a/examples/graph/index.html b/examples/graph/index.html new file mode 100644 index 00000000..ea33ac29 --- /dev/null +++ b/examples/graph/index.html @@ -0,0 +1,38 @@ + + + + + + +
      + + + \ No newline at end of file diff --git a/examples/graph/index.ts b/examples/graph/index.ts new file mode 100644 index 00000000..8d244fb7 --- /dev/null +++ b/examples/graph/index.ts @@ -0,0 +1,5 @@ +import { OperationsManager } from '../../tests/utils' +import * as config from "./operations"; + +const manager = new OperationsManager(config) +manager.runAll() \ No newline at end of file diff --git a/examples/graph/nodes/nodeA.js b/examples/graph/nodes/nodeA.js new file mode 100644 index 00000000..45e5f8a5 --- /dev/null +++ b/examples/graph/nodes/nodeA.js @@ -0,0 +1,34 @@ +import { log } from '../../../tests/utils/index' + + +export const x = 5 +export const y = 2 + +export const jump = (input)=>{ + const message = 'jump!' + log.add(message) + + let output = 'jumped' + if (input) output = output + input + return output +} + +export const listenerUpdates = { + 'nodeB.nodeC': undefined, + 'nodeB.nodeC.z': undefined +} + +export const __listeners = { + 'nodeB.x':'jump', //listeners in a scope are bound to 'this' node + 'nodeB.nodeC':function(input){ + const message = 'nodeA listener: nodeC operator returned:' + log.add(message) + listenerUpdates['nodeB.nodeC'] = input + }, + 'nodeB.nodeC.z':function(input){ + const message = 'nodeA listener: nodeC z prop changed:' + log.add(message) + listenerUpdates['nodeB.nodeC.z'] = input + }, + 'nodeE': 'jump' +} \ No newline at end of file diff --git a/examples/graph/operations.ts b/examples/graph/operations.ts new file mode 100644 index 00000000..bd95382b --- /dev/null +++ b/examples/graph/operations.ts @@ -0,0 +1,182 @@ + +import { Graph, GraphNode } from "../../src/core/Graph"; +import model from './tree' + +import { loaders as includedLoaders } from "../../src/loaders"; +import htmlLoader from '../../src/loaders/html/html.loader' +import { isNode, log } from '../../tests/utils/index' + +type GlobalType = { + state: any, + nodeIdMap: any, + data: any, + + graph: Graph, + nodeAInstance: any, + graph2: Graph, + popped: GraphNode, +} + +export let globals = {} as GlobalType + +export const start = () => { + + const loaders = { + ...includedLoaders + } as any + + if (!isNode) loaders.html = htmlLoader; + + const nodeIdMap = {} + const state = { + data: {}, // Will be replaced by graph state + get: function (node, key) { + node = nodeIdMap[node] + const id = ((key) ? [node, key].join('.') : node) + return this.data[id] + } // Get the latest state from a global object + } + + globals.state = state + globals.nodeAInstance = model.nodeA + + const graph = new Graph({ + roots: model, + loaders, + }); + + log.addHeader('Graph constructed') + + graph.__node.nodes.forEach(n => { + const root = n.__node + nodeIdMap[root.tag] = root.unique; + }) + + globals.state.data = graph.__node.state.data + globals.nodeIdMap = nodeIdMap + globals.graph = graph + + return graph; +} + +export const stop = () => { + return globals.graph.remove('nodeE') +} + +export const operations = [ + { + name: "graph.run('nodeG')", + function: () => globals.graph.run('nodeG') + }, + { + name: "nodeAInstance.x = 1", + function: () => { + globals.nodeAInstance.x = 1; //should trigger nodeA.x listener on nodeC + return globals.nodeAInstance.x; + } + }, + { + name: "graph.get('nodeA').x = 2", + function: () => { + const nodeA = globals.graph.get('nodeA'); + nodeA.x = 2; //same thing + return nodeA.x; + } + }, + { + name: "graph.get('nodeB').x += 1", + function: () => { + const nodeB = globals.graph.get('nodeB'); + nodeB.x += 1; //should trigger nodeA listener jump() + return nodeB.x; + } + }, + { + name: "graph.run('nodeB.nodeC', 4)", + function: () => globals.graph.run('nodeB.nodeC', 4) //should trigger nodeA listener + }, + { + name: "graph.get('nodeB.nodeC').z += 1", + function: () => { + const nodeC = globals.graph.get('nodeB.nodeC') + nodeC.z += 1; + return nodeC.z; + } + }, + { + name: "graph.get('nodeA').jump()", + function: () => { + const nodeA = globals.graph.get('nodeA'); + return nodeA.jump(); //should trigger nodeC listener + } + }, + { + name: "graph.run('nodeA.jump')", + function: () => globals.graph.run('nodeA.jump') //same + }, + + + // NOTE: Tests run up to here... + { + header: "graph2 constructed", + function: () => { + globals.graph2 = new Graph({roots: { graph: globals.graph }}); + return globals.graph2; + } + }, + { + header: "nodeB removed!", + function: () => { + globals.popped = globals.graph.remove('nodeB'); + console.log(globals.popped.__node.tag, 'popped') + return globals.popped; + } + }, + { + name: "graph.get('nodeA').jump()", + function: () => { + const nodeA = globals.graph.get('nodeA'); + return nodeA.jump(); //should NOT trigger nodeC listener + } + }, + { + header: "nodeB reparented to graph2", + function: () => { + globals.graph2.add(globals.popped); //reparent nodeB to the parent graph + console.log(JSON.stringify(globals.graph.__node.state.triggers)); //should be no triggers left + return globals.popped + } + }, + { + name: "popped.x += 1", + function: () => { + globals.popped.x += 1; //should no longer trigger nodeA.x listener on nodeC + return globals.popped.x; + } + }, + { + name: "popped.__children.nodeC.__operator(1)", + function: () => { + const children = globals.popped.__children as any + children.nodeC.__operator(1) + } + }, + { + name: "graph.get('nodeA').jump()", + function: () => globals.graph.get('nodeA').jump() //this should not trigger the nodeA.jump listener on nodeC now + }, + { + header: 'Remove nodeE after next update', + function: () => { + return new Promise((resolve) => { + setTimeout(()=>{ + const nodeE = stop() + resolve(nodeE) + } , 1000) + }) + } + } +] + + +export default operations \ No newline at end of file diff --git a/examples/basics/sync_async/package.json b/examples/graph/package.json similarity index 94% rename from examples/basics/sync_async/package.json rename to examples/graph/package.json index 77af2ce0..e4a6e7a7 100644 --- a/examples/basics/sync_async/package.json +++ b/examples/graph/package.json @@ -1,5 +1,5 @@ { - "name": "tinybuildapp442", + "name": "tinybuildapp1331", "version": "0.0.0", "description": "Barebones esbuild and test node server implementation. For building", "main": "index.js", @@ -20,7 +20,7 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": {}, "devDependencies": {}, "nodemonConfig": { diff --git a/examples/loaders/basic/tinybuild.config.js b/examples/graph/tinybuild.config.js similarity index 93% rename from examples/loaders/basic/tinybuild.config.js rename to examples/graph/tinybuild.config.js index 22f73fa6..b0f98edf 100644 --- a/examples/loaders/basic/tinybuild.config.js +++ b/examples/graph/tinybuild.config.js @@ -10,7 +10,7 @@ const config = { bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, + minify: false, sourcemap: false //globalThis:null //'mymodule' //globals:{'index.js':['Graph']} @@ -20,14 +20,14 @@ const config = { debug: false, protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 + port: 8000, //e.g. port 80, 443, 8000 startpage: "index.html", //home page socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost hotreload: 5000, //hotreload websocket server port //watch: ['../'], //watch additional directories other than the current working directory pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) + python__node: 7000, //websocket relay port (relays messages to client from nodejs that were sent to it by python) errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions diff --git a/examples/graph/tree.js b/examples/graph/tree.js new file mode 100644 index 00000000..0c17746a --- /dev/null +++ b/examples/graph/tree.js @@ -0,0 +1,85 @@ +import * as nodeA from './nodes/nodeA.js' +import { isNode, log } from '../../tests/utils/index' + +class nodeClass { //treated as a class to instance rather than a function to set as __operator + __operator = () => { + const message = 'class instanced node called!' + log.add(message) + return true + } +} + +let tree = { + + nodeA: Object.assign({}, nodeA), // Avoid issues with ESM + + nodeB:{ + x:3, + y:4, + __children:{ + nodeC:{ + z:4, + listenerUpdates: { + 'nodeA.jump': undefined, + 'nodeA.x': undefined + }, + __operator:function(a) { + this.z += a; + const message = 'nodeC operator: nodeC z prop added to' + log.add(message) + return this.z; + }, + __listeners:{ + 'nodeA.x':function(newX) { + const message = 'nodeC listener: nodeA x prop updated' + log.add(message) + this.listenerUpdates['nodeA.x'] = newX + }, + 'nodeA.jump':function(jump) { + const message = 'nodeC listener: nodeA ' + log.add(message) + this.listenerUpdates['nodeA.jump'] = jump + } + } + } + } + + }, + + nodeD:(a,b,c)=>{ return a+b+c; }, //becomes the .__operator prop and calling triggers setState for this tag (or nested tag if a child) + + + nodeE:{ + __operator:function (){ + const message = 'looped' + log.add(message) + return true; + }, + __node:{ + loop:1000, + looping:true + } + }, + + nodeG: nodeClass + +}; + + +if (!isNode) { + tree.nodeF = { + __props:document.createElement('div'), //properties on the '__props' object will be proxied and mutatable as 'this' on the node. E.g. for representing HTML elements + __onconnected:function (node) { + this.innerHTML = 'Test'; + this.style.backgroundColor = 'green'; + // document.body.appendChild(this.__props); + // console.log(this,this.__props); + }, + __ondisconnected:function(node) { + document.body.removeChild(this.__props); + } + + } +} + +export default tree \ No newline at end of file diff --git a/examples/basics/listeners/index.html b/examples/html/index.html similarity index 100% rename from examples/basics/listeners/index.html rename to examples/html/index.html diff --git a/examples/loaders/html/index.ts b/examples/html/index.ts similarity index 57% rename from examples/loaders/html/index.ts rename to examples/html/index.ts index c47c7984..76adcba9 100644 --- a/examples/loaders/html/index.ts +++ b/examples/html/index.ts @@ -1,22 +1,4 @@ -import { - Graph, - wchtmlloader, //includes a web component library for custom html elements - htmlloader, //basic html elements - HTMLNodeProperties -} from '../../../index' - -let component = { - __template:`
      Hello world!
      `, - __element:'web-component', - __onrender:function (elm){ - console.log('rendered!'); - (document.getElementById('wcdiv') as HTMLElement).onclick = (ev) => { - if((ev.target as HTMLElement).style.backgroundColor !== 'red') - setTimeout(()=>{(ev.target as HTMLElement).style.backgroundColor = '';},1000); - (ev.target as HTMLElement).style.backgroundColor = 'red'; - } - } -} as HTMLNodeProperties +import {Graph, wchtmlloader, HTMLNodeProperties} from '../../build/main/index' let roots = { @@ -42,7 +24,18 @@ let roots = { ev.target.innerHTML = 'Clicked!'; } } as HTMLNodeProperties, - component + component:{ + __template:`
      Hello world!
      `, + __element:'web-component', + __onrender:function (elm){ + console.log('rendered!'); + (document.getElementById('wcdiv') as HTMLElement).onclick = (ev) => { + if((ev.target as HTMLElement).style.backgroundColor !== 'red') + setTimeout(()=>{(ev.target as HTMLElement).style.backgroundColor = '';},1000); + (ev.target as HTMLElement).style.backgroundColor = 'red'; + } + } + } as HTMLNodeProperties } } as HTMLNodeProperties } @@ -50,7 +43,6 @@ let roots = { let graph = new Graph({ roots, loaders:{ - //htmlloader wchtmlloader } }) \ No newline at end of file diff --git a/examples/loaders/html/package-lock.json b/examples/html/package-lock.json similarity index 94% rename from examples/loaders/html/package-lock.json rename to examples/html/package-lock.json index 8847d868..ccc457cc 100644 --- a/examples/loaders/html/package-lock.json +++ b/examples/html/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp8682", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "web-worker": "^1.2.0" }, @@ -16,7 +16,7 @@ "../../../../../AppData/Roaming/npm/node_modules/tinybuild": { "version": "0.3.190", "extraneous": true, - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "chokidar": "~3.5.3", "esbuild": "~0.14.49", diff --git a/examples/loaders/html/package.json b/examples/html/package.json similarity index 96% rename from examples/loaders/html/package.json rename to examples/html/package.json index fcbc11a2..865c9195 100644 --- a/examples/loaders/html/package.json +++ b/examples/html/package.json @@ -20,7 +20,7 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "web-worker": "^1.2.0" }, diff --git a/examples/basics/listeners/tinybuild.config.js b/examples/html/tinybuild.config.js similarity index 100% rename from examples/basics/listeners/tinybuild.config.js rename to examples/html/tinybuild.config.js diff --git a/examples/services/http/backend.ts b/examples/httpserver/backend.ts similarity index 95% rename from examples/services/http/backend.ts rename to examples/httpserver/backend.ts index 77dbf649..e3d4186f 100644 --- a/examples/services/http/backend.ts +++ b/examples/httpserver/backend.ts @@ -1,5 +1,5 @@ -import { HTTPbackend, ServerProps, ServerInfo, SSEbackend, SSEProps, WSSbackend, SocketServerProps } from "../../../index.node"//"graphscript-node"; -import { Router } from '../../../src/services/router/Router'; +import { HTTPbackend, ServerProps, ServerInfo, SSEbackend, SSEProps, WSSbackend, SocketServerProps } from "../../build/node/index.node"//"graphscript-node"; +import { Router } from '../../src/services/router/Router'; function exitHandler(options, exitCode) { @@ -30,7 +30,7 @@ let server = router.run( host:'localhost', port:8080, pages:{ - '/*':{ + '/':{ template:`
      Nice...
      `, onrequest:(self,node,req,res)=>{ node.get = `

      Hello World!! The Time: ${new Date(Date.now()).toISOString()}

      ` diff --git a/examples/services/http/package-lock.json b/examples/httpserver/package-lock.json similarity index 99% rename from examples/services/http/package-lock.json rename to examples/httpserver/package-lock.json index 836674f9..3e14380e 100644 --- a/examples/services/http/package-lock.json +++ b/examples/httpserver/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp9941", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript-node": "~0.0.138" } diff --git a/examples/services/http/package.json b/examples/httpserver/package.json similarity index 91% rename from examples/services/http/package.json rename to examples/httpserver/package.json index 3ac6695b..87bb176c 100644 --- a/examples/services/http/package.json +++ b/examples/httpserver/package.json @@ -19,8 +19,10 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { + "better-sse": "^0.8.0", + "graphscript-node": "~0.1.41" }, "nodemonConfig": { "env": { diff --git a/examples/services/http/tinybuild.config.js b/examples/httpserver/tinybuild.config.js similarity index 100% rename from examples/services/http/tinybuild.config.js rename to examples/httpserver/tinybuild.config.js diff --git a/examples/loaders/3dmodel/tinybuild.config.js b/examples/loaders/3dmodel/tinybuild.config.js deleted file mode 100644 index 749308ef..00000000 --- a/examples/loaders/3dmodel/tinybuild.config.js +++ /dev/null @@ -1,36 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/loaders/basic/index.html b/examples/loaders/basic/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/loaders/basic/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/loaders/basic/index.ts b/examples/loaders/basic/index.ts deleted file mode 100644 index ec19dff7..00000000 --- a/examples/loaders/basic/index.ts +++ /dev/null @@ -1,48 +0,0 @@ -import {Graph, Loader, GraphNodeProperties, Roots } from '../../../src/core/Graph' -import { loop } from '../../../src/loaders/index' - - -const roots = { - - loopNode:{ - __element:'div', - innerHTML:`
      Hello world!
      `, - __operator:function (){ - const message = `looped: ${performance.now().toFixed(1)}ms`; - this.insertAdjacentHTML('beforeend',`
      ${message}
      `) - console.log(message); - - return true; - }, - __node:{ - loop:1000, //note this doesn't result in perfect 1000ms loops due to how javascript prioritizes stuff, so it's only relative - looping:true - } - } as GraphNodeProperties - -} as Roots - -let customHTMLLoader:Loader = ( - node, -) => { - if(typeof node.__element == 'string') { - node.__props = document.createElement(node.__element); - if(node.__props instanceof HTMLElement) { - for(const key in node) { - node.__props[key] = node[key]; - } - node.__proxyObject(node.__props); - - document.body.insertAdjacentElement('beforeend',node.__props) - } - } -} - -const graph = new Graph({ - roots, - loaders:{ - customHTMLLoader, - loop //load order can matter depending on expected proxies etc like in this case - } -}); - diff --git a/examples/loaders/basic/package.json b/examples/loaders/basic/package.json deleted file mode 100644 index 0f4a02f7..00000000 --- a/examples/loaders/basic/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "tinybuildapp503", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "LGPL-3.0-or-later", - "dependencies": {}, - "devDependencies": {}, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} \ No newline at end of file diff --git a/examples/loaders/html/index.html b/examples/loaders/html/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/loaders/html/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/loaders/html/tinybuild.config.js b/examples/loaders/html/tinybuild.config.js deleted file mode 100644 index 749308ef..00000000 --- a/examples/loaders/html/tinybuild.config.js +++ /dev/null @@ -1,36 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/loaders/web_components/components/draggable.js b/examples/loaders/web_components/components/draggable.js deleted file mode 100644 index e7031a78..00000000 --- a/examples/loaders/web_components/components/draggable.js +++ /dev/null @@ -1,43 +0,0 @@ -//https://www.w3schools.com/howto/howto_js_draggable.asp -// Make the DIV element draggable: - -export function makeDraggable(elmnt) { - var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; - if (document.getElementById(elmnt.id + "header")) { - // if present, the header is where you move the DIV from: - document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; - } else { - // otherwise, move the DIV from anywhere inside the DIV: - elmnt.onmousedown = dragMouseDown; - } - - function dragMouseDown(e) { - e = e || window.event; - e.preventDefault(); - // get the mouse cursor position at startup: - pos3 = e.clientX; - pos4 = e.clientY; - document.onmouseup = closeDragElement; - // call a function whenever the cursor moves: - document.onmousemove = elementDrag; - } - - function elementDrag(e) { - e = e || window.event; - e.preventDefault(); - // calculate the new cursor position: - pos1 = pos3 - e.clientX; - pos2 = pos4 - e.clientY; - pos3 = e.clientX; - pos4 = e.clientY; - // set the element's new position: - elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; - elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; - } - - function closeDragElement() { - // stop moving when mouse button is released: - document.onmouseup = null; - document.onmousemove = null; - } -} \ No newline at end of file diff --git a/examples/loaders/web_components/components/node/node.css b/examples/loaders/web_components/components/node/node.css deleted file mode 100644 index 3029b896..00000000 --- a/examples/loaders/web_components/components/node/node.css +++ /dev/null @@ -1,4 +0,0 @@ -.nodeheader { /* component css tags should probably be sufficiently unique like other component libraries, or just use inline styles */ - text-align:center; - width: max-content; -} \ No newline at end of file diff --git a/examples/loaders/web_components/components/node/node.html b/examples/loaders/web_components/components/node/node.html deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/loaders/web_components/components/node/node.ts b/examples/loaders/web_components/components/node/node.ts deleted file mode 100644 index 12214269..00000000 --- a/examples/loaders/web_components/components/node/node.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { makeDraggable } from "../draggable"; -import { PointHTML } from "../point/point"; - -//@ts-ignore -import style from './node.css'; //in esbuild, set loader:{'.css':'text' } -//@ts-ignore -import html from './node.html'; //add to loader: {...'.html':'text'} - -export class NodeHTML { - - tagName = 'graph-node'; - - __template = '' // = html; - __css = style; - __components = { - 'custom-point-name': PointHTML - } - - draggable=true; - - style = { - position:'absolute', - padding:'10px', - display:'flex', - borderRadius:'10%', - backgroundColor:'lightblue', - cursor:'pointer' - }; - - __onrender = function() { - this.insertAdjacentHTML('beforeend', ` -
      -
      Drag ${this.__node.tag ?? 'Me'}!
      -
      -
      - - - - - - -
      -
      - `) - } - - __onconnected = function() { - makeDraggable(this); //the htmlElement properties are bound to 'this' as well as 'this.__props' so you can manipulate the node directly - }; - - // __children={ - // container:{ - // __element:'div', - // __children:{ - // header:{ - // __element:'div', - // innerHTML:'Drag Me!', - // className:'nodeheader' - // }, - // ln:{__template:'
      '}, - // body:{ - // __element:'div', - // style:{ - // display:'flex' - // }, - // __children:{ - // inputs:{ - // __element:'span', - // style:{ - // width:'12.5%' - // } - // }, - // content:{ - // __element:'span', - // style:{ - // width:'75%' - // } - // }, - // outputs:{ - // __element:'span', - // style:{ - // width:'12.5%' - // }, - // __children:{ - // point:PointHTML, - // point2:PointHTML - // } - // } - // } - // } - // } - // } - // }; - -} \ No newline at end of file diff --git a/examples/loaders/web_components/components/point/point.css b/examples/loaders/web_components/components/point/point.css deleted file mode 100644 index e06d2a6c..00000000 --- a/examples/loaders/web_components/components/point/point.css +++ /dev/null @@ -1,10 +0,0 @@ -.point { - width: 1px; - height: 1px; - border: 10px solid transparent; - border-left-color: greenyellow; - position: relative; -} -.point:hover { - border-left-color: yellow; -} diff --git a/examples/loaders/web_components/components/point/point.html b/examples/loaders/web_components/components/point/point.html deleted file mode 100644 index ad99828e..00000000 --- a/examples/loaders/web_components/components/point/point.html +++ /dev/null @@ -1,2 +0,0 @@ -
      -
      \ No newline at end of file diff --git a/examples/loaders/web_components/components/point/point.ts b/examples/loaders/web_components/components/point/point.ts deleted file mode 100644 index 88a3f6c0..00000000 --- a/examples/loaders/web_components/components/point/point.ts +++ /dev/null @@ -1,18 +0,0 @@ - -//@ts-ignore -import style from './point.css'; //in esbuild, set loader:{'.css':'text' } -//@ts-ignore -import html from './point.html'; //add to loader: {...'.html':'text'} - -export class PointHTML { - - tagName='interactive-point'; - - __template = html; - __css = style; - - __onconnected = function() { - //console.log(this); - }; - -} \ No newline at end of file diff --git a/examples/loaders/web_components/index.html b/examples/loaders/web_components/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/loaders/web_components/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/loaders/web_components/index.ts b/examples/loaders/web_components/index.ts deleted file mode 100644 index 55cf875b..00000000 --- a/examples/loaders/web_components/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -import {Graph, GraphNode, wchtmlloader} from '../../../index' -import { NodeHTML } from './components/node/node'; - -new Graph({ - roots:{ - draggable: NodeHTML, - other: NodeHTML - }, - loaders:{ - wchtmlloader - } -}); \ No newline at end of file diff --git a/examples/loaders/web_components/package-lock.json b/examples/loaders/web_components/package-lock.json deleted file mode 100644 index 89434d34..00000000 --- a/examples/loaders/web_components/package-lock.json +++ /dev/null @@ -1,129 +0,0 @@ -{ - "name": "tinybuildapp5363", - "version": "0.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "tinybuildapp5363", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "dependencies": { - "graphscript": "^0.2.80" - }, - "devDependencies": {} - }, - "../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.202", - "extraneous": true, - "license": "LGPL-3.0-or-later", - "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.17.10", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.9.5" - } - }, - "node_modules/better-sse": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz", - "integrity": "sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA==", - "engines": { - "node": ">=12", - "pnpm": ">=6" - } - }, - "node_modules/brainsatplay-math": { - "version": "0.0.25", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", - "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" - }, - "node_modules/bson-objectid": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", - "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" - }, - "node_modules/graphscript": { - "version": "0.2.80", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.80.tgz", - "integrity": "sha512-TU6LLYPqpS5acZqu3+wrkwp+IWZixloVhG/UNFFbxW8OcdLFeW7rpYesmemb307UVKqkCeod9iOwgz5Cgfsl0w==", - "dependencies": { - "better-sse": "^0.8.0", - "brainsatplay-math": "~0.1.0", - "bson-objectid": "~2.0.3", - "web-worker": "~1.2.0", - "ws": "~8.11.0" - } - }, - "node_modules/web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - }, - "node_modules/ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - }, - "dependencies": { - "better-sse": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz", - "integrity": "sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA==" - }, - "brainsatplay-math": { - "version": "0.0.25", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", - "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" - }, - "bson-objectid": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", - "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" - }, - "graphscript": { - "version": "0.2.80", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.80.tgz", - "integrity": "sha512-TU6LLYPqpS5acZqu3+wrkwp+IWZixloVhG/UNFFbxW8OcdLFeW7rpYesmemb307UVKqkCeod9iOwgz5Cgfsl0w==", - "requires": { - "better-sse": "^0.8.0", - "brainsatplay-math": "~0.1.0", - "bson-objectid": "~2.0.3", - "web-worker": "~1.2.0", - "ws": "~8.11.0" - } - }, - "web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - }, - "ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", - "requires": {} - } - } -} diff --git a/examples/loaders/web_components/package.json b/examples/loaders/web_components/package.json deleted file mode 100644 index ab88c2bf..00000000 --- a/examples/loaders/web_components/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "tinybuildapp5363", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "LGPL-3.0-or-later", - "dependencies": { - "graphscript": "^0.2.80" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} diff --git a/examples/loaders/web_components/tinybuild.config.js b/examples/loaders/web_components/tinybuild.config.js deleted file mode 100644 index f162fe94..00000000 --- a/examples/loaders/web_components/tinybuild.config.js +++ /dev/null @@ -1,37 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false, - loader:{'.html':'text', '.css':'text' } - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/services/workers/pipelining/index.html b/examples/services/workers/pipelining/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/pipelining/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/services/workers/pipelining/index.ts b/examples/services/workers/pipelining/index.ts deleted file mode 100644 index cc006d41..00000000 --- a/examples/services/workers/pipelining/index.ts +++ /dev/null @@ -1,113 +0,0 @@ - -import { WorkerInfo, WorkerService, remoteGraphRoutes } from '../../../../index'; - -import worker from './worker' - -//main thread - - -const graph = new WorkerService({ - //props:{} //could set the props instead of globalThis but it really does not matter unless you want to bake in for more complex service modules - roots:{ - ...remoteGraphRoutes, - } -}); - -console.log('Worker Service', graph); - - -const worker1 = graph.addWorker({url:worker}) as WorkerInfo; -const worker2 = graph.addWorker({url:worker}) as WorkerInfo; -const worker3 = graph.addWorker({url:worker}) as WorkerInfo; - -//simulate long tasks -function taskA(input) { // SCOPE REFACTOR: Might actually need to pass self and origin... - return new Promise((res,rej) => { - setTimeout(() => { - console.log(input,42); - res(42); - }, 3000) //long task - }); -}; - -function taskB(input) { // SCOPE REFACTOR: Might actually need to pass self and origin... - return new Promise((res,rej) => { - setTimeout(() => { - console.log(input,42); - res(42); - }, 1000) //long task - }); -}; - -function taskC(input) { // SCOPE REFACTOR: Might actually need to pass self and origin... - return new Promise((res,rej) => { - setTimeout(() => { - console.log(input,42); - res(42); - }, 1500) //long task - }); -}; - -function subTaskA(input:number) { - console.log('multiplying',input,'by 10'); - return input * 10; -} - -function subTaskB(input:number) { - console.log('applying log to',input); - return Math.log(input); -} - -graph.run('transferFunction', - taskA, - worker1, - 'task' //in case of minification really -); - -graph.run('transferFunction', - taskB, - worker2, - 'task' -); - -graph.run('transferFunction', - taskC, - worker3, - 'task' -); - - -//now for a message channel pipeline. -graph.run('transferFunction', - subTaskA, - worker1, - 'subTaskA' -).then(console.log); - -graph.run('transferFunction', - subTaskB, - worker2, - 'subTaskB' -).then(console.log); - -let portId = graph.establishMessageChannel(worker1, worker2); - -//subscribe worker 2 to worker 1 directly (no overhead on main thread) -worker2.post('subscribeToWorker',[ - 'subTaskA', - portId, - 'subTaskB' -]); - -//now subscribe to the output on the main thread (or it could be a rendering thread etc., mind the rules of using threads!) -worker2.subscribe('subTaskB',(res) => { - console.log('result from worker2', res); -}).then(() => { - worker1.run('subTaskA', 42); //makes sure this runs after worker\2 is ready -}); - - - -worker1.run('task','What is the meaning of life?'); -worker2.run('task','What is the meaning of life?'); -worker3.run('task','What is the meaning of life?'); diff --git a/examples/services/workers/pipelining/package-lock.json b/examples/services/workers/pipelining/package-lock.json deleted file mode 100644 index 1e72f344..00000000 --- a/examples/services/workers/pipelining/package-lock.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "tinybuildapp9800", - "version": "0.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "tinybuildapp9800", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "dependencies": { - "web-worker": "^1.2.0" - }, - "devDependencies": {} - }, - "../../../../../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.205", - "extraneous": true, - "license": "LGPL-3.0-or-later", - "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.17.10", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.9.5" - } - }, - "node_modules/web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - } - } -} diff --git a/examples/services/workers/pipelining/package.json b/examples/services/workers/pipelining/package.json deleted file mode 100644 index 7b486bbd..00000000 --- a/examples/services/workers/pipelining/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "tinybuildapp9800", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "LGPL-3.0-or-later", - "dependencies": { - "web-worker": "^1.2.0" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} diff --git a/examples/services/workers/pipelining/tinybuild.config.js b/examples/services/workers/pipelining/tinybuild.config.js deleted file mode 100644 index 749308ef..00000000 --- a/examples/services/workers/pipelining/tinybuild.config.js +++ /dev/null @@ -1,36 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/services/workers/pipelining/worker.ts b/examples/services/workers/pipelining/worker.ts deleted file mode 100644 index 64639d93..00000000 --- a/examples/services/workers/pipelining/worker.ts +++ /dev/null @@ -1,21 +0,0 @@ - -import { WorkerService, remoteGraphRoutes } from '../../../../index'; - -//worker threads - -declare var WorkerGlobalScope; - -if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { - - const worker = new WorkerService({ - //props:{} //could set the props instead of globalThis but it really does not matter unless you want to bake in for more complex service modules - roots:{ - ...remoteGraphRoutes, - } - }); - - console.log('worker', worker) - -} - -export default self as any; diff --git a/examples/services/workers/workerECS/index.html b/examples/services/workers/workerECS/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/workerECS/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/services/workers/workercanvas/index.html b/examples/services/workers/workercanvas/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/workercanvas/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/services/workers/workerthreejs/index.html b/examples/services/workers/workerthreejs/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/workerthreejs/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/advanced/webrtcrouter/README.md b/examples/webrtcrouter/README.md similarity index 100% rename from examples/advanced/webrtcrouter/README.md rename to examples/webrtcrouter/README.md diff --git a/examples/advanced/webrtcrouter/backend.ts b/examples/webrtcrouter/backend.ts similarity index 91% rename from examples/advanced/webrtcrouter/backend.ts rename to examples/webrtcrouter/backend.ts index 25177e2d..84ac039d 100644 --- a/examples/advanced/webrtcrouter/backend.ts +++ b/examples/webrtcrouter/backend.ts @@ -11,12 +11,12 @@ process.on('exit', exitHandler.bind(null,{cleanup:true})); process.on('SIGINT', exitHandler.bind(null, {exit:true})); -import { Router, User } from "../../../src/services/router/Router"; -import { SocketServerProps, WSSbackend } from "../../../src/services/wss/WSS.node"; -import { SSEbackend, SSEProps } from "../../../src/services/sse/SSE.node"; -import { HTTPbackend, ServerProps } from "../../../src/services/http/HTTP.node"; -import { SessionsService } from "../../../src/services/sessions/sessions.service"; -import { scriptBoilerPlate } from "../../../src/services/http/boilerplate"; +import { Router, User } from "../../src/services/router/Router"; +import { SocketServerProps, WSSbackend } from "../../src/services/wss/WSS.node"; +import { SSEbackend, SSEProps } from "../../src/services/sse/SSE.node"; +import { HTTPbackend, ServerProps } from "../../src/services/http/HTTP.node"; +import { SessionsService } from "../../src/services/sessions/sessions.service"; +import { scriptBoilerPlate } from "../../src/services/http/boilerplate"; const router = new Router({ graph:{ diff --git a/examples/advanced/webrtcrouter/frontend.ts b/examples/webrtcrouter/frontend.ts similarity index 93% rename from examples/advanced/webrtcrouter/frontend.ts rename to examples/webrtcrouter/frontend.ts index c0519715..4c68619c 100644 --- a/examples/advanced/webrtcrouter/frontend.ts +++ b/examples/webrtcrouter/frontend.ts @@ -1,28 +1,10 @@ -import { HTTPfrontend } from '../../../src/services/http/HTTP.browser'; -import { Router } from '../../../src/services/router/Router' -import { EventSourceProps, SSEfrontend } from '../../../src/services/sse/SSE.browser'; -import { SessionsService } from '../../../src/services/sessions/sessions.service'; -import { WebRTCfrontend, WebRTCInfo } from '../../../src/services/webrtc/WebRTC.browser'; -import { WebSocketProps, WSSfrontend } from '../../../src/services/wss/WSS.browser'; -import {Graph, htmlloader} from '../../../index' - -//how it works -//https://hacks.mozilla.org/2013/07/webrtc-and-the-ocean-of-acronyms/ - -/* Execution. A Signal channel is an intermediary to pass data, e.g. a socket server. -________________________________________________________ -| peer A | STUN | TURN | Signal channel | Peer B | - - x-whoamI-> - <--NAT---x - x---make channel--> - x----------offer sdp------------>|x------------> //make call - <---------answer sdp------------x|<------------x //accept call - x------ice candidate A---------->|x------------> //send communication stuff - <------ice candidate B----------x|<------------x //send communication stuff back - <---------------who am I?-------------x //then this stuff establishes the data channels and streams (or something) - x--------------IP and port------------> -*/ +import { HTTPfrontend } from '../../src/services/http/HTTP.browser'; +import { Router } from '../../src/services/router/Router' +import { EventSourceProps, SSEfrontend } from '../../src/services/sse/SSE.browser'; +import { SessionsService } from '../../src/services/sessions/sessions.service'; +import { WebRTCfrontend, WebRTCInfo } from '../../src/services/webrtc/WebRTC.browser'; +import { WebSocketProps, WSSfrontend } from '../../src/services/wss/WSS.browser'; +import {Graph, htmlloader} from '../../build/main/index' const router = new Router({ order:['webrtc','wss','sse'], @@ -99,8 +81,8 @@ const router = new Router({ (router.services.sessions as SessionsService).run('userUpdateLoop',user); - user.rooms = {} as any; - user.localrtc = {} as any; + user.rooms = {}; + user.localrtc = {}; console.log(user); @@ -136,7 +118,7 @@ const router = new Router({ }, }).then((room:WebRTCInfo) => { - user.rooms[newId].hostdescription = room.description; + user.rooms[newId].hostdescription = room.hostdescription; user.localrtc[newId] = room; (document.getElementById('myrooms') as HTMLElement).insertAdjacentHTML('beforeend',` @@ -208,21 +190,21 @@ const router = new Router({ ownerId:userId, isLive:false, hostcandidates:{}, - hostdescription:remoteroom.description, + hostdescription:remoteroom.hostdescription, peercandidates:{}, peerdescription:undefined }; (router.services.webrtc as WebRTCfrontend).openRTC({ _id:roomId, - description:remoteroom.description, + hostdescription:remoteroom.hostdescription, onicecandidate:(ev) => { if(ev.candidate) user.rooms[roomId].peercandidates[`peercandidate${Math.floor(Math.random()*1000000000000000)}`] = ev.candidate; }, }).then((localroom) => { user.localrtc[roomId] = localroom; - user.rooms[roomId].peerdescription = localroom.description; + user.rooms[roomId].peerdescription = localroom.peerdescription; (user.localrtc[roomId].rtc as RTCPeerConnection).addEventListener('datachannel',(ev) => { diff --git a/examples/advanced/webrtcrouter/index.html b/examples/webrtcrouter/index.html similarity index 100% rename from examples/advanced/webrtcrouter/index.html rename to examples/webrtcrouter/index.html diff --git a/examples/advanced/webrtcrouter/package-lock.json b/examples/webrtcrouter/package-lock.json similarity index 99% rename from examples/advanced/webrtcrouter/package-lock.json rename to examples/webrtcrouter/package-lock.json index cd093aaf..b9dee49d 100644 --- a/examples/advanced/webrtcrouter/package-lock.json +++ b/examples/webrtcrouter/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp2273", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "better-sse": "^0.7.1", "brainsatplay-math": "^0.0.22", diff --git a/examples/advanced/webrtcrouter/package.json b/examples/webrtcrouter/package.json similarity index 94% rename from examples/advanced/webrtcrouter/package.json rename to examples/webrtcrouter/package.json index 394c4a0b..bd7196c7 100644 --- a/examples/advanced/webrtcrouter/package.json +++ b/examples/webrtcrouter/package.json @@ -18,15 +18,16 @@ "keywords": [ "esbuild" ], - "dependencies":{ + "dependencies": { "better-sse": "^0.7.1", "brainsatplay-math": "^0.0.22", "bson-objectid": "^2.0.3", "gpujsutils": "^1.0.12", "web-worker": "^1.2.0", - "ws": "^8.7.0"}, + "ws": "^8.7.0" + }, "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "nodemonConfig": { "env": { "NODEMON": true diff --git a/examples/advanced/webrtcrouter/tinybuild.backend.js b/examples/webrtcrouter/tinybuild.backend.js similarity index 100% rename from examples/advanced/webrtcrouter/tinybuild.backend.js rename to examples/webrtcrouter/tinybuild.backend.js diff --git a/examples/advanced/webrtcrouter/tinybuild.config.js b/examples/webrtcrouter/tinybuild.config.js similarity index 98% rename from examples/advanced/webrtcrouter/tinybuild.config.js rename to examples/webrtcrouter/tinybuild.config.js index 792d7fa5..c639249c 100644 --- a/examples/advanced/webrtcrouter/tinybuild.config.js +++ b/examples/webrtcrouter/tinybuild.config.js @@ -33,4 +33,4 @@ const config = { // keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions // } } -module.exports = config; //es5 \ No newline at end of file +module.exports = config; //es5 //export default config; // \ No newline at end of file diff --git a/examples/services/workers/workerECS/PickHelper.js b/examples/workerECS/PickHelper.js similarity index 100% rename from examples/services/workers/workerECS/PickHelper.js rename to examples/workerECS/PickHelper.js diff --git a/examples/services/workers/workerECS/ecs_test.ts b/examples/workerECS/ecs_test.ts similarity index 98% rename from examples/services/workers/workerECS/ecs_test.ts rename to examples/workerECS/ecs_test.ts index 5d4c049e..c20def02 100644 --- a/examples/services/workers/workerECS/ecs_test.ts +++ b/examples/workerECS/ecs_test.ts @@ -9,15 +9,14 @@ import { WorkerCanvasControls, WorkerInfo, htmlloader, - HTMLNodeProperties, - remoteGraphRoutes -} from '../../../../index'//'graphscript' + HTMLNodeProperties +} from '../../build/main/index'//'graphscript' import gsworker from './worker' const workers = new WorkerService(); -const router = new Router({ services:{ workers, workerCanvasRoutes, remoteGraphRoutes }, loaders:{htmlloader} }); +const router = new Router({ services:{ workers, workerCanvasRoutes }, loaders:{htmlloader} }); console.log(router); @@ -247,6 +246,7 @@ let ret = router.load({ const scene = new THREE.Scene(); + canvas.addEventListener('resize', (ev) => { //console.log('resizing', canvas.clientWidth, canvas.clientHeight) renderer.setSize(canvas.clientWidth, canvas.clientHeight, false); @@ -393,24 +393,25 @@ let ret = router.load({ ['x','y','z'] //or for arrays could be the array values ); + return { entityId:this.__node.graph.entityId, positions:positionBuffer }; //typedarrays are automatically transferred }; - workers.run('transferFunction', - bufferPositions, + workers.transferFunction( entities, + bufferPositions, 'bufferPositions' ); - workers.run('transferFunction', - bufferPositions, + workers.transferFunction( entities2, + bufferPositions, 'bufferPositions' ); - + entities.post('ECSService.subscribe',[ 'movement', 'bufferPositions' diff --git a/examples/basics/proxy/index.html b/examples/workerECS/index.html similarity index 100% rename from examples/basics/proxy/index.html rename to examples/workerECS/index.html diff --git a/examples/services/workers/workerECS/package-lock.json b/examples/workerECS/package-lock.json similarity index 98% rename from examples/services/workers/workerECS/package-lock.json rename to examples/workerECS/package-lock.json index a4479335..f7d0175b 100644 --- a/examples/services/workers/workerECS/package-lock.json +++ b/examples/workerECS/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp261", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "~0.1.47", "three": "^0.143.0", @@ -39,7 +39,7 @@ "integrity": "sha512-X9l63+mitFW0pxLF43jDZjxxkwE6a1SUGZJRGE4nmGoU9r599ilfQmXluBPPKuoK1B+ODcUrGi6eleAbA7C9Ow==", "dependencies": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.9.0" @@ -111,7 +111,7 @@ "integrity": "sha512-X9l63+mitFW0pxLF43jDZjxxkwE6a1SUGZJRGE4nmGoU9r599ilfQmXluBPPKuoK1B+ODcUrGi6eleAbA7C9Ow==", "requires": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.9.0" diff --git a/examples/services/workers/workerECS/package.json b/examples/workerECS/package.json similarity index 94% rename from examples/services/workers/workerECS/package.json rename to examples/workerECS/package.json index 2de0265a..05128808 100644 --- a/examples/services/workers/workerECS/package.json +++ b/examples/workerECS/package.json @@ -20,10 +20,11 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "~0.1.47", "three": "^0.143.0", + "web-worker": "^1.2.0", "webgl-plot-utils": "^0.3.13" }, "nodemonConfig": { diff --git a/examples/services/workers/workerECS/tinybuild.config.js b/examples/workerECS/tinybuild.config.js similarity index 100% rename from examples/services/workers/workerECS/tinybuild.config.js rename to examples/workerECS/tinybuild.config.js diff --git a/examples/services/workers/workerECS/worker.ts b/examples/workerECS/worker.ts similarity index 86% rename from examples/services/workers/workerECS/worker.ts rename to examples/workerECS/worker.ts index d60fb2f5..b0419f7e 100644 --- a/examples/services/workers/workerECS/worker.ts +++ b/examples/workerECS/worker.ts @@ -1,14 +1,14 @@ import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, ECSService, //GPUService -} from '../../../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' +} from '../../build/main/index'/////"../../GraphServiceRouter/index";//from 'graphscript' -import {Systems} from '../../../../src/extras/index.services' +import {Systems} from '../../src/extras/build/services/index.services' -import { CanvasProps } from '../../../../src/services/worker/WorkerCanvas'; +import { CanvasProps } from '../../src/services/worker/WorkerCanvas'; import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' @@ -25,11 +25,10 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope services:{ //GPUService, ECSService, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading }, roots:{ ...workerCanvasRoutes, - ...remoteGraphRoutes, receiveThreeCanvas:function(options:CanvasProps){ //modified canvas receiver that installs desired threejs modules const ThreeProps = { //e.g. install these systems to 'self', which is the worker canvas THREE, diff --git a/examples/basics/sync_async/index.html b/examples/workercanvas/index.html similarity index 100% rename from examples/basics/sync_async/index.html rename to examples/workercanvas/index.html diff --git a/examples/services/workers/workercanvas/index.ts b/examples/workercanvas/index.ts similarity index 98% rename from examples/services/workers/workercanvas/index.ts rename to examples/workercanvas/index.ts index e8efc071..faa7c1c3 100644 --- a/examples/services/workers/workercanvas/index.ts +++ b/examples/workercanvas/index.ts @@ -6,7 +6,7 @@ import { WorkerCanvas, WorkerCanvasControls, HTMLNodeProperties -} from '../../../../index'//'graphscript' +} from '../../build/main/index'//'graphscript' import gsworker from './worker' diff --git a/examples/services/workers/workercanvas/package-lock.json b/examples/workercanvas/package-lock.json similarity index 99% rename from examples/services/workers/workercanvas/package-lock.json rename to examples/workercanvas/package-lock.json index ffdfcf4c..8df9d552 100644 --- a/examples/services/workers/workercanvas/package-lock.json +++ b/examples/workercanvas/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp261", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "^0.0.157" } diff --git a/examples/services/workers/workercanvas/package.json b/examples/workercanvas/package.json similarity index 92% rename from examples/services/workers/workercanvas/package.json rename to examples/workercanvas/package.json index 2a8ad300..164b029f 100644 --- a/examples/services/workers/workercanvas/package.json +++ b/examples/workercanvas/package.json @@ -20,9 +20,10 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "graphscript": "~0.1.47" + "graphscript": "~0.1.47", + "web-worker": "^1.2.0" }, "nodemonConfig": { "env": { diff --git a/examples/services/workers/workercanvas/tinybuild.config.js b/examples/workercanvas/tinybuild.config.js similarity index 100% rename from examples/services/workers/workercanvas/tinybuild.config.js rename to examples/workercanvas/tinybuild.config.js diff --git a/examples/services/workers/workercanvas/worker.ts b/examples/workercanvas/worker.ts similarity index 73% rename from examples/services/workers/workercanvas/worker.ts rename to examples/workercanvas/worker.ts index 6743b34a..e334bef8 100644 --- a/examples/services/workers/workercanvas/worker.ts +++ b/examples/workercanvas/worker.ts @@ -1,10 +1,10 @@ import { Math2 } from 'brainsatplay-math'; import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, //GPUService -} from '../../../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' +} from '../../build/main/index'/////"../../GraphServiceRouter/index";//from 'graphscript' declare var WorkerGlobalScope; @@ -14,7 +14,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope services:{ //GPUService as any, workerCanvasRoutes, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading Math, Math2 } diff --git a/examples/services/workers/workerthreejs/PickHelper.js b/examples/workerthreejs/PickHelper.js similarity index 100% rename from examples/services/workers/workerthreejs/PickHelper.js rename to examples/workerthreejs/PickHelper.js diff --git a/examples/loaders/3dmodel/index.html b/examples/workerthreejs/index.html similarity index 100% rename from examples/loaders/3dmodel/index.html rename to examples/workerthreejs/index.html diff --git a/examples/services/workers/workerthreejs/index.ts b/examples/workerthreejs/index.ts similarity index 99% rename from examples/services/workers/workerthreejs/index.ts rename to examples/workerthreejs/index.ts index 078e8f24..06f21851 100644 --- a/examples/services/workers/workerthreejs/index.ts +++ b/examples/workerthreejs/index.ts @@ -6,7 +6,7 @@ import { WorkerCanvasControls, htmlloader, HTMLNodeProperties -} from '../../../../index'//'graphscript' +} from '../../build/main/index'//'graphscript' import gsworker from './worker' diff --git a/examples/services/workers/workerthreejs/package-lock.json b/examples/workerthreejs/package-lock.json similarity index 99% rename from examples/services/workers/workerthreejs/package-lock.json rename to examples/workerthreejs/package-lock.json index 30c2e101..b7fc03ea 100644 --- a/examples/services/workers/workerthreejs/package-lock.json +++ b/examples/workerthreejs/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp261", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "^0.0.157", "three": "^0.143.0" diff --git a/examples/services/workers/workerthreejs/package.json b/examples/workerthreejs/package.json similarity index 92% rename from examples/services/workers/workerthreejs/package.json rename to examples/workerthreejs/package.json index a456f1fd..21019627 100644 --- a/examples/services/workers/workerthreejs/package.json +++ b/examples/workerthreejs/package.json @@ -20,10 +20,11 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "~0.1.47", - "three": "^0.143.0" + "three": "^0.143.0", + "web-worker": "^1.2.0" }, "nodemonConfig": { "env": { diff --git a/examples/services/workers/workerthreejs/tinybuild.config.js b/examples/workerthreejs/tinybuild.config.js similarity index 100% rename from examples/services/workers/workerthreejs/tinybuild.config.js rename to examples/workerthreejs/tinybuild.config.js diff --git a/examples/services/workers/workerthreejs/worker.ts b/examples/workerthreejs/worker.ts similarity index 87% rename from examples/services/workers/workerthreejs/worker.ts rename to examples/workerthreejs/worker.ts index 6ddbd4ba..9ce85556 100644 --- a/examples/services/workers/workerthreejs/worker.ts +++ b/examples/workerthreejs/worker.ts @@ -1,14 +1,14 @@ import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, ECSService //GPUService -} from '../../../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' +} from '../../build/main/index'/////"../../GraphServiceRouter/index";//from 'graphscript' -import {Systems} from '../../../../src/extras/index.services' +import {Systems} from '../../src/extras/build/services/index.services' -import { CanvasProps } from '../../../../src/services/worker/WorkerCanvas'; +import { CanvasProps } from '../../src/services/worker/WorkerCanvas'; import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' @@ -25,7 +25,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope services:{ //GPUService, ECSService, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading }, roots:{ ...workerCanvasRoutes, diff --git a/index.core.ts b/index.core.ts deleted file mode 100644 index e94571ea..00000000 --- a/index.core.ts +++ /dev/null @@ -1,5 +0,0 @@ - -export * from './src/core/Graph' -export * from './src/core/EventHandler' - -export * from './src/loaders' \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 00000000..d5809f34 --- /dev/null +++ b/index.html @@ -0,0 +1,12 @@ + + + + + + + GraphScript + + + + + \ No newline at end of file diff --git a/index.node.ts b/index.node.ts deleted file mode 100644 index 6ae17440..00000000 --- a/index.node.ts +++ /dev/null @@ -1,38 +0,0 @@ -//frontend (browser-compatible) exports - -export * from './src/core/Graph' -export * from './src/core/EventHandler' -export * from './src/loaders' - -export { methodstrings } from './src/loaders/methodstrings' - -export * from './src/services/Service' -export * from './src/services/remote/remote.routes' - -export * from './src/services/ecs/ECS.service' - -// export * from './services/dom/DOM.service' -// export * from './services/dom/components/index' - -export * from './src/services/e2ee/E2EE.service' - -//export * from './services/gpu/GPU.service' - -export * from './src/services/http/HTTP.node' - -export * from './src/services/sse/SSE.node' - -export * from './src/services/wss/WSS.node' - -export * from './src/services/cmd/CMD.node' - -//export * from './src/services/struct/Struct.frontend' - -// export * from './src/services/webrtc/WebRTC.browser' - -//export * from './src/services/worker/Worker.service' //this needs a polyfill to work in nodejs -//export * from './src/services/worker/Subprocess' - -export * from './src/services/sessions/sessions.service' - -export * from './src/services/router/Router' \ No newline at end of file diff --git a/index.ts b/index.ts deleted file mode 100644 index cebf97cd..00000000 --- a/index.ts +++ /dev/null @@ -1,43 +0,0 @@ -//frontend (browser-compatible) exports - - -export * from './src/core/Graph' -export * from './src/core/EventHandler' -export * from './src/loaders' -export * from './src/services/utils' - -export { methodstrings } from './src/loaders/methodstrings' - -export * from './src/services/Service' -export * from './src/services/remote/remote.routes' - -export * from './src/services/ecs/ECS.service' - -export {html, xml} from './src/loaders/html/html' -export * from './src/loaders/html/html.loader' - -export { DOMElement, addCustomElement } from './src/loaders/html/DOMElement' -export * from './src/loaders/html/wc.loader' //includes the web component spec, html loader is a little leaner otherwise - -export * from './src/services/e2ee/E2EE.service' - -//export * from './services/gpu/GPU.service' - -export * from './src/services/http/HTTP.browser' - -export * from './src/services/sse/SSE.browser' - -export * from './src/services/wss/WSS.browser' - -//export * from './services/struct/Struct.frontend' - -export * from './src/services/webrtc/WebRTC.browser' - -export * from './src/services/worker/Worker.service' -export * from './src/services/worker/ProxyListener' -export * from './src/services/worker/WorkerCanvas' -//export * from './src/services/worker/Subprocess' - -export * from './src/services/sessions/sessions.service' - -export * from './src/services/router/Router' \ No newline at end of file diff --git a/jest.config.ts b/jest.config.ts new file mode 100644 index 00000000..68b65b46 --- /dev/null +++ b/jest.config.ts @@ -0,0 +1,32 @@ +import type {Config} from 'jest'; + +const config: Config = { + coverageProvider: 'v8', + preset: 'ts-jest/presets/default-esm', // or other ESM presets + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, + transform: { + // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest` + // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest` + '^.+\\.tsx?$': [ + 'ts-jest', + { + useESM: true, + }, + ], + }, + + testEnvironment: 'node', + testMatch: ['**/*.test.*'], + testPathIgnorePatterns: ['/node_modules/'], + coverageDirectory: './coverage', + coveragePathIgnorePatterns: ['node_modules'], + reporters: ['default'], + extensionsToTreatAsEsm: ['.ts'], + + verbose: true, + silent: false +}; + +export default config \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 5e09c1ee..b8405836 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,85 +1,158 @@ { - "name": "graphscript", - "version": "0.3.1", + "name": "graphscript-monorepo", + "version": "0.2.28", "lockfileVersion": 2, "requires": true, "packages": { "": { + "name": "graphscript-monorepo", + "version": "0.2.28", + "license": "AGPL-3.0-or-later", + "workspaces": [ + "**" + ], + "devDependencies": { + "@jest/globals": "^29.3.1", + "@types/jest": "^29.2.4", + "@types/node": "~18.7.15", + "@types/ws": "~8.5.3", + "jest": "^29.3.1", + "ts-jest": "^29.0.3", + "ts-node": "^10.9.1", + "typescript": "^4.9.4" + } + }, + "benchmarks": { + "name": "graphscript-benchmark" + }, + "build/core": { + "name": "graphscript-core", + "version": "0.2.27", + "license": "AGPL-3.0-or-later" + }, + "build/main": { "name": "graphscript", - "version": "0.3.1", - "license": "LGPL-3.0-or-later", + "version": "0.2.28", + "license": "AGPL-3.0-or-later", + "dependencies": { + "web-worker": "^1.2.0" + } + }, + "build/node": { + "name": "graphscript-node", + "version": "0.2.27", + "license": "AGPL-3.0-or-later", "dependencies": { - "better-sse": "~0.11.0", - "brainsatplay-math": "~0.1.0", - "web-worker": "~1.3.0", - "ws": "~8.16.0" + "better-sse": "^0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "sjcl": "^1.0.8", + "web-worker": "~1.2.0", + "ws": "~8.11.0" }, "devDependencies": { - "@types/node": "~18.7.15", - "@types/ws": "~8.5.3" + "@types/node": "~18.7.15" } }, - "../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.127", - "extraneous": true, - "license": "LGPL-3.0-or-later", + "examples/3dmodel": { + "name": "tinybuildapp5631", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.14.41", - "esbuild-plugin-d.ts": "^1.1.0", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.6.4" + "babylonjs": "^5.39.0", + "web-worker": "^1.2.0" } }, - "node_modules/@types/node": { - "version": "18.7.19", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.19.tgz", - "integrity": "sha512-Sq1itGUKUX1ap7GgZlrzdBydjbsJL/NSQt/4wkAxUJ7/OS5c2WkoN6WSpWc2Yc5wtKMZOUA0VCs/j2XJadN3HA==", - "dev": true + "examples/audiofeedback": { + "name": "tinybuildapp7099", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@capacitor-community/bluetooth-le": "^2.0.1", + "browserfs": "^1.4.3", + "device-decoder": "~0.3.4", + "graphscript": "^0.2.28", + "graphscript-services": "~0.2.26", + "howler": "~2.2.3", + "web-worker": "^1.2.0" + } }, - "node_modules/@types/ws": { - "version": "8.5.4", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", - "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", - "dev": true, + "examples/audiofeedback/node_modules/graphscript-services": { + "version": "0.2.27", + "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.27.tgz", + "integrity": "sha512-9KDKkbswyFKV+HN+oyGGMuaqZhOLrXQiLKSpAhD4k973/KiXY2BPLZpZ5pMT2+FJA/WDWXq3RBhHRli4RPJEAw==", + "license": "AGPL-3.0-or-later", "dependencies": { - "@types/node": "*" + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "web-worker": "^1.2.0", + "webgl-plot-utils": "~0.3.15" } }, - "node_modules/better-sse": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.11.0.tgz", - "integrity": "sha512-xY5Nmn9XyO5PiMw4//C+mNCUknaueugBqXMoMdEp2s9oNDVI4Vu6nhjduxA6yOxJVm/O6u3YC3FbLMHEvTzk3Q==", - "engines": { - "node": ">=12", - "pnpm": ">=6" + "examples/eegnfb": { + "name": "tinybuildapp6104", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@capacitor-community/bluetooth-le": "^2.0.1", + "browserfs": "^1.4.3", + "device-decoder": "~0.3.4", + "device-decoder.third-party": "~0.1.24", + "graphscript": "^0.2.28", + "howler": "~2.2.3", + "web-worker": "^1.2.0", + "webgl-plot-utils": "^0.3.15" } }, - "node_modules/brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" + "examples/graph": { + "name": "tinybuildapp1331", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "devDependencies": {} }, - "node_modules/web-worker": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.3.0.tgz", - "integrity": "sha512-BSR9wyRsy/KOValMgd5kMyr3JzpdeoR9KVId8u5GVlTTAtNChlsE4yTxeY7zMdNSyOmoKBv8NH2qeRY9Tg+IaA==" + "examples/html": { + "name": "tinybuildapp8682", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "web-worker": "^1.2.0" + } }, - "node_modules/ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", + "examples/httpserver": { + "name": "tinybuildapp9941", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "^0.8.0", + "graphscript-node": "~0.1.41" + } + }, + "examples/httpserver/node_modules/graphscript-node": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript-node/-/graphscript-node-0.1.52.tgz", + "integrity": "sha512-kOcEm6qgdY8sZihkiPXesVky4lUgQ5ajPyUGx2ZmEfgXaxeu35eclwmph66EtWHjLjxxtcSsdchXbAhojQb+8w==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.9.0" + } + }, + "examples/httpserver/node_modules/ws": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.9.0.tgz", + "integrity": "sha512-Ja7nszREasGaYUYCI2k4lCKIRTt+y7XuqVoHR44YpI49TtryyqbqvDMn5eqfW7e6HzTukDRIsXqzVHScqRcafg==", + "license": "MIT", "engines": { "node": ">=10.0.0" }, "peerDependencies": { "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" + "utf-8-validate": "^5.0.2" }, "peerDependenciesMeta": { "bufferutil": { @@ -89,44 +162,7603 @@ "optional": true } } - } - }, - "dependencies": { - "@types/node": { - "version": "18.7.19", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.19.tgz", - "integrity": "sha512-Sq1itGUKUX1ap7GgZlrzdBydjbsJL/NSQt/4wkAxUJ7/OS5c2WkoN6WSpWc2Yc5wtKMZOUA0VCs/j2XJadN3HA==", - "dev": true }, - "@types/ws": { - "version": "8.5.4", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", - "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", + "examples/webrtcrouter": { + "name": "tinybuildapp2273", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "^0.7.1", + "brainsatplay-math": "^0.0.22", + "bson-objectid": "^2.0.3", + "gpujsutils": "^1.0.12", + "web-worker": "^1.2.0", + "ws": "^8.7.0" + } + }, + "examples/webrtcrouter/node_modules/better-sse": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.7.1.tgz", + "integrity": "sha512-2t7XGg6hQFNwtmFXKi6/jyY5K0/4fa5UoOqVSYG2W/AFbVCt8gPnFw2LHM9ude91a8KhoXtRt9zOwpVZ5f5K5g==", + "license": "MIT", + "engines": { + "node": ">=12", + "pnpm": ">=6" + } + }, + "examples/webrtcrouter/node_modules/brainsatplay-math": { + "version": "0.0.22", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.22.tgz", + "integrity": "sha512-er+7fobi+bgtuiaN5Pcg0cpOfl/d5hrM8W8sF5lnX9VWhcs2TvyG3J0UV+pozGYSBvtqij7Evs4HhhFIh3cfbQ==", + "license": "AGPL-3.0-or-later" + }, + "examples/workercanvas": { + "name": "graphscript-workercanvas-example", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "graphscript": "~0.1.47", + "web-worker": "^1.2.0" + } + }, + "examples/workercanvas/node_modules/graphscript": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + } + }, + "examples/workerECS": { + "name": "graphscript-workerecs-example", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "graphscript": "~0.1.47", + "three": "^0.143.0", + "web-worker": "^1.2.0", + "webgl-plot-utils": "^0.3.13" + } + }, + "examples/workerECS/node_modules/graphscript": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + } + }, + "examples/workerthreejs": { + "name": "graphscript-workerthreejs-example", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "graphscript": "~0.1.47", + "three": "^0.143.0", + "web-worker": "^1.2.0" + } + }, + "examples/workerthreejs/node_modules/graphscript": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", + "integrity": "sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w==", "dev": true, - "requires": { - "@types/node": "*" + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" } }, - "better-sse": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.11.0.tgz", - "integrity": "sha512-xY5Nmn9XyO5PiMw4//C+mNCUknaueugBqXMoMdEp2s9oNDVI4Vu6nhjduxA6yOxJVm/O6u3YC3FbLMHEvTzk3Q==" + "node_modules/@ampproject/remapping/node_modules/@jridgewell/gen-mapping": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz", + "integrity": "sha512-sQXCasFk+U8lWYEe66WxRDOE9PjVz4vSM51fTu3Hw+ClTpUSQb718772vH3pyS5pShp6lvQM7SxgIDXXXmOX7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.0.0", + "@jridgewell/sourcemap-codec": "^1.4.10" + }, + "engines": { + "node": ">=6.0.0" + } }, - "brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" + "node_modules/@babel/code-frame": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } }, - "web-worker": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.3.0.tgz", - "integrity": "sha512-BSR9wyRsy/KOValMgd5kMyr3JzpdeoR9KVId8u5GVlTTAtNChlsE4yTxeY7zMdNSyOmoKBv8NH2qeRY9Tg+IaA==" + "node_modules/@babel/compat-data": { + "version": "7.20.10", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.20.10.tgz", + "integrity": "sha512-sEnuDPpOJR/fcafHMjpcpGN5M2jbUGUHwmuWKM/YdPzeEDJg8bgmbcWQFUfE32MQjti1koACvoPVsDe8Uq+idg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } }, - "ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", - "requires": {} + "node_modules/@babel/core": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.20.7.tgz", + "integrity": "sha512-t1ZjCluspe5DW24bn2Rr1CDb2v9rn/hROtg9a2tmd0+QYf4bsloYfLQzjG4qHPNMhWtKdGC33R5AxGR2Af2cBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.20.7", + "@babel/helper-compilation-targets": "^7.20.7", + "@babel/helper-module-transforms": "^7.20.7", + "@babel/helpers": "^7.20.7", + "@babel/parser": "^7.20.7", + "@babel/template": "^7.20.7", + "@babel/traverse": "^7.20.7", + "@babel/types": "^7.20.7", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.20.7.tgz", + "integrity": "sha512-7wqMOJq8doJMZmP4ApXTzLxSr7+oO2jroJURrVEp6XShrQUObV8Tq/D0NCcoYg2uHqUrjzO0zwBjoYzelxK+sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.20.7", + "@jridgewell/gen-mapping": "^0.3.2", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.20.7.tgz", + "integrity": "sha512-4tGORmfQcrc+bvrjb5y3dG9Mx1IOZjsHqQVUz7XCNHO+iTmqxWnVg3KRygjGmpRLJGdQSKuvFinbIb0CnZwHAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.20.5", + "@babel/helper-validator-option": "^7.18.6", + "browserslist": "^4.21.3", + "lru-cache": "^5.1.1", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.18.9", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", + "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.19.0.tgz", + "integrity": "sha512-WAwHBINyrpqywkUH0nTnNgI5ina5TFn85HKS0pbPDfxFfhyR/aNQEn4hGi1P1JyT//I0t4OgXUlofzWILRvS5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.18.10", + "@babel/types": "^7.19.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-hoist-variables": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", + "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", + "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.20.11", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.20.11.tgz", + "integrity": "sha512-uRy78kN4psmji1s2QtbtcCSaj/LILFDp0f/ymhpQH5QY3nljUZCaNWz9X1dEj/8MBdBEFECs7yRhKn8i7NjZgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-module-imports": "^7.18.6", + "@babel/helper-simple-access": "^7.20.2", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/helper-validator-identifier": "^7.19.1", + "@babel/template": "^7.20.7", + "@babel/traverse": "^7.20.10", + "@babel/types": "^7.20.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.20.2", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.20.2.tgz", + "integrity": "sha512-8RvlJG2mj4huQ4pZ+rU9lqKi9ZKiRmuvGuM2HlWmkmgOhbs6zEAw6IEiJ5cQqGbDzGZOhwuOQNtZMi/ENLjZoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.20.2", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.20.2.tgz", + "integrity": "sha512-+0woI/WPq59IrqDYbVGfshjT5Dmk/nnbdpcF8SnMhhXObpTq2KNBdLFRFrkVdbDOyUmHBCxzm5FHV1rACIkIbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.20.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-split-export-declaration": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", + "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.19.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", + "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.19.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", + "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz", + "integrity": "sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.20.7.tgz", + "integrity": "sha512-PBPjs5BppzsGaxHQCDKnZ6Gd9s6xl8bBCluz3vEInLGRJmnZan4F6BYCeqtyXqkk4W5IlPmjK4JlOuZkpJ3xZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.20.7", + "@babel/traverse": "^7.20.7", + "@babel/types": "^7.20.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", + "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/highlight/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/parser": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.20.7.tgz", + "integrity": "sha512-T3Z9oHybU+0vZlY9CiDSJQTD5ZapcW18ZctFMi0MOAl/4BjFF4ul7NVSARLdbGO5vDqy9eQiGTV0LtKfvCYvcg==", + "dev": true, + "license": "MIT", + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz", + "integrity": "sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.20.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.20.0.tgz", + "integrity": "sha512-rd9TkG+u1CExzS4SM1BlMEhMXwFLKVjOAFFCDx9PbX5ycJWDoWMcwdJH9RhkPu1dOgn5TrxLot/Gx6lWFuAUNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.19.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz", + "integrity": "sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.18.6", + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.20.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.20.10.tgz", + "integrity": "sha512-oSf1juCgymrSez8NI4A2sr4+uB/mFd9MXplYGPEBnfAuWmmyeVcHa6xLPiaRBcXkcb/28bgxmQLTVwFKE1yfsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.20.7", + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-function-name": "^7.19.0", + "@babel/helper-hoist-variables": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "debug": "^4.1.0", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.20.7.tgz", + "integrity": "sha512-69OnhBxSSgK0OzTJai4kyPDiKTIe3j+ctaHdIGVbRahTLAT7L3R9oeXHC2aVSuGYt3cVnoAMDmOCgJ2yaiLMvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.19.4", + "@babel/helper-validator-identifier": "^7.19.1", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@capacitor-community/bluetooth-le": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@capacitor-community/bluetooth-le/-/bluetooth-le-2.0.1.tgz", + "integrity": "sha512-K8NOAvzHKdwy+Ql9Y8hvtZh5gj5pnleAD8Q89HM9FDMbTsZmyBID0FcPGJxAZVRAb9VuaID3YykluRM7Up27ew==", + "dependencies": { + "@types/web-bluetooth": "^0.0.15", + "throat": "^6.0.1" + }, + "peerDependencies": { + "@capacitor/core": "^4.0.0" + } + }, + "node_modules/@capacitor/core": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@capacitor/core/-/core-4.6.1.tgz", + "integrity": "sha512-7A2IV9E8umgu9u0fChUTjQJq+Jp25GJZMmWxoQN/nVx/1rcpFJ4m1xo3NPBoIRs+aV7FR+BM17mPrnkKlA8N2g==", + "peer": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.3.1.tgz", + "integrity": "sha512-IRE6GD47KwcqA09RIWrabKdHPiKDGgtAL31xDxbi/RjQMsr+lY+ppxmHwY0dUEV3qvvxZzoe5Hl0RXZJOjQNUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/core": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.3.1.tgz", + "integrity": "sha512-0ohVjjRex985w5MmO5L3u5GR1O30DexhBSpuwx2P+9ftyqHdJXnk7IUWiP80oHMvt7ubHCJHxV0a0vlKVuZirw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.3.1", + "@jest/reporters": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.2.0", + "jest-config": "^29.3.1", + "jest-haste-map": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.3.1", + "jest-resolve-dependencies": "^29.3.1", + "jest-runner": "^29.3.1", + "jest-runtime": "^29.3.1", + "jest-snapshot": "^29.3.1", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "jest-watcher": "^29.3.1", + "micromatch": "^4.0.4", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/environment": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.3.1.tgz", + "integrity": "sha512-pMmvfOPmoa1c1QpfFW0nXYtNLpofqo4BrCIk6f2kW4JFeNlHV2t3vd+3iDLf31e2ot2Mec0uqZfmI+U0K2CFag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/fake-timers": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "jest-mock": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.3.1.tgz", + "integrity": "sha512-QivM7GlSHSsIAWzgfyP8dgeExPRZ9BIe2LsdPyEhCGkZkoyA+kGsoIzbKAfZCvvRzfZioKwPtCZIt5SaoxYCvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.3.1", + "jest-snapshot": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.3.1.tgz", + "integrity": "sha512-wlrznINZI5sMjwvUoLVk617ll/UYfGIZNxmbU+Pa7wmkL4vYzhV9R2pwVqUh4NWWuLQWkI8+8mOkxs//prKQ3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.2.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/fake-timers": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.3.1.tgz", + "integrity": "sha512-iHTL/XpnDlFki9Tq0Q1GGuVeQ8BHZGIYsvCO5eN/O/oJaRzofG9Xndd9HuSDBI/0ZS79pg0iwn07OMTQ7ngF2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.3.1", + "@sinonjs/fake-timers": "^9.1.2", + "@types/node": "*", + "jest-message-util": "^29.3.1", + "jest-mock": "^29.3.1", + "jest-util": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/globals": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.3.1.tgz", + "integrity": "sha512-cTicd134vOcwO59OPaB6AmdHQMCtWOe+/DitpTZVxWgMJ+YvXL1HNAmPyiGbSHmF/mXVBkvlm8YYtQhyHPnV6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.3.1", + "@jest/expect": "^29.3.1", + "@jest/types": "^29.3.1", + "jest-mock": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/reporters": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.3.1.tgz", + "integrity": "sha512-GhBu3YFuDrcAYW/UESz1JphEAbvUjaY2vShRZRoRY1mxpCMB3yGSJ4j9n0GxVlEOdCf7qjvUfBCrTUUqhVfbRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@jridgewell/trace-mapping": "^0.3.15", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1", + "jest-worker": "^29.3.1", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/schemas": { + "version": "29.0.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.0.0.tgz", + "integrity": "sha512-3Ab5HgYIIAnS0HjqJHQYZS+zXc4tUmTmBH3z83ajI6afXp8X3ZtdLX+nXx+I7LNkJD7uN9LAVhgnjDgZa2z0kA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.24.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.2.0.tgz", + "integrity": "sha512-1NX9/7zzI0nqa6+kgpSdKPK+WU1p+SJk3TloWZf5MzPbxri9UEeXX5bWZAPCzbQcyuAzubcdUHA7hcNznmRqWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.15", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-result": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.3.1.tgz", + "integrity": "sha512-qeLa6qc0ddB0kuOZyZIhfN5q0e2htngokyTWsGriedsDhItisW7SDYZ7ceOe57Ii03sL988/03wAcBh3TChMGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.3.1.tgz", + "integrity": "sha512-IqYvLbieTv20ArgKoAMyhLHNrVHJfzO6ARZAbQRlY4UGWfdDnLlZEF0BvKOMd77uIiIjSZRwq3Jb3Fa3I8+2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.3.1", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.3.1.tgz", + "integrity": "sha512-8wmCFBTVGYqFNLWfcOWoVuMuKYPUBTnTMDkdvFtAYELwDOl9RGwOsvQWGPFxDJ8AWY9xM/8xCXdqmPK3+Q5Lug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.3.1", + "@jridgewell/trace-mapping": "^0.3.15", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.3.1", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jest/types": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.3.1.tgz", + "integrity": "sha512-d0S0jmmTpjnhCmNpApgX3jrUZgZ22ivKJRvL2lli5hpCRoNnp1f85r2/wpKfXuYu8E7Jjh1hGfhPyup1NM5AmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.0.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", + "integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", + "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.14", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", + "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.17", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.17.tgz", + "integrity": "sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.24.51", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.24.51.tgz", + "integrity": "sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sinonjs/commons": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.6.tgz", + "integrity": "sha512-Ky+XkAkqPZSm3NLBeUng77EBQl3cmeJhITaGHdYH8kjVB+aun3S4XBRti2zt17mtt0mIUDiNxYeoJm6drVvBJQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-9.1.2.tgz", + "integrity": "sha512-BPS4ynJW/o92PUR4wgriz2Ud5gpST5vz6GQfMixEDK0Z8ZCUv2M7SkBLykH56T++Xs+8ln9zTGbOvNGIe02/jw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^1.7.0" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", + "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.3.tgz", + "integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/babel__core": { + "version": "7.1.20", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.20.tgz", + "integrity": "sha512-PVb6Bg2QuscZ30FvOU7z4guG6c926D9YRvOxEaelzndpMsvP+YM74Q/dAFASpg2l6+XLalxSGxcq/lrgYWZtyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.6.4", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", + "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", + "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.18.3.tgz", + "integrity": "sha512-1kbcJ40lLB7MHsj39U4Sh1uTd2E7rLEa79kmDpI6cy+XiXsteB3POdQomoq4FxszMrO3ZYchkhYJw7A2862b3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.3.0" + } + }, + "node_modules/@types/graceful-fs": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.5.tgz", + "integrity": "sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", + "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/jest": { + "version": "29.2.4", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.2.4.tgz", + "integrity": "sha512-PipFB04k2qTRPePduVLTRiPzQfvMeLwUN3Z21hsAKaB/W9IIzgB2pizCL466ftJlcyZqnHoC9ZHpxLGl3fS86A==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "node_modules/@types/node": { + "version": "18.7.19", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.19.tgz", + "integrity": "sha512-Sq1itGUKUX1ap7GgZlrzdBydjbsJL/NSQt/4wkAxUJ7/OS5c2WkoN6WSpWc2Yc5wtKMZOUA0VCs/j2XJadN3HA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/prettier": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", + "integrity": "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.15", + "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.15.tgz", + "integrity": "sha512-w7hEHXnPMEZ+4nGKl/KDRVpxkwYxYExuHOYXyzIzCDzEZ9ZCGMAewulr9IqJu2LR4N37fcnb1XVeuZ09qgOxhA==", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz", + "integrity": "sha512-6YOoWjruKj1uLf3INHH7D3qTXwFfEsg1kf3c0uDdSBJwfa/llkwIjrAGV7j7mVgGNbzTQ3HiHKKDXl6bJPD97w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.17", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.17.tgz", + "integrity": "sha512-72bWxFKTK6uwWJAVT+3rF6Jo6RTojiJ27FQo8Rf60AL+VZbzoVPnMFhKsUnbjR8A3BTCYQ7Mv3hnl8T0A+CX9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", + "dev": true, + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", + "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true, + "license": "MIT" + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/async": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", + "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/babel-jest": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.3.1.tgz", + "integrity": "sha512-aard+xnMoxgjwV70t0L6wkW/3HQQtV+O0PEimxKgzNqCJnbYmroPojdP2tqKSOAt8QAKV/uSZU8851M7B5+fcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/transform": "^29.3.1", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.2.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.8.0" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-jest-hoist": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.2.0.tgz", + "integrity": "sha512-TnspP2WNiR3GLfCsUNHqeXw0RoQ2f9U5hQ5L3XFpwuO8htQmSrhh8qsB6vi5Yi8+kuynN1yjDjQsPfkebmB6ZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/babel-preset-current-node-syntax": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", + "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-top-level-await": "^7.8.3" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/babel-preset-jest": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.2.0.tgz", + "integrity": "sha512-z9JmMJppMxNv8N7fNRHvhMg9cvIkMxQBXgFkane3yKVEvEOP+kB50lk8DFRvF9PGqbyXxlmebKWhuDORO8RgdA==", + "dev": true, + "license": "MIT", + "dependencies": { + "babel-plugin-jest-hoist": "^29.2.0", + "babel-preset-current-node-syntax": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/babylonjs": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/babylonjs/-/babylonjs-5.39.0.tgz", + "integrity": "sha512-U6nI2cGrflsL9z+SsEKzOGYGm0I6eu7d2hPO3rOxCfVFMSi9rCDI0tUPxQ7JpjQ6dkGFQafvmJnczUeFt/a16w==", + "hasInstallScript": true + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/better-sse": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz", + "integrity": "sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA==", + "engines": { + "node": ">=12", + "pnpm": ">=6" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/brainsatplay-math": { + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + }, + "node_modules/browserfs": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/browserfs/-/browserfs-1.4.3.tgz", + "integrity": "sha512-tz8HClVrzTJshcyIu8frE15cjqjcBIu15Bezxsvl/i+6f59iNCN3kznlWjz0FEb3DlnDx3gW5szxeT6D1x0s0w==", + "dependencies": { + "async": "^2.1.4", + "pako": "^1.0.4" + }, + "bin": { + "make_xhrfs_index": "dist/scripts/make_xhrfs_index.js" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/browserslist": { + "version": "4.21.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.4.tgz", + "integrity": "sha512-CBHJJdDmgjl3daYjN5Cp5kbTf1mUhZoS+beLklHIvkOWscs83YAhLlF3Wsh/lciQYAcbBJgTOD44VtG31ZM4Hw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "license": "MIT", + "dependencies": { + "caniuse-lite": "^1.0.30001400", + "electron-to-chromium": "^1.4.251", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.9" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-json-stable-stringify": "2.x" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "node-int64": "^0.4.0" + } + }, + "node_modules/bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001441", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001441.tgz", + "integrity": "sha512-OyxRR4Vof59I3yGWXws6i908EtGbMzVUi3ganaZQHmydk1iwDhRnvaPG2WaR0KcqrDFKrxVZHULT396LEPhXfg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/ci-info": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.7.0.tgz", + "integrity": "sha512-2CpRNYmImPx+RXKLq6jko/L07phmS9I02TyqkcNU20GCF/GgaWvc58hPtjxDX8lPpkdwc9sNh72V9k00S7ezog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz", + "integrity": "sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==", + "dev": true, + "license": "MIT" + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/collect-v8-coverage": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", + "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dedent": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", + "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/device-decoder": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/device-decoder/-/device-decoder-0.3.5.tgz", + "integrity": "sha512-F2D61UWMXl/MC1PMX5EIt5y4nx8vA2MHeu//uvctKzFbCXbLiS9Qv/JE3avbxgGe3Mt/mW+4nlwNlAwBdv75iQ==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@capacitor-community/bluetooth-le": "~2.0.1", + "brainsatplay-math": "~0.0.25", + "graphscript": "~0.2.27", + "graphscript-services": "~0.2.27", + "graphscript-services.gpu": "~0.2.27", + "graphscript-services.storage": "~0.2.27", + "webgl-plot-utils": "~0.3.15" + } + }, + "node_modules/device-decoder.third-party": { + "version": "0.1.25", + "resolved": "https://registry.npmjs.org/device-decoder.third-party/-/device-decoder.third-party-0.1.25.tgz", + "integrity": "sha512-/l2GS56jvrzwYpDqlvAiUDUr/ruxfKhXAgUUn72TSEKjQNhrXKi+Y6TU/+WSpF/HemiL4dZ7YxshL/iQCg9kEQ==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "webgl-plot-utils": "~0.3.15" + } + }, + "node_modules/device-decoder/node_modules/graphscript-services": { + "version": "0.2.27", + "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.27.tgz", + "integrity": "sha512-9KDKkbswyFKV+HN+oyGGMuaqZhOLrXQiLKSpAhD4k973/KiXY2BPLZpZ5pMT2+FJA/WDWXq3RBhHRli4RPJEAw==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "web-worker": "^1.2.0", + "webgl-plot-utils": "~0.3.15" + } + }, + "node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/diff-sequences": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.3.1.tgz", + "integrity": "sha512-hlM3QR272NXCi4pq+N4Kok4kOp6EsgOM3ZSpJI7Da3UAs+Ttsi8MRmB6trM/lhyzUxGfOgnpkHtgqm5Q/CTcfQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.4.284", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.284.tgz", + "integrity": "sha512-M8WEXFuKXMYMVr45fo8mq0wUrrJHheiKZf6BArTKk9ZBYCKJEOU5H8cdWgDT+qCVZf7Na4lVUaZsA+h6uA9+PA==", + "dev": true, + "license": "ISC" + }, + "node_modules/emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/emittery?sponsor=1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expect": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.3.1.tgz", + "integrity": "sha512-gGb1yTgU30Q0O/tQq+z30KBWv24ApkMgFUpvKBkyLUBL68Wv8dHdJxTBZFl/iT8K/bqDHvUYRH6IIN3rToopPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/expect-utils": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fb-watchman": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", + "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bser": "2.1.1" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/gpujsutils": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" + }, + "node_modules/graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true, + "license": "ISC" + }, + "node_modules/graphscript": { + "resolved": "build/main", + "link": true + }, + "node_modules/graphscript-benchmark": { + "resolved": "benchmarks", + "link": true + }, + "node_modules/graphscript-children-loader": { + "resolved": "src/core/loaders/graphscript-children-loader", + "link": true + }, + "node_modules/graphscript-core": { + "resolved": "build/core", + "link": true + }, + "node_modules/graphscript-default-loader": { + "resolved": "src/core/loaders/graphscript-default-loader", + "link": true + }, + "node_modules/graphscript-extras": { + "resolved": "src/extras", + "link": true + }, + "node_modules/graphscript-listeners-loader": { + "resolved": "src/core/loaders/graphscript-listeners-loader", + "link": true + }, + "node_modules/graphscript-node": { + "resolved": "build/node", + "link": true + }, + "node_modules/graphscript-operator-loader": { + "resolved": "src/core/loaders/graphscript-operator-loader", + "link": true + }, + "node_modules/graphscript-parent-loader": { + "resolved": "src/core/loaders/graphscript-parent-loader", + "link": true + }, + "node_modules/graphscript-props-loader": { + "resolved": "src/core/loaders/graphscript-props-loader", + "link": true + }, + "node_modules/graphscript-root-loader": { + "resolved": "src/core/loaders/graphscript-root-loader", + "link": true + }, + "node_modules/graphscript-services": { + "resolved": "src/extras/build/services", + "link": true + }, + "node_modules/graphscript-services.gpu": { + "resolved": "src/extras/build/gpu", + "link": true + }, + "node_modules/graphscript-services.storage": { + "resolved": "src/extras/build/storage", + "link": true + }, + "node_modules/graphscript-workercanvas-example": { + "resolved": "examples/workercanvas", + "link": true + }, + "node_modules/graphscript-workerecs-example": { + "resolved": "examples/workerECS", + "link": true + }, + "node_modules/graphscript-workerthreejs-example": { + "resolved": "examples/workerthreejs", + "link": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/howler": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/howler/-/howler-2.2.3.tgz", + "integrity": "sha512-QM0FFkw0LRX1PR8pNzJVAY25JhIWvbKMBFM4gqk+QdV+kPXOhleWGCB6AiAF/goGjIHK2e/nIElplvjQwhr0jg==" + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/import-local": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", + "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", + "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.5.tgz", + "integrity": "sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.3.1.tgz", + "integrity": "sha512-6iWfL5DTT0Np6UYs/y5Niu7WIfNv/wRTtN5RSXt2DIEft3dx3zPuw/3WJQBCJfmEzvDiEKwoqMbGD9n49+qLSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.3.1", + "@jest/types": "^29.3.1", + "import-local": "^3.0.2", + "jest-cli": "^29.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.2.0.tgz", + "integrity": "sha512-qPVmLLyBmvF5HJrY7krDisx6Voi8DmlV3GZYX0aFNbaQsZeoz1hfxcCMbqDGuQCxU1dJy9eYc2xscE8QrCCYaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "execa": "^5.0.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.3.1.tgz", + "integrity": "sha512-wpr26sEvwb3qQQbdlmei+gzp6yoSSoSL6GsLPxnuayZSMrSd5Ka7IjAvatpIernBvT2+Ic6RLTg+jSebScmasg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.3.1", + "@jest/expect": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^0.7.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.3.1", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-runtime": "^29.3.1", + "jest-snapshot": "^29.3.1", + "jest-util": "^29.3.1", + "p-limit": "^3.1.0", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-cli": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.3.1.tgz", + "integrity": "sha512-TO/ewvwyvPOiBBuWZ0gm04z3WWP8TIK8acgPzE4IxgsLKQgb377NYGrQLc3Wl/7ndWzIH2CDNNsUjGxwLL43VQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/types": "^29.3.1", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "import-local": "^3.0.2", + "jest-config": "^29.3.1", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "prompts": "^2.0.1", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.3.1.tgz", + "integrity": "sha512-y0tFHdj2WnTEhxmGUK1T7fgLen7YK4RtfvpLFBXfQkh2eMJAQq24Vx9472lvn5wg0MAO6B+iPfJfzdR9hJYalg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.3.1", + "@jest/types": "^29.3.1", + "babel-jest": "^29.3.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.3.1", + "jest-environment-node": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.3.1", + "jest-runner": "^29.3.1", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-diff": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.3.1.tgz", + "integrity": "sha512-vU8vyiO7568tmin2lA3r2DP8oRvzhvRcD4DjpXc6uGveQodyk7CKLhQlCSiwgx3g0pFaE88/KLZ0yaTWMc4Uiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-docblock": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.2.0.tgz", + "integrity": "sha512-bkxUsxTgWQGbXV5IENmfiIuqZhJcyvF7tU4zJ/7ioTutdz4ToB5Yx6JOFBpgI+TphRY4lhOyCWGNH/QFQh5T6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.3.1.tgz", + "integrity": "sha512-qrZH7PmFB9rEzCSl00BWjZYuS1BSOH8lLuC0azQE9lQrAx3PWGKHTDudQiOSwIy5dGAJh7KA0ScYlCP7JxvFYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.3.1", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "jest-util": "^29.3.1", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-environment-node": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.3.1.tgz", + "integrity": "sha512-xm2THL18Xf5sIHoU7OThBPtuH6Lerd+Y1NLYiZJlkE3hbE+7N7r8uvHIl/FkZ5ymKXJe/11SQuf3fv4v6rUMag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.3.1", + "@jest/fake-timers": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "jest-mock": "^29.3.1", + "jest-util": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.2.0.tgz", + "integrity": "sha512-uXNJlg8hKFEnDgFsrCjznB+sTxdkuqiCL6zMgA75qEbAJjJYTs9XPrvDctrEig2GDow22T/LvHgO57iJhXB/UA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.3.1.tgz", + "integrity": "sha512-/FFtvoG1xjbbPXQLFef+WSU4yrc0fc0Dds6aRPBojUid7qlPqZvxdUBA03HW0fnVHXVCnCdkuoghYItKNzc/0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.3.1", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.3.1", + "jest-worker": "^29.3.1", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/jest-leak-detector": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.3.1.tgz", + "integrity": "sha512-3DA/VVXj4zFOPagGkuqHnSQf1GZBmmlagpguxEERO6Pla2g84Q1MaVIB3YMxgUaFIaYag8ZnTyQgiZ35YEqAQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.3.1.tgz", + "integrity": "sha512-fkRMZUAScup3txIKfMe3AIZZmPEjWEdsPJFK3AIy5qRohWqQFg1qrmKfYXR9qEkNc7OdAu2N4KPHibEmy4HPeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.3.1.tgz", + "integrity": "sha512-lMJTbgNcDm5z+6KDxWtqOFWlGQxD6XaYwBqHR8kmpkP+WWWG90I35kdtQHY67Ay5CSuydkTBbJG+tH9JShFCyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.3.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-mock": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.3.1.tgz", + "integrity": "sha512-H8/qFDtDVMFvFP4X8NuOT3XRDzOUTz+FeACjufHzsOIBAxivLqkB1PoLCaJx9iPPQ8dZThHPp/G3WRWyMgA3JA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "jest-util": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, + "node_modules/jest-regex-util": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.2.0.tgz", + "integrity": "sha512-6yXn0kg2JXzH30cr2NlThF+70iuO/3irbaB4mh5WyqNIvLLP+B6sFdluO1/1RJmslyh/f9osnefECflHvTbwVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.3.1.tgz", + "integrity": "sha512-amXJgH/Ng712w3Uz5gqzFBBjxV8WFLSmNjoreBGMqxgCz5cH7swmBZzgBaCIOsvb0NbpJ0vgaSFdJqMdT+rADw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "resolve": "^1.20.0", + "resolve.exports": "^1.1.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.3.1.tgz", + "integrity": "sha512-Vk0cYq0byRw2WluNmNWGqPeRnZ3p3hHmjJMp2dyyZeYIfiBskwq4rpiuGFR6QGAdbj58WC7HN4hQHjf2mpvrLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-regex-util": "^29.2.0", + "jest-snapshot": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.3.1.tgz", + "integrity": "sha512-oFvcwRNrKMtE6u9+AQPMATxFcTySyKfLhvso7Sdk/rNpbhg4g2GAGCopiInk1OP4q6gz3n6MajW4+fnHWlU3bA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.3.1", + "@jest/environment": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.2.0", + "jest-environment-node": "^29.3.1", + "jest-haste-map": "^29.3.1", + "jest-leak-detector": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-resolve": "^29.3.1", + "jest-runtime": "^29.3.1", + "jest-util": "^29.3.1", + "jest-watcher": "^29.3.1", + "jest-worker": "^29.3.1", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.3.1.tgz", + "integrity": "sha512-jLzkIxIqXwBEOZx7wx9OO9sxoZmgT2NhmQKzHQm1xwR1kNW/dn0OjxR424VwHHf1SPN6Qwlb5pp1oGCeFTQ62A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.3.1", + "@jest/fake-timers": "^29.3.1", + "@jest/globals": "^29.3.1", + "@jest/source-map": "^29.2.0", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-mock": "^29.3.1", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.3.1", + "jest-snapshot": "^29.3.1", + "jest-util": "^29.3.1", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.3.1.tgz", + "integrity": "sha512-+3JOc+s28upYLI2OJM4PWRGK9AgpsMs/ekNryUV0yMBClT9B1DF2u2qay8YxcQd338PPYSFNb0lsar1B49sLDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/traverse": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/babel__traverse": "^7.0.6", + "@types/prettier": "^2.1.5", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.3.1", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-haste-map": "^29.3.1", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1", + "natural-compare": "^1.4.0", + "pretty-format": "^29.3.1", + "semver": "^7.3.5" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot/node_modules/semver": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.3.1.tgz", + "integrity": "sha512-7YOVZaiX7RJLv76ZfHt4nbNEzzTRiMW/IiOG7ZOKmTXmoGBxUDefgMAxQubu6WPVqP5zSzAdZG0FfLcC7HOIFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.3.1.tgz", + "integrity": "sha512-N9Lr3oYR2Mpzuelp1F8negJR3YE+L1ebk1rYA5qYo9TTY3f9OWdptLoNSPP9itOCBIRBqjt/S5XHlzYglLN67g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.3.1", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "leven": "^3.1.0", + "pretty-format": "^29.3.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-watcher": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.3.1.tgz", + "integrity": "sha512-RspXG2BQFDsZSRKGCT/NiNa8RkQ1iKAjrO0//soTMWx/QUt+OcxMqMSBxz23PYGqUuWm2+m2mNNsmj0eIoOaFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.3.1", + "string-length": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.3.1.tgz", + "integrity": "sha512-lY4AnnmsEWeiXirAIA0c9SDPbuCBq8IYuDVL8PMm0MZ2PEs2yPvRA/J64QBXuZp7CYKrDM/rmNrc9/i3KJQncw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.3.1", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.2.tgz", + "integrity": "sha512-46Tk9JiOL2z7ytNQWFLpj99RZkVgeHf87yGQKsIkaPz1qSH9UczKH1rO7K3wgRselo0tYMUNfecYpm/p1vC7tQ==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.8.tgz", + "integrity": "sha512-dFSmB8fFHEH/s81Xi+Y/15DQY6VHW81nXRj86EMSL3lmuTmK1e+aT4wrFCkTbm+gSwkw4KpX+rT/pMM2c1mF+A==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-locate/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", + "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve.exports": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-1.1.0.tgz", + "integrity": "sha512-J1l+Zxxp4XK3LUDZ9m60LRJF/mAe4z6a4xyabPHk7pvK5t35dACV32iIjJDFeWZFfZlO29w6SZ67knR0tHzJtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/sjcl": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/sjcl/-/sjcl-1.0.8.tgz", + "integrity": "sha512-LzIjEQ0S0DpIgnxMEayM1rq9aGwGRG4OnZhCdjx7glTaJtf4zRfpg87ImfjSJjoW9vKpagd82McDOwbRT5kQKQ==", + "engines": { + "node": "*" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/three": { + "version": "0.143.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.143.0.tgz", + "integrity": "sha512-oKcAGYHhJ46TGEuHjodo2n6TY2R6lbvrkp+feKZxqsUL/WkH7GKKaeu6RHeyb2Xjfk2dPLRKLsOP0KM2VgT8Zg==", + "license": "MIT" + }, + "node_modules/throat": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/throat/-/throat-6.0.1.tgz", + "integrity": "sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w==", + "license": "MIT" + }, + "node_modules/tinybuildapp1331": { + "resolved": "examples/graph", + "link": true + }, + "node_modules/tinybuildapp2273": { + "resolved": "examples/webrtcrouter", + "link": true + }, + "node_modules/tinybuildapp5631": { + "resolved": "examples/3dmodel", + "link": true + }, + "node_modules/tinybuildapp6104": { + "resolved": "examples/eegnfb", + "link": true + }, + "node_modules/tinybuildapp7099": { + "resolved": "examples/audiofeedback", + "link": true + }, + "node_modules/tinybuildapp8682": { + "resolved": "examples/html", + "link": true + }, + "node_modules/tinybuildapp9941": { + "resolved": "examples/httpserver", + "link": true + }, + "node_modules/tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-jest": { + "version": "29.0.3", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.0.3.tgz", + "integrity": "sha512-Ibygvmuyq1qp/z3yTh9QTwVVAbFdDy/+4BtIQR2sp6baF2SJU/8CKK/hhnGIDY2L90Az2jIqTwZPnN2p+BweiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bs-logger": "0.x", + "fast-json-stable-stringify": "2.x", + "jest-util": "^29.0.0", + "json5": "^2.2.1", + "lodash.memoize": "4.x", + "make-error": "1.x", + "semver": "7.x", + "yargs-parser": "^21.0.1" + }, + "bin": { + "ts-jest": "cli.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": ">=7.0.0-beta.0 <8", + "@jest/types": "^29.0.0", + "babel-jest": "^29.0.0", + "jest": "^29.0.0", + "typescript": ">=4.3" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "@jest/types": { + "optional": true + }, + "babel-jest": { + "optional": true + }, + "esbuild": { + "optional": true + } + } + }, + "node_modules/ts-jest/node_modules/semver": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ts-node": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", + "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/tslib": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", + "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==", + "peer": true + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "4.9.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz", + "integrity": "sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", + "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + }, + "bin": { + "browserslist-lint": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/v8-to-istanbul": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.0.1.tgz", + "integrity": "sha512-74Y4LqY74kLE6IFyIjPtkSTWzUZmj8tdHT9Ii/26dvQ6K9Dl2NbEfj0XgU2sHCtKgt5VupqhlO/5aWuqS+IY1w==", + "dev": true, + "license": "ISC", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^1.6.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "node_modules/walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "makeerror": "1.0.12" + } + }, + "node_modules/web-worker": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + }, + "node_modules/webgl-plot": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==", + "license": "MIT" + }, + "node_modules/webgl-plot-utils": { + "version": "0.3.15", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", + "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", + "dependencies": { + "webgl-plot": "~0.7.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "dev": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/ws": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", + "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true, + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.6.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.6.2.tgz", + "integrity": "sha512-1/9UrdHjDZc0eOU0HxOHoS78C69UD3JRMvzlJ7S79S2nTaWRA/whGCTV8o9e/N/1Va9YIV7Q4sOxD8VV4pCWOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "src/core/loaders/graphscript-children-loader": {}, + "src/core/loaders/graphscript-default-loader": {}, + "src/core/loaders/graphscript-listeners-loader": {}, + "src/core/loaders/graphscript-operator-loader": {}, + "src/core/loaders/graphscript-parent-loader": {}, + "src/core/loaders/graphscript-props-loader": {}, + "src/core/loaders/graphscript-root-loader": {}, + "src/extras": { + "name": "graphscript-extras", + "version": "0.2.27", + "license": "AGPL-3.0-or-later" + }, + "src/extras/build/gpu": { + "name": "graphscript-services.gpu", + "version": "0.2.27", + "license": "AGPL-3.0-or-later", + "dependencies": { + "brainsatplay-math": "^0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.3", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" + }, + "devDependencies": { + "@types/node": "~18.7.15" + } + }, + "src/extras/build/services": { + "name": "graphscript-services", + "version": "0.0.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "brainsatplay-math": "^0.0.25", + "bson-objectid": "^2.0.4", + "webgl-plot-utils": "^0.3.15" + } + }, + "src/extras/build/storage": { + "name": "graphscript-services.storage", + "version": "0.2.27", + "license": "AGPL-3.0-or-later", + "dependencies": { + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" + }, + "devDependencies": { + "@types/node": "~18.7.15" + } + }, + "src/services/e2ee": { + "extraneous": true, + "dependencies": { + "@types/sjcl": "^1.0.30", + "sjcl": "^1.0.8" + } + } + }, + "dependencies": { + "@ampproject/remapping": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", + "integrity": "sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w==", + "dev": true, + "requires": { + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "dependencies": { + "@jridgewell/gen-mapping": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz", + "integrity": "sha512-sQXCasFk+U8lWYEe66WxRDOE9PjVz4vSM51fTu3Hw+ClTpUSQb718772vH3pyS5pShp6lvQM7SxgIDXXXmOX7w==", + "dev": true, + "requires": { + "@jridgewell/set-array": "^1.0.0", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + } + } + }, + "@babel/code-frame": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "dev": true, + "requires": { + "@babel/highlight": "^7.18.6" + } + }, + "@babel/compat-data": { + "version": "7.20.10", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.20.10.tgz", + "integrity": "sha512-sEnuDPpOJR/fcafHMjpcpGN5M2jbUGUHwmuWKM/YdPzeEDJg8bgmbcWQFUfE32MQjti1koACvoPVsDe8Uq+idg==", + "dev": true + }, + "@babel/core": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.20.7.tgz", + "integrity": "sha512-t1ZjCluspe5DW24bn2Rr1CDb2v9rn/hROtg9a2tmd0+QYf4bsloYfLQzjG4qHPNMhWtKdGC33R5AxGR2Af2cBw==", + "dev": true, + "requires": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.20.7", + "@babel/helper-compilation-targets": "^7.20.7", + "@babel/helper-module-transforms": "^7.20.7", + "@babel/helpers": "^7.20.7", + "@babel/parser": "^7.20.7", + "@babel/template": "^7.20.7", + "@babel/traverse": "^7.20.7", + "@babel/types": "^7.20.7", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + } + }, + "@babel/generator": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.20.7.tgz", + "integrity": "sha512-7wqMOJq8doJMZmP4ApXTzLxSr7+oO2jroJURrVEp6XShrQUObV8Tq/D0NCcoYg2uHqUrjzO0zwBjoYzelxK+sw==", + "dev": true, + "requires": { + "@babel/types": "^7.20.7", + "@jridgewell/gen-mapping": "^0.3.2", + "jsesc": "^2.5.1" + } + }, + "@babel/helper-compilation-targets": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.20.7.tgz", + "integrity": "sha512-4tGORmfQcrc+bvrjb5y3dG9Mx1IOZjsHqQVUz7XCNHO+iTmqxWnVg3KRygjGmpRLJGdQSKuvFinbIb0CnZwHAQ==", + "dev": true, + "requires": { + "@babel/compat-data": "^7.20.5", + "@babel/helper-validator-option": "^7.18.6", + "browserslist": "^4.21.3", + "lru-cache": "^5.1.1", + "semver": "^6.3.0" + }, + "dependencies": { + "lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "requires": { + "yallist": "^3.0.2" + } + }, + "yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + } + } + }, + "@babel/helper-environment-visitor": { + "version": "7.18.9", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", + "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "dev": true + }, + "@babel/helper-function-name": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.19.0.tgz", + "integrity": "sha512-WAwHBINyrpqywkUH0nTnNgI5ina5TFn85HKS0pbPDfxFfhyR/aNQEn4hGi1P1JyT//I0t4OgXUlofzWILRvS5w==", + "dev": true, + "requires": { + "@babel/template": "^7.18.10", + "@babel/types": "^7.19.0" + } + }, + "@babel/helper-hoist-variables": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", + "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "dev": true, + "requires": { + "@babel/types": "^7.18.6" + } + }, + "@babel/helper-module-imports": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", + "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", + "dev": true, + "requires": { + "@babel/types": "^7.18.6" + } + }, + "@babel/helper-module-transforms": { + "version": "7.20.11", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.20.11.tgz", + "integrity": "sha512-uRy78kN4psmji1s2QtbtcCSaj/LILFDp0f/ymhpQH5QY3nljUZCaNWz9X1dEj/8MBdBEFECs7yRhKn8i7NjZgg==", + "dev": true, + "requires": { + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-module-imports": "^7.18.6", + "@babel/helper-simple-access": "^7.20.2", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/helper-validator-identifier": "^7.19.1", + "@babel/template": "^7.20.7", + "@babel/traverse": "^7.20.10", + "@babel/types": "^7.20.7" + } + }, + "@babel/helper-plugin-utils": { + "version": "7.20.2", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.20.2.tgz", + "integrity": "sha512-8RvlJG2mj4huQ4pZ+rU9lqKi9ZKiRmuvGuM2HlWmkmgOhbs6zEAw6IEiJ5cQqGbDzGZOhwuOQNtZMi/ENLjZoQ==", + "dev": true + }, + "@babel/helper-simple-access": { + "version": "7.20.2", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.20.2.tgz", + "integrity": "sha512-+0woI/WPq59IrqDYbVGfshjT5Dmk/nnbdpcF8SnMhhXObpTq2KNBdLFRFrkVdbDOyUmHBCxzm5FHV1rACIkIbA==", + "dev": true, + "requires": { + "@babel/types": "^7.20.2" + } + }, + "@babel/helper-split-export-declaration": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", + "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "dev": true, + "requires": { + "@babel/types": "^7.18.6" + } + }, + "@babel/helper-string-parser": { + "version": "7.19.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", + "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", + "dev": true + }, + "@babel/helper-validator-identifier": { + "version": "7.19.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", + "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "dev": true + }, + "@babel/helper-validator-option": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz", + "integrity": "sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw==", + "dev": true + }, + "@babel/helpers": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.20.7.tgz", + "integrity": "sha512-PBPjs5BppzsGaxHQCDKnZ6Gd9s6xl8bBCluz3vEInLGRJmnZan4F6BYCeqtyXqkk4W5IlPmjK4JlOuZkpJ3xZA==", + "dev": true, + "requires": { + "@babel/template": "^7.20.7", + "@babel/traverse": "^7.20.7", + "@babel/types": "^7.20.7" + } + }, + "@babel/highlight": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", + "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "@babel/parser": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.20.7.tgz", + "integrity": "sha512-T3Z9oHybU+0vZlY9CiDSJQTD5ZapcW18ZctFMi0MOAl/4BjFF4ul7NVSARLdbGO5vDqy9eQiGTV0LtKfvCYvcg==", + "dev": true + }, + "@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.12.13" + } + }, + "@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-jsx": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz", + "integrity": "sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.18.6" + } + }, + "@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.14.5" + } + }, + "@babel/plugin-syntax-typescript": { + "version": "7.20.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.20.0.tgz", + "integrity": "sha512-rd9TkG+u1CExzS4SM1BlMEhMXwFLKVjOAFFCDx9PbX5ycJWDoWMcwdJH9RhkPu1dOgn5TrxLot/Gx6lWFuAUNQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.19.0" + } + }, + "@babel/template": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz", + "integrity": "sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.18.6", + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7" + } + }, + "@babel/traverse": { + "version": "7.20.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.20.10.tgz", + "integrity": "sha512-oSf1juCgymrSez8NI4A2sr4+uB/mFd9MXplYGPEBnfAuWmmyeVcHa6xLPiaRBcXkcb/28bgxmQLTVwFKE1yfsg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.20.7", + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-function-name": "^7.19.0", + "@babel/helper-hoist-variables": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "debug": "^4.1.0", + "globals": "^11.1.0" + } + }, + "@babel/types": { + "version": "7.20.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.20.7.tgz", + "integrity": "sha512-69OnhBxSSgK0OzTJai4kyPDiKTIe3j+ctaHdIGVbRahTLAT7L3R9oeXHC2aVSuGYt3cVnoAMDmOCgJ2yaiLMvg==", + "dev": true, + "requires": { + "@babel/helper-string-parser": "^7.19.4", + "@babel/helper-validator-identifier": "^7.19.1", + "to-fast-properties": "^2.0.0" + } + }, + "@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true + }, + "@capacitor-community/bluetooth-le": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@capacitor-community/bluetooth-le/-/bluetooth-le-2.0.1.tgz", + "integrity": "sha512-K8NOAvzHKdwy+Ql9Y8hvtZh5gj5pnleAD8Q89HM9FDMbTsZmyBID0FcPGJxAZVRAb9VuaID3YykluRM7Up27ew==", + "requires": { + "@types/web-bluetooth": "^0.0.15", + "throat": "^6.0.1" + } + }, + "@capacitor/core": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@capacitor/core/-/core-4.6.1.tgz", + "integrity": "sha512-7A2IV9E8umgu9u0fChUTjQJq+Jp25GJZMmWxoQN/nVx/1rcpFJ4m1xo3NPBoIRs+aV7FR+BM17mPrnkKlA8N2g==", + "peer": true, + "requires": { + "tslib": "^2.1.0" + } + }, + "@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "requires": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "dependencies": { + "@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + } + } + }, + "@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "requires": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "dependencies": { + "camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true + } + } + }, + "@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true + }, + "@jest/console": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.3.1.tgz", + "integrity": "sha512-IRE6GD47KwcqA09RIWrabKdHPiKDGgtAL31xDxbi/RjQMsr+lY+ppxmHwY0dUEV3qvvxZzoe5Hl0RXZJOjQNUg==", + "dev": true, + "requires": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1", + "slash": "^3.0.0" + } + }, + "@jest/core": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.3.1.tgz", + "integrity": "sha512-0ohVjjRex985w5MmO5L3u5GR1O30DexhBSpuwx2P+9ftyqHdJXnk7IUWiP80oHMvt7ubHCJHxV0a0vlKVuZirw==", + "dev": true, + "requires": { + "@jest/console": "^29.3.1", + "@jest/reporters": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.2.0", + "jest-config": "^29.3.1", + "jest-haste-map": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.3.1", + "jest-resolve-dependencies": "^29.3.1", + "jest-runner": "^29.3.1", + "jest-runtime": "^29.3.1", + "jest-snapshot": "^29.3.1", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "jest-watcher": "^29.3.1", + "micromatch": "^4.0.4", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, + "@jest/environment": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.3.1.tgz", + "integrity": "sha512-pMmvfOPmoa1c1QpfFW0nXYtNLpofqo4BrCIk6f2kW4JFeNlHV2t3vd+3iDLf31e2ot2Mec0uqZfmI+U0K2CFag==", + "dev": true, + "requires": { + "@jest/fake-timers": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "jest-mock": "^29.3.1" + } + }, + "@jest/expect": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.3.1.tgz", + "integrity": "sha512-QivM7GlSHSsIAWzgfyP8dgeExPRZ9BIe2LsdPyEhCGkZkoyA+kGsoIzbKAfZCvvRzfZioKwPtCZIt5SaoxYCvg==", + "dev": true, + "requires": { + "expect": "^29.3.1", + "jest-snapshot": "^29.3.1" + } + }, + "@jest/expect-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.3.1.tgz", + "integrity": "sha512-wlrznINZI5sMjwvUoLVk617ll/UYfGIZNxmbU+Pa7wmkL4vYzhV9R2pwVqUh4NWWuLQWkI8+8mOkxs//prKQ3g==", + "dev": true, + "requires": { + "jest-get-type": "^29.2.0" + } + }, + "@jest/fake-timers": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.3.1.tgz", + "integrity": "sha512-iHTL/XpnDlFki9Tq0Q1GGuVeQ8BHZGIYsvCO5eN/O/oJaRzofG9Xndd9HuSDBI/0ZS79pg0iwn07OMTQ7ngF2A==", + "dev": true, + "requires": { + "@jest/types": "^29.3.1", + "@sinonjs/fake-timers": "^9.1.2", + "@types/node": "*", + "jest-message-util": "^29.3.1", + "jest-mock": "^29.3.1", + "jest-util": "^29.3.1" + } + }, + "@jest/globals": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.3.1.tgz", + "integrity": "sha512-cTicd134vOcwO59OPaB6AmdHQMCtWOe+/DitpTZVxWgMJ+YvXL1HNAmPyiGbSHmF/mXVBkvlm8YYtQhyHPnV6Q==", + "dev": true, + "requires": { + "@jest/environment": "^29.3.1", + "@jest/expect": "^29.3.1", + "@jest/types": "^29.3.1", + "jest-mock": "^29.3.1" + } + }, + "@jest/reporters": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.3.1.tgz", + "integrity": "sha512-GhBu3YFuDrcAYW/UESz1JphEAbvUjaY2vShRZRoRY1mxpCMB3yGSJ4j9n0GxVlEOdCf7qjvUfBCrTUUqhVfbRA==", + "dev": true, + "requires": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@jridgewell/trace-mapping": "^0.3.15", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1", + "jest-worker": "^29.3.1", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + } + }, + "@jest/schemas": { + "version": "29.0.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.0.0.tgz", + "integrity": "sha512-3Ab5HgYIIAnS0HjqJHQYZS+zXc4tUmTmBH3z83ajI6afXp8X3ZtdLX+nXx+I7LNkJD7uN9LAVhgnjDgZa2z0kA==", + "dev": true, + "requires": { + "@sinclair/typebox": "^0.24.1" + } + }, + "@jest/source-map": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.2.0.tgz", + "integrity": "sha512-1NX9/7zzI0nqa6+kgpSdKPK+WU1p+SJk3TloWZf5MzPbxri9UEeXX5bWZAPCzbQcyuAzubcdUHA7hcNznmRqWQ==", + "dev": true, + "requires": { + "@jridgewell/trace-mapping": "^0.3.15", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + } + }, + "@jest/test-result": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.3.1.tgz", + "integrity": "sha512-qeLa6qc0ddB0kuOZyZIhfN5q0e2htngokyTWsGriedsDhItisW7SDYZ7ceOe57Ii03sL988/03wAcBh3TChMGw==", + "dev": true, + "requires": { + "@jest/console": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + } + }, + "@jest/test-sequencer": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.3.1.tgz", + "integrity": "sha512-IqYvLbieTv20ArgKoAMyhLHNrVHJfzO6ARZAbQRlY4UGWfdDnLlZEF0BvKOMd77uIiIjSZRwq3Jb3Fa3I8+2UA==", + "dev": true, + "requires": { + "@jest/test-result": "^29.3.1", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "slash": "^3.0.0" + } + }, + "@jest/transform": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.3.1.tgz", + "integrity": "sha512-8wmCFBTVGYqFNLWfcOWoVuMuKYPUBTnTMDkdvFtAYELwDOl9RGwOsvQWGPFxDJ8AWY9xM/8xCXdqmPK3+Q5Lug==", + "dev": true, + "requires": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.3.1", + "@jridgewell/trace-mapping": "^0.3.15", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.3.1", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.1" + }, + "dependencies": { + "convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + } + } + }, + "@jest/types": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.3.1.tgz", + "integrity": "sha512-d0S0jmmTpjnhCmNpApgX3jrUZgZ22ivKJRvL2lli5hpCRoNnp1f85r2/wpKfXuYu8E7Jjh1hGfhPyup1NM5AmA==", + "dev": true, + "requires": { + "@jest/schemas": "^29.0.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + } + }, + "@jridgewell/gen-mapping": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", + "integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", + "dev": true, + "requires": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + } + }, + "@jridgewell/resolve-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", + "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "dev": true + }, + "@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true + }, + "@jridgewell/sourcemap-codec": { + "version": "1.4.14", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", + "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", + "dev": true + }, + "@jridgewell/trace-mapping": { + "version": "0.3.17", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.17.tgz", + "integrity": "sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" + } + }, + "@sinclair/typebox": { + "version": "0.24.51", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.24.51.tgz", + "integrity": "sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA==", + "dev": true + }, + "@sinonjs/commons": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.6.tgz", + "integrity": "sha512-Ky+XkAkqPZSm3NLBeUng77EBQl3cmeJhITaGHdYH8kjVB+aun3S4XBRti2zt17mtt0mIUDiNxYeoJm6drVvBJQ==", + "dev": true, + "requires": { + "type-detect": "4.0.8" + } + }, + "@sinonjs/fake-timers": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-9.1.2.tgz", + "integrity": "sha512-BPS4ynJW/o92PUR4wgriz2Ud5gpST5vz6GQfMixEDK0Z8ZCUv2M7SkBLykH56T++Xs+8ln9zTGbOvNGIe02/jw==", + "dev": true, + "requires": { + "@sinonjs/commons": "^1.7.0" + } + }, + "@tsconfig/node10": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", + "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", + "dev": true + }, + "@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true + }, + "@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true + }, + "@tsconfig/node16": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.3.tgz", + "integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==", + "dev": true + }, + "@types/babel__core": { + "version": "7.1.20", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.20.tgz", + "integrity": "sha512-PVb6Bg2QuscZ30FvOU7z4guG6c926D9YRvOxEaelzndpMsvP+YM74Q/dAFASpg2l6+XLalxSGxcq/lrgYWZtyQ==", + "dev": true, + "requires": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "@types/babel__generator": { + "version": "7.6.4", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", + "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@types/babel__template": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", + "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", + "dev": true, + "requires": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@types/babel__traverse": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.18.3.tgz", + "integrity": "sha512-1kbcJ40lLB7MHsj39U4Sh1uTd2E7rLEa79kmDpI6cy+XiXsteB3POdQomoq4FxszMrO3ZYchkhYJw7A2862b3w==", + "dev": true, + "requires": { + "@babel/types": "^7.3.0" + } + }, + "@types/graceful-fs": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.5.tgz", + "integrity": "sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/istanbul-lib-coverage": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", + "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", + "dev": true + }, + "@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "*" + } + }, + "@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "dev": true, + "requires": { + "@types/istanbul-lib-report": "*" + } + }, + "@types/jest": { + "version": "29.2.4", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.2.4.tgz", + "integrity": "sha512-PipFB04k2qTRPePduVLTRiPzQfvMeLwUN3Z21hsAKaB/W9IIzgB2pizCL466ftJlcyZqnHoC9ZHpxLGl3fS86A==", + "dev": true, + "requires": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "@types/node": { + "version": "18.7.19", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.19.tgz", + "integrity": "sha512-Sq1itGUKUX1ap7GgZlrzdBydjbsJL/NSQt/4wkAxUJ7/OS5c2WkoN6WSpWc2Yc5wtKMZOUA0VCs/j2XJadN3HA==", + "dev": true + }, + "@types/prettier": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", + "integrity": "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==", + "dev": true + }, + "@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", + "dev": true + }, + "@types/web-bluetooth": { + "version": "0.0.15", + "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.15.tgz", + "integrity": "sha512-w7hEHXnPMEZ+4nGKl/KDRVpxkwYxYExuHOYXyzIzCDzEZ9ZCGMAewulr9IqJu2LR4N37fcnb1XVeuZ09qgOxhA==" + }, + "@types/ws": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz", + "integrity": "sha512-6YOoWjruKj1uLf3INHH7D3qTXwFfEsg1kf3c0uDdSBJwfa/llkwIjrAGV7j7mVgGNbzTQ3HiHKKDXl6bJPD97w==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/yargs": { + "version": "17.0.17", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.17.tgz", + "integrity": "sha512-72bWxFKTK6uwWJAVT+3rF6Jo6RTojiJ27FQo8Rf60AL+VZbzoVPnMFhKsUnbjR8A3BTCYQ7Mv3hnl8T0A+CX9g==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", + "dev": true + }, + "acorn": { + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", + "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", + "dev": true + }, + "acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true + }, + "ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "requires": { + "type-fest": "^0.21.3" + } + }, + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "async": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", + "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", + "requires": { + "lodash": "^4.17.14" + } + }, + "babel-jest": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.3.1.tgz", + "integrity": "sha512-aard+xnMoxgjwV70t0L6wkW/3HQQtV+O0PEimxKgzNqCJnbYmroPojdP2tqKSOAt8QAKV/uSZU8851M7B5+fcA==", + "dev": true, + "requires": { + "@jest/transform": "^29.3.1", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.2.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + } + }, + "babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + } + }, + "babel-plugin-jest-hoist": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.2.0.tgz", + "integrity": "sha512-TnspP2WNiR3GLfCsUNHqeXw0RoQ2f9U5hQ5L3XFpwuO8htQmSrhh8qsB6vi5Yi8+kuynN1yjDjQsPfkebmB6ZA==", + "dev": true, + "requires": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + } + }, + "babel-preset-current-node-syntax": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", + "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", + "dev": true, + "requires": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-top-level-await": "^7.8.3" + } + }, + "babel-preset-jest": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.2.0.tgz", + "integrity": "sha512-z9JmMJppMxNv8N7fNRHvhMg9cvIkMxQBXgFkane3yKVEvEOP+kB50lk8DFRvF9PGqbyXxlmebKWhuDORO8RgdA==", + "dev": true, + "requires": { + "babel-plugin-jest-hoist": "^29.2.0", + "babel-preset-current-node-syntax": "^1.0.0" + } + }, + "babylonjs": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/babylonjs/-/babylonjs-5.39.0.tgz", + "integrity": "sha512-U6nI2cGrflsL9z+SsEKzOGYGm0I6eu7d2hPO3rOxCfVFMSi9rCDI0tUPxQ7JpjQ6dkGFQafvmJnczUeFt/a16w==" + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "better-sse": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz", + "integrity": "sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA==" + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, + "brainsatplay-math": { + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + }, + "browserfs": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/browserfs/-/browserfs-1.4.3.tgz", + "integrity": "sha512-tz8HClVrzTJshcyIu8frE15cjqjcBIu15Bezxsvl/i+6f59iNCN3kznlWjz0FEb3DlnDx3gW5szxeT6D1x0s0w==", + "requires": { + "async": "^2.1.4", + "pako": "^1.0.4" + } + }, + "browserslist": { + "version": "4.21.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.4.tgz", + "integrity": "sha512-CBHJJdDmgjl3daYjN5Cp5kbTf1mUhZoS+beLklHIvkOWscs83YAhLlF3Wsh/lciQYAcbBJgTOD44VtG31ZM4Hw==", + "dev": true, + "requires": { + "caniuse-lite": "^1.0.30001400", + "electron-to-chromium": "^1.4.251", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.9" + } + }, + "bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "requires": { + "fast-json-stable-stringify": "2.x" + } + }, + "bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dev": true, + "requires": { + "node-int64": "^0.4.0" + } + }, + "bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, + "buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true + }, + "camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true + }, + "caniuse-lite": { + "version": "1.0.30001441", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001441.tgz", + "integrity": "sha512-OyxRR4Vof59I3yGWXws6i908EtGbMzVUi3ganaZQHmydk1iwDhRnvaPG2WaR0KcqrDFKrxVZHULT396LEPhXfg==", + "dev": true + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true + }, + "ci-info": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.7.0.tgz", + "integrity": "sha512-2CpRNYmImPx+RXKLq6jko/L07phmS9I02TyqkcNU20GCF/GgaWvc58hPtjxDX8lPpkdwc9sNh72V9k00S7ezog==", + "dev": true + }, + "cjs-module-lexer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz", + "integrity": "sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==", + "dev": true + }, + "cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + } + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "dev": true + }, + "collect-v8-coverage": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", + "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", + "dev": true + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "dev": true + }, + "create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, + "dedent": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", + "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", + "dev": true + }, + "deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true + }, + "detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "dev": true + }, + "device-decoder": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/device-decoder/-/device-decoder-0.3.5.tgz", + "integrity": "sha512-F2D61UWMXl/MC1PMX5EIt5y4nx8vA2MHeu//uvctKzFbCXbLiS9Qv/JE3avbxgGe3Mt/mW+4nlwNlAwBdv75iQ==", + "requires": { + "@capacitor-community/bluetooth-le": "~2.0.1", + "brainsatplay-math": "~0.0.25", + "graphscript": "~0.2.27", + "graphscript-services": "~0.2.27", + "graphscript-services.gpu": "~0.2.27", + "graphscript-services.storage": "~0.2.27", + "webgl-plot-utils": "~0.3.15" + }, + "dependencies": { + "graphscript-services": { + "version": "0.2.27", + "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.27.tgz", + "integrity": "sha512-9KDKkbswyFKV+HN+oyGGMuaqZhOLrXQiLKSpAhD4k973/KiXY2BPLZpZ5pMT2+FJA/WDWXq3RBhHRli4RPJEAw==", + "requires": { + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "web-worker": "^1.2.0", + "webgl-plot-utils": "~0.3.15" + } + } + } + }, + "device-decoder.third-party": { + "version": "0.1.25", + "resolved": "https://registry.npmjs.org/device-decoder.third-party/-/device-decoder.third-party-0.1.25.tgz", + "integrity": "sha512-/l2GS56jvrzwYpDqlvAiUDUr/ruxfKhXAgUUn72TSEKjQNhrXKi+Y6TU/+WSpF/HemiL4dZ7YxshL/iQCg9kEQ==", + "requires": { + "webgl-plot-utils": "~0.3.15" + } + }, + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true + }, + "diff-sequences": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.3.1.tgz", + "integrity": "sha512-hlM3QR272NXCi4pq+N4Kok4kOp6EsgOM3ZSpJI7Da3UAs+Ttsi8MRmB6trM/lhyzUxGfOgnpkHtgqm5Q/CTcfQ==", + "dev": true + }, + "electron-to-chromium": { + "version": "1.4.284", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.284.tgz", + "integrity": "sha512-M8WEXFuKXMYMVr45fo8mq0wUrrJHheiKZf6BArTKk9ZBYCKJEOU5H8cdWgDT+qCVZf7Na4lVUaZsA+h6uA9+PA==", + "dev": true + }, + "emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "dev": true + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true + }, + "escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + } + }, + "exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "dev": true + }, + "expect": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.3.1.tgz", + "integrity": "sha512-gGb1yTgU30Q0O/tQq+z30KBWv24ApkMgFUpvKBkyLUBL68Wv8dHdJxTBZFl/iT8K/bqDHvUYRH6IIN3rToopPA==", + "dev": true, + "requires": { + "@jest/expect-utils": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1" + } + }, + "fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "fb-watchman": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", + "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "dev": true, + "requires": { + "bser": "2.1.1" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "optional": true + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true + }, + "get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true + }, + "get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true + }, + "glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true + }, + "gpujsutils": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true + }, + "graphscript": { + "version": "file:build/main", + "requires": { + "web-worker": "^1.2.0" + } + }, + "graphscript-benchmark": { + "version": "file:benchmarks" + }, + "graphscript-children-loader": { + "version": "file:src/core/loaders/graphscript-children-loader" + }, + "graphscript-core": { + "version": "file:build/core" + }, + "graphscript-default-loader": { + "version": "file:src/core/loaders/graphscript-default-loader" + }, + "graphscript-extras": { + "version": "file:src/extras" + }, + "graphscript-listeners-loader": { + "version": "file:src/core/loaders/graphscript-listeners-loader" + }, + "graphscript-node": { + "version": "file:build/node", + "requires": { + "@types/node": "~18.7.15", + "better-sse": "^0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "sjcl": "^1.0.8", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + } + }, + "graphscript-operator-loader": { + "version": "file:src/core/loaders/graphscript-operator-loader" + }, + "graphscript-parent-loader": { + "version": "file:src/core/loaders/graphscript-parent-loader" + }, + "graphscript-props-loader": { + "version": "file:src/core/loaders/graphscript-props-loader" + }, + "graphscript-root-loader": { + "version": "file:src/core/loaders/graphscript-root-loader" + }, + "graphscript-services": { + "version": "file:src/extras/build/services", + "requires": { + "brainsatplay-math": "^0.0.25", + "bson-objectid": "^2.0.4", + "webgl-plot-utils": "^0.3.15" + } + }, + "graphscript-services.gpu": { + "version": "file:src/extras/build/gpu", + "requires": { + "@types/node": "~18.7.15", + "brainsatplay-math": "^0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.3", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" + } + }, + "graphscript-services.storage": { + "version": "file:src/extras/build/storage", + "requires": { + "@types/node": "~18.7.15", + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" + } + }, + "graphscript-workercanvas-example": { + "version": "file:examples/workercanvas", + "requires": { + "graphscript": "~0.1.47", + "web-worker": "^1.2.0" + }, + "dependencies": { + "graphscript": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", + "requires": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + } + } + } + }, + "graphscript-workerecs-example": { + "version": "file:examples/workerECS", + "requires": { + "graphscript": "~0.1.47", + "three": "^0.143.0", + "web-worker": "^1.2.0", + "webgl-plot-utils": "^0.3.13" + }, + "dependencies": { + "graphscript": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", + "requires": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + } + } + } + }, + "graphscript-workerthreejs-example": { + "version": "file:examples/workerthreejs", + "requires": { + "graphscript": "~0.1.47", + "three": "^0.143.0", + "web-worker": "^1.2.0" + }, + "dependencies": { + "graphscript": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", + "requires": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.11.0" + } + } + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "howler": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/howler/-/howler-2.2.3.tgz", + "integrity": "sha512-QM0FFkw0LRX1PR8pNzJVAY25JhIWvbKMBFM4gqk+QdV+kPXOhleWGCB6AiAF/goGjIHK2e/nIElplvjQwhr0jg==" + }, + "html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true + }, + "human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true + }, + "import-local": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", + "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", + "dev": true, + "requires": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true + }, + "is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "dev": true + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true + }, + "istanbul-lib-instrument": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", + "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", + "dev": true, + "requires": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + } + }, + "istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + } + }, + "istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + } + }, + "istanbul-reports": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.5.tgz", + "integrity": "sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==", + "dev": true, + "requires": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + } + }, + "jest": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.3.1.tgz", + "integrity": "sha512-6iWfL5DTT0Np6UYs/y5Niu7WIfNv/wRTtN5RSXt2DIEft3dx3zPuw/3WJQBCJfmEzvDiEKwoqMbGD9n49+qLSA==", + "dev": true, + "requires": { + "@jest/core": "^29.3.1", + "@jest/types": "^29.3.1", + "import-local": "^3.0.2", + "jest-cli": "^29.3.1" + } + }, + "jest-changed-files": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.2.0.tgz", + "integrity": "sha512-qPVmLLyBmvF5HJrY7krDisx6Voi8DmlV3GZYX0aFNbaQsZeoz1hfxcCMbqDGuQCxU1dJy9eYc2xscE8QrCCYaA==", + "dev": true, + "requires": { + "execa": "^5.0.0", + "p-limit": "^3.1.0" + } + }, + "jest-circus": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.3.1.tgz", + "integrity": "sha512-wpr26sEvwb3qQQbdlmei+gzp6yoSSoSL6GsLPxnuayZSMrSd5Ka7IjAvatpIernBvT2+Ic6RLTg+jSebScmasg==", + "dev": true, + "requires": { + "@jest/environment": "^29.3.1", + "@jest/expect": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^0.7.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.3.1", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-runtime": "^29.3.1", + "jest-snapshot": "^29.3.1", + "jest-util": "^29.3.1", + "p-limit": "^3.1.0", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + } + }, + "jest-cli": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.3.1.tgz", + "integrity": "sha512-TO/ewvwyvPOiBBuWZ0gm04z3WWP8TIK8acgPzE4IxgsLKQgb377NYGrQLc3Wl/7ndWzIH2CDNNsUjGxwLL43VQ==", + "dev": true, + "requires": { + "@jest/core": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/types": "^29.3.1", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "import-local": "^3.0.2", + "jest-config": "^29.3.1", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "prompts": "^2.0.1", + "yargs": "^17.3.1" + } + }, + "jest-config": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.3.1.tgz", + "integrity": "sha512-y0tFHdj2WnTEhxmGUK1T7fgLen7YK4RtfvpLFBXfQkh2eMJAQq24Vx9472lvn5wg0MAO6B+iPfJfzdR9hJYalg==", + "dev": true, + "requires": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.3.1", + "@jest/types": "^29.3.1", + "babel-jest": "^29.3.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.3.1", + "jest-environment-node": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.3.1", + "jest-runner": "^29.3.1", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + } + }, + "jest-diff": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.3.1.tgz", + "integrity": "sha512-vU8vyiO7568tmin2lA3r2DP8oRvzhvRcD4DjpXc6uGveQodyk7CKLhQlCSiwgx3g0pFaE88/KLZ0yaTWMc4Uiw==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "diff-sequences": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + } + }, + "jest-docblock": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.2.0.tgz", + "integrity": "sha512-bkxUsxTgWQGbXV5IENmfiIuqZhJcyvF7tU4zJ/7ioTutdz4ToB5Yx6JOFBpgI+TphRY4lhOyCWGNH/QFQh5T6A==", + "dev": true, + "requires": { + "detect-newline": "^3.0.0" + } + }, + "jest-each": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.3.1.tgz", + "integrity": "sha512-qrZH7PmFB9rEzCSl00BWjZYuS1BSOH8lLuC0azQE9lQrAx3PWGKHTDudQiOSwIy5dGAJh7KA0ScYlCP7JxvFYA==", + "dev": true, + "requires": { + "@jest/types": "^29.3.1", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "jest-util": "^29.3.1", + "pretty-format": "^29.3.1" + } + }, + "jest-environment-node": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.3.1.tgz", + "integrity": "sha512-xm2THL18Xf5sIHoU7OThBPtuH6Lerd+Y1NLYiZJlkE3hbE+7N7r8uvHIl/FkZ5ymKXJe/11SQuf3fv4v6rUMag==", + "dev": true, + "requires": { + "@jest/environment": "^29.3.1", + "@jest/fake-timers": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "jest-mock": "^29.3.1", + "jest-util": "^29.3.1" + } + }, + "jest-get-type": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.2.0.tgz", + "integrity": "sha512-uXNJlg8hKFEnDgFsrCjznB+sTxdkuqiCL6zMgA75qEbAJjJYTs9XPrvDctrEig2GDow22T/LvHgO57iJhXB/UA==", + "dev": true + }, + "jest-haste-map": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.3.1.tgz", + "integrity": "sha512-/FFtvoG1xjbbPXQLFef+WSU4yrc0fc0Dds6aRPBojUid7qlPqZvxdUBA03HW0fnVHXVCnCdkuoghYItKNzc/0A==", + "dev": true, + "requires": { + "@jest/types": "^29.3.1", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "fsevents": "^2.3.2", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.3.1", + "jest-worker": "^29.3.1", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + } + }, + "jest-leak-detector": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.3.1.tgz", + "integrity": "sha512-3DA/VVXj4zFOPagGkuqHnSQf1GZBmmlagpguxEERO6Pla2g84Q1MaVIB3YMxgUaFIaYag8ZnTyQgiZ35YEqAQA==", + "dev": true, + "requires": { + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + } + }, + "jest-matcher-utils": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.3.1.tgz", + "integrity": "sha512-fkRMZUAScup3txIKfMe3AIZZmPEjWEdsPJFK3AIy5qRohWqQFg1qrmKfYXR9qEkNc7OdAu2N4KPHibEmy4HPeQ==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "jest-diff": "^29.3.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.3.1" + } + }, + "jest-message-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.3.1.tgz", + "integrity": "sha512-lMJTbgNcDm5z+6KDxWtqOFWlGQxD6XaYwBqHR8kmpkP+WWWG90I35kdtQHY67Ay5CSuydkTBbJG+tH9JShFCyA==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.3.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.3.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + } + }, + "jest-mock": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.3.1.tgz", + "integrity": "sha512-H8/qFDtDVMFvFP4X8NuOT3XRDzOUTz+FeACjufHzsOIBAxivLqkB1PoLCaJx9iPPQ8dZThHPp/G3WRWyMgA3JA==", + "dev": true, + "requires": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "jest-util": "^29.3.1" + } + }, + "jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "dev": true, + "requires": {} + }, + "jest-regex-util": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.2.0.tgz", + "integrity": "sha512-6yXn0kg2JXzH30cr2NlThF+70iuO/3irbaB4mh5WyqNIvLLP+B6sFdluO1/1RJmslyh/f9osnefECflHvTbwVA==", + "dev": true + }, + "jest-resolve": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.3.1.tgz", + "integrity": "sha512-amXJgH/Ng712w3Uz5gqzFBBjxV8WFLSmNjoreBGMqxgCz5cH7swmBZzgBaCIOsvb0NbpJ0vgaSFdJqMdT+rADw==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.3.1", + "jest-validate": "^29.3.1", + "resolve": "^1.20.0", + "resolve.exports": "^1.1.0", + "slash": "^3.0.0" + } + }, + "jest-resolve-dependencies": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.3.1.tgz", + "integrity": "sha512-Vk0cYq0byRw2WluNmNWGqPeRnZ3p3hHmjJMp2dyyZeYIfiBskwq4rpiuGFR6QGAdbj58WC7HN4hQHjf2mpvrLA==", + "dev": true, + "requires": { + "jest-regex-util": "^29.2.0", + "jest-snapshot": "^29.3.1" + } + }, + "jest-runner": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.3.1.tgz", + "integrity": "sha512-oFvcwRNrKMtE6u9+AQPMATxFcTySyKfLhvso7Sdk/rNpbhg4g2GAGCopiInk1OP4q6gz3n6MajW4+fnHWlU3bA==", + "dev": true, + "requires": { + "@jest/console": "^29.3.1", + "@jest/environment": "^29.3.1", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.2.0", + "jest-environment-node": "^29.3.1", + "jest-haste-map": "^29.3.1", + "jest-leak-detector": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-resolve": "^29.3.1", + "jest-runtime": "^29.3.1", + "jest-util": "^29.3.1", + "jest-watcher": "^29.3.1", + "jest-worker": "^29.3.1", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + } + }, + "jest-runtime": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.3.1.tgz", + "integrity": "sha512-jLzkIxIqXwBEOZx7wx9OO9sxoZmgT2NhmQKzHQm1xwR1kNW/dn0OjxR424VwHHf1SPN6Qwlb5pp1oGCeFTQ62A==", + "dev": true, + "requires": { + "@jest/environment": "^29.3.1", + "@jest/fake-timers": "^29.3.1", + "@jest/globals": "^29.3.1", + "@jest/source-map": "^29.2.0", + "@jest/test-result": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-mock": "^29.3.1", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.3.1", + "jest-snapshot": "^29.3.1", + "jest-util": "^29.3.1", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + } + }, + "jest-snapshot": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.3.1.tgz", + "integrity": "sha512-+3JOc+s28upYLI2OJM4PWRGK9AgpsMs/ekNryUV0yMBClT9B1DF2u2qay8YxcQd338PPYSFNb0lsar1B49sLDA==", + "dev": true, + "requires": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/traverse": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.3.1", + "@jest/transform": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/babel__traverse": "^7.0.6", + "@types/prettier": "^2.1.5", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.3.1", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.3.1", + "jest-get-type": "^29.2.0", + "jest-haste-map": "^29.3.1", + "jest-matcher-utils": "^29.3.1", + "jest-message-util": "^29.3.1", + "jest-util": "^29.3.1", + "natural-compare": "^1.4.0", + "pretty-format": "^29.3.1", + "semver": "^7.3.5" + }, + "dependencies": { + "semver": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "dev": true, + "requires": { + "lru-cache": "^6.0.0" + } + } + } + }, + "jest-util": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.3.1.tgz", + "integrity": "sha512-7YOVZaiX7RJLv76ZfHt4nbNEzzTRiMW/IiOG7ZOKmTXmoGBxUDefgMAxQubu6WPVqP5zSzAdZG0FfLcC7HOIFQ==", + "dev": true, + "requires": { + "@jest/types": "^29.3.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + } + }, + "jest-validate": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.3.1.tgz", + "integrity": "sha512-N9Lr3oYR2Mpzuelp1F8negJR3YE+L1ebk1rYA5qYo9TTY3f9OWdptLoNSPP9itOCBIRBqjt/S5XHlzYglLN67g==", + "dev": true, + "requires": { + "@jest/types": "^29.3.1", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "leven": "^3.1.0", + "pretty-format": "^29.3.1" + } + }, + "jest-watcher": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.3.1.tgz", + "integrity": "sha512-RspXG2BQFDsZSRKGCT/NiNa8RkQ1iKAjrO0//soTMWx/QUt+OcxMqMSBxz23PYGqUuWm2+m2mNNsmj0eIoOaFg==", + "dev": true, + "requires": { + "@jest/test-result": "^29.3.1", + "@jest/types": "^29.3.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.3.1", + "string-length": "^4.0.1" + } + }, + "jest-worker": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.3.1.tgz", + "integrity": "sha512-lY4AnnmsEWeiXirAIA0c9SDPbuCBq8IYuDVL8PMm0MZ2PEs2yPvRA/J64QBXuZp7CYKrDM/rmNrc9/i3KJQncw==", + "dev": true, + "requires": { + "@types/node": "*", + "jest-util": "^29.3.1", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "dependencies": { + "supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "json5": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.2.tgz", + "integrity": "sha512-46Tk9JiOL2z7ytNQWFLpj99RZkVgeHf87yGQKsIkaPz1qSH9UczKH1rO7K3wgRselo0tYMUNfecYpm/p1vC7tQ==", + "dev": true + }, + "kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true + }, + "leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true + }, + "lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true + }, + "lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "requires": { + "yallist": "^4.0.0" + } + }, + "make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "requires": { + "semver": "^6.0.0" + } + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "requires": { + "tmpl": "1.0.5" + } + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "requires": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true + }, + "node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", + "dev": true + }, + "node-releases": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.8.tgz", + "integrity": "sha512-dFSmB8fFHEH/s81Xi+Y/15DQY6VHW81nXRj86EMSL3lmuTmK1e+aT4wrFCkTbm+gSwkw4KpX+rT/pMM2c1mF+A==", + "dev": true + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "requires": { + "path-key": "^3.0.0" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "requires": { + "yocto-queue": "^0.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + }, + "dependencies": { + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + } + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" + }, + "parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true + }, + "pirates": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", + "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", + "dev": true + }, + "pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "requires": { + "find-up": "^4.0.0" + } + }, + "pretty-format": { + "version": "29.3.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.3.1.tgz", + "integrity": "sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==", + "dev": true, + "requires": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true + } + } + }, + "prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "requires": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + } + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", + "dev": true + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true + }, + "resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dev": true, + "requires": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } + }, + "resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "requires": { + "resolve-from": "^5.0.0" + } + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + }, + "resolve.exports": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-1.1.0.tgz", + "integrity": "sha512-J1l+Zxxp4XK3LUDZ9m60LRJF/mAe4z6a4xyabPHk7pvK5t35dACV32iIjJDFeWZFfZlO29w6SZ67knR0tHzJtQ==", + "dev": true + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, + "sjcl": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/sjcl/-/sjcl-1.0.8.tgz", + "integrity": "sha512-LzIjEQ0S0DpIgnxMEayM1rq9aGwGRG4OnZhCdjx7glTaJtf4zRfpg87ImfjSJjoW9vKpagd82McDOwbRT5kQKQ==" + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true + }, + "stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "requires": { + "escape-string-regexp": "^2.0.0" + } + }, + "string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "dev": true, + "requires": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + } + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true + }, + "strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true + }, + "test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "requires": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + } + }, + "three": { + "version": "0.143.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.143.0.tgz", + "integrity": "sha512-oKcAGYHhJ46TGEuHjodo2n6TY2R6lbvrkp+feKZxqsUL/WkH7GKKaeu6RHeyb2Xjfk2dPLRKLsOP0KM2VgT8Zg==" + }, + "throat": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/throat/-/throat-6.0.1.tgz", + "integrity": "sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w==" + }, + "tinybuildapp1331": { + "version": "file:examples/graph" + }, + "tinybuildapp2273": { + "version": "file:examples/webrtcrouter", + "requires": { + "better-sse": "^0.7.1", + "brainsatplay-math": "^0.0.22", + "bson-objectid": "^2.0.3", + "gpujsutils": "^1.0.12", + "web-worker": "^1.2.0", + "ws": "^8.7.0" + }, + "dependencies": { + "better-sse": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.7.1.tgz", + "integrity": "sha512-2t7XGg6hQFNwtmFXKi6/jyY5K0/4fa5UoOqVSYG2W/AFbVCt8gPnFw2LHM9ude91a8KhoXtRt9zOwpVZ5f5K5g==" + }, + "brainsatplay-math": { + "version": "0.0.22", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.22.tgz", + "integrity": "sha512-er+7fobi+bgtuiaN5Pcg0cpOfl/d5hrM8W8sF5lnX9VWhcs2TvyG3J0UV+pozGYSBvtqij7Evs4HhhFIh3cfbQ==" + } + } + }, + "tinybuildapp5631": { + "version": "file:examples/3dmodel", + "requires": { + "babylonjs": "^5.39.0", + "web-worker": "^1.2.0" + } + }, + "tinybuildapp6104": { + "version": "file:examples/eegnfb", + "requires": { + "@capacitor-community/bluetooth-le": "^2.0.1", + "browserfs": "^1.4.3", + "device-decoder": "~0.3.4", + "device-decoder.third-party": "~0.1.24", + "graphscript": "^0.2.28", + "howler": "~2.2.3", + "web-worker": "^1.2.0", + "webgl-plot-utils": "^0.3.15" + } + }, + "tinybuildapp7099": { + "version": "file:examples/audiofeedback", + "requires": { + "@capacitor-community/bluetooth-le": "^2.0.1", + "browserfs": "^1.4.3", + "device-decoder": "~0.3.4", + "graphscript": "^0.2.28", + "graphscript-services": "~0.2.26", + "howler": "~2.2.3", + "web-worker": "^1.2.0" + }, + "dependencies": { + "graphscript-services": { + "version": "0.2.27", + "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.27.tgz", + "integrity": "sha512-9KDKkbswyFKV+HN+oyGGMuaqZhOLrXQiLKSpAhD4k973/KiXY2BPLZpZ5pMT2+FJA/WDWXq3RBhHRli4RPJEAw==", + "requires": { + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "web-worker": "^1.2.0", + "webgl-plot-utils": "~0.3.15" + } + } + } + }, + "tinybuildapp8682": { + "version": "file:examples/html", + "requires": { + "web-worker": "^1.2.0" + } + }, + "tinybuildapp9941": { + "version": "file:examples/httpserver", + "requires": { + "better-sse": "^0.8.0", + "graphscript-node": "~0.1.41" + }, + "dependencies": { + "graphscript-node": { + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript-node/-/graphscript-node-0.1.52.tgz", + "integrity": "sha512-kOcEm6qgdY8sZihkiPXesVky4lUgQ5ajPyUGx2ZmEfgXaxeu35eclwmph66EtWHjLjxxtcSsdchXbAhojQb+8w==", + "requires": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.9.0" + } + }, + "ws": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.9.0.tgz", + "integrity": "sha512-Ja7nszREasGaYUYCI2k4lCKIRTt+y7XuqVoHR44YpI49TtryyqbqvDMn5eqfW7e6HzTukDRIsXqzVHScqRcafg==", + "requires": {} + } + } + }, + "tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "dev": true + }, + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "dev": true + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } + }, + "ts-jest": { + "version": "29.0.3", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.0.3.tgz", + "integrity": "sha512-Ibygvmuyq1qp/z3yTh9QTwVVAbFdDy/+4BtIQR2sp6baF2SJU/8CKK/hhnGIDY2L90Az2jIqTwZPnN2p+BweiQ==", + "dev": true, + "requires": { + "bs-logger": "0.x", + "fast-json-stable-stringify": "2.x", + "jest-util": "^29.0.0", + "json5": "^2.2.1", + "lodash.memoize": "4.x", + "make-error": "1.x", + "semver": "7.x", + "yargs-parser": "^21.0.1" + }, + "dependencies": { + "semver": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "dev": true, + "requires": { + "lru-cache": "^6.0.0" + } + } + } + }, + "ts-node": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", + "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "dev": true, + "requires": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + } + }, + "tslib": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", + "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==", + "peer": true + }, + "type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true + }, + "type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true + }, + "typescript": { + "version": "4.9.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz", + "integrity": "sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==", + "dev": true + }, + "update-browserslist-db": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", + "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", + "dev": true, + "requires": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + } + }, + "v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true + }, + "v8-to-istanbul": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.0.1.tgz", + "integrity": "sha512-74Y4LqY74kLE6IFyIjPtkSTWzUZmj8tdHT9Ii/26dvQ6K9Dl2NbEfj0XgU2sHCtKgt5VupqhlO/5aWuqS+IY1w==", + "dev": true, + "requires": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^1.6.0" + } + }, + "walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "dev": true, + "requires": { + "makeerror": "1.0.12" + } + }, + "web-worker": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + }, + "webgl-plot": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" + }, + "webgl-plot-utils": { + "version": "0.3.15", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", + "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", + "requires": { + "webgl-plot": "~0.7.0" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + } + }, + "ws": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", + "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", + "requires": {} + }, + "y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true + }, + "yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "yargs": { + "version": "17.6.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.6.2.tgz", + "integrity": "sha512-1/9UrdHjDZc0eOU0HxOHoS78C69UD3JRMvzlJ7S79S2nTaWRA/whGCTV8o9e/N/1Va9YIV7Q4sOxD8VV4pCWOw==", + "dev": true, + "requires": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + } + }, + "yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true + }, + "yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true + }, + "yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true } } } diff --git a/package.json b/package.json index 8a9b9da1..49957355 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,18 @@ { - "name": "graphscript", - "version": "0.3.12", + "name": "graphscript-monorepo", + "version": "0.2.28", "description": "Comprehensive acyclic-graph based application architecture with microservices and networking", "main": "dist/index.js", "module": "dist/index.esm.js", "types": "dist/index.d.ts", + "type": "module", + "private": true, + "workspaces": [ + "**" + ], "scripts": { - "start": "tinybuild && tinybuild path=tinybuild.node.config.js && tinybuild path=tinybuild.core.config.js && cd src/extras && npm start", - "build": "tinybuild build", + "start": "tinybuild", + "build": "cd build && cd main && tinybuild && cd ../node && tinybuild path=tinybuild.node.config.js && cd ../core && tinybuild path=tinybuild.core.config.js && cd ../../src/extras && npm run build", "serve": "tinybuild serve", "init": "node tinybuild/init.js", "concurrent": "concurrently \"npm run python\" \"npm start\"", @@ -15,28 +20,23 @@ "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", "python": "python python/server.py", "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" + "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start", + "test": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand --coverage", + "bench": "cd benchmarks && ts-node index.ts" }, "keywords": [ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "devDependencies": { - "better-sse": "~0.11.0", - "brainsatplay-math": "~0.1.0", - "web-worker": "~1.3.0", - "ws": "~8.16.0", + "@jest/globals": "^29.3.1", + "@types/jest": "^29.2.4", "@types/node": "~18.7.15", - "@types/ws": "~8.5.3" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] + "@types/ws": "~8.5.3", + "jest": "^29.3.1", + "ts-jest": "^29.0.3", + "ts-node": "^10.9.1", + "typescript": "^4.9.4" } } diff --git a/src/core/EventHandler.ts b/src/core/EventHandler.ts index 1ba81a51..e8c79608 100644 --- a/src/core/EventHandler.ts +++ b/src/core/EventHandler.ts @@ -1,29 +1,16 @@ //mini state event handler for arbitrary data event callback handling - //a graph representing a callstack of nodes which can be arranged arbitrarily with forward and backprop or propagation to wherever export class EventHandler { - data={} as {[key:string]:any} - triggers={} as {[key:string]:{sub:number,onchange:Function,[key:string]:any}[]} - ctr = 0; //sub counter, always ensures unique values + pushToState={} + data={} + triggers={} constructor(data?:{[key:string]:any}) { if(typeof data === 'object') this.data = data; } setState = (updateObj:{[key:string]:any}) => { Object.assign(this.data, updateObj); - - let props = Object.getOwnPropertyNames(updateObj) - for (const prop of props) { - this.triggerEvent(prop, this.data[prop]); - } - if(this.triggers[statesubKey]) { - let run = (fn) => { fn(updateObj); } - const l = this.triggers[statesubKey].length; - for (let i = l - 1; i >= 0; i--) { - run(this.triggers[statesubKey][i].onchange); //go in reverse in case a trigger pops - } - } - + for (const prop of Object.getOwnPropertyNames(updateObj)) this.triggerEvent(prop, this.data[prop]) return this.data; } setValue = (key, value) => { @@ -31,22 +18,11 @@ export class EventHandler { this.triggerEvent(key,value); } triggerEvent = (key, value) => { - if(this.triggers[key]) { - let fn = (obj) => { obj.onchange(value); }; - const l = this.triggers[key].length; - for (let i = l - 1; i >= 0; i--) { - fn(this.triggers[key][i]); //go in reverse in case a trigger pops - } - } - } - subscribeState = (onchange:(res:any)=>void) => { - return this.subscribeEvent(statesubKey, onchange); - } - unsubscribeState = (sub:number) => { - return this.unsubscribeEvent(statesubKey, sub); + if(this.triggers[key]) this.triggers[key].forEach((obj) => obj.onchange(value)); } subscribeEvent = (key:string,onchange:(res:any)=>void, refObject?:{[key:string]:any}, refKey?:string) => { if(key) { + if(refObject && refKey && !this.triggers[key]) { //this acts more like an observer rather than needing to hard copy stuff Object.defineProperty(this.data,key,{ @@ -65,30 +41,30 @@ export class EventHandler { this.triggers[key] = []; } - let l = this.ctr; - this.ctr++; - + let l = this.triggers[key].length; + + this.triggers[key].push({sub:l, onchange}); - return l; + return this.triggers[key].length-1; } else return undefined; } unsubscribeEvent = (key:string,sub?:number) => { - let triggers = this.triggers[key]; + let triggers = this.triggers[key] if (triggers){ - if(sub === undefined) { + if(!sub) { delete this.triggers[key]; delete this.data[key]; //garbage collect useless data } else { - let idx = undefined; + let sub = undefined; let obj = triggers.find((o,i)=>{ if(o.sub===sub) { - idx = i; + sub = i; return true; } }); - if(obj) triggers.splice(idx,1); + if(obj) triggers.splice(sub,1); if(Object.keys(triggers).length === 0) { delete this.triggers[key]; delete this.data[key]; //garbage collect useless data @@ -104,14 +80,11 @@ export class EventHandler { let changed = (value) => { onchange(value); - this.unsubscribeEvent(key, sub); + this.unsubscribeEvent(key,sub); } sub = this.subscribeEvent(key,changed); - - return sub; } - getEvent = (key,sub?) => { - if(typeof sub !== 'number') return this.triggers[key]; + getEvent = (key,sub) => { for(const s in this.triggers[key]) { if(this.triggers[key][s].sub === sub) return this.triggers[key][s]; } @@ -125,5 +98,4 @@ export class EventHandler { onRemoved:(trigger:{sub:number, onchange:Function})=>void; } -let statesubKey = '*s'; diff --git a/src/core/Graph.ts b/src/core/Graph.ts index a9b071ac..27dd3179 100644 --- a/src/core/Graph.ts +++ b/src/core/Graph.ts @@ -1,16 +1,24 @@ //graphnodes but we are going to define graph nodes as scopes and graphs as instances of scopes, // then the execution behaviors will be made plugins to recognize settings on the objects optionally. This is more generic +import { isClass } from "@babel/types"; import { EventHandler } from "./EventHandler"; +import * as loaders from "./loaders"; +import { recursiveSet } from "./loaders/graphscript-children-loader"; +import { setListeners } from "./loaders/graphscript-listeners-loader"; +import * as parsers from "./parsers"; +import { isNativeClass } from "./parsers/function"; +// import rootLoader from './loaders/graphscript-root-loader/index' -export const state = new EventHandler(); //default shared global state +// const defaultLoaders = Object.values(loaders) +export const state = new EventHandler(); //default shared global state export type GraphNodeProperties = { - __props?:Function|{[key:string]:any}|GraphNodeProperties|GraphNode, //Proxy objects or from a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. + __props?:Function|GraphNodeProperties, //a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. __operator?:((...args:any[])=>any)|string, //The 'main' function of the graph node, children will call this function if triggered by a parent. Functions passed as graphnodeproperties become the operator which can set state. - __children?:{[key:string]:any}, //child nodes belonging to this node, e.g. for propagating results - __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true, subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs + __children?:{[key:string]:GraphNodeProperties}, //child nodes belonging to this node, e.g. for propagating results + __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true,subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs __onconnected?:((node)=>void|((node)=>void)[]), //what happens once the node is created? __ondisconnected?:((node)=>void|((node)=>void)[]), //what happens when the node is deleted? __node?:{ //node specific properties, can contain a lot more things @@ -18,11 +26,10 @@ export type GraphNodeProperties = { state?:EventHandler, //by default has a global shared state [key:string]:any }, - __args?:any[], //can structure input arguments, include '__result' when generically calling operators for where to pass the original input in in a set of arguments - __callable?:boolean, //we can have the graphnode return itself as a callable function with private properties [key:string]:any } + export type Loader = ( node:GraphNode, parent:Graph|GraphNode, @@ -32,12 +39,10 @@ export type Loader = ( key:string )=>void; -export type Roots = { - [key:string]:any -} //node definitions +export type Loaders = {[x: string]: Loader} | Loader[] export type GraphOptions = { - roots?:Roots, //node definitions + roots?:{[key:string]:any}, //node definitions loaders?:{ [key:string]:Loader|{ init?:Loader, @@ -49,43 +54,6 @@ export type GraphOptions = { [key:string]:any } -export type argObject = { - __input?:string|((...args)=>any), __callback:string|((...args)=>any), //interchangeable - __args?:any[], //can use this instead of __output in general. - __output?:string|argObject|((...args)=>any) //another way to pass args from the input/callback results -} - -export type Listener = { - __callback?:string, //prototype callback - __args?:(argObject|Function|string)[], //prototype arguments - sub:number, - node:GraphNode, //owning node (source node) - graph:Graph, //owning graph - source?:string, //source node (owning node) - key?:string, //source key - target?:string, //target node - tkey?:string, //target key - arguments?:Function[] //wrapped arguments, hot swappable - subInput?:boolean, - onchange:Function //internal function called by the event handler, wrapped by graphscript -} - - -//Call node __operators like so: let node = graph.get('abc'); let result = node(input); -export class Callable extends Function { - - __bound:Callable; - __call:((...args:any[])=>any); - [key:string]:any; - - constructor() { - super('return this.__bound.__call.apply(this.__bound, arguments)') - this.__bound = this.bind(this) - return this.__bound; - } - -} - //this is a scope export class GraphNode { @@ -96,10 +64,15 @@ export class GraphNode { [key:string]:any } = { //GraphNode-specific properties tag:`node${Math.floor(Math.random()*1000000000000000)}`, - unique:`${Math.floor(Math.random()*1000000000000000)}`, + unique: `${Math.random()}`, state, + // operator: undefined as any, // graph: undefined as any, + // children: undefined as any, // localState: undefined as any, + // oncreate:undefined as any, //function or array of functions + // ondelete:undefined as any, //function or array of functions + // listeners:undefined as any, //e.g. { 'nodeA.x':(newX)=>{console.log('nodeA.x changed:',x)} } // source:undefined as any// source graph if a graph is passed as properties } @@ -108,505 +81,59 @@ export class GraphNode { __operator?; __listeners?; __props?; - __args:any[] //can structure input arguments, include '__result' when generically calling operators for where to pass the original input in in a set of arguments - // __onconnected:undefined as any, //function or array of functions - // __ondisconnected:undefined as any, //function or array of functions + [key:string]:any //pass GraphNodeProperties, functions, or tags of other nodes - constructor(properties:GraphNodeProperties, parent?:{[key:string]:any}, graph?:Graph) { - //super(); - this.__setProperties(properties,parent,graph); - - // Check if the properties are a function or denote the GraphNode to be callable (but all properties private!!) - if (typeof properties === 'function' || properties?.__callable) { //assuming operator is defined - const callableInstance = new Callable(); - callableInstance.__call = (...args) => this.__operator(...args); - - // Create a proxy to delegate function calls to callableInstance and properties to this - const proxy = new Proxy(callableInstance, { //experimental - get: (target, prop, receiver) => { - if (Reflect.has(this, prop)) { - return Reflect.get(this, prop, receiver); - } - return Reflect.get(target, prop, receiver); - }, - set: (target, prop, value, receiver) => { - if (Reflect.has(this, prop)) { - return Reflect.set(this, prop, value, receiver); - } - return Reflect.set(target, prop, value, receiver); - } - }); - Object.setPrototypeOf(proxy,this); //pass instanceof checks + constructor(properties:any, parent?:{[key:string]:any}, graph?:Graph) { - //@ts-ignore - return proxy; - } - } - - //slightly more convenient than doing this.__node.graph - get __graph() { - return this.__node?.graph; - } - - set __graph(graph) { - this.__node.graph = graph; - } + let original = properties; + if (typeof properties === 'function') properties = parsers.functions(properties) + else if (typeof properties === 'string') properties = parsers.string(properties, graph) - __setProperties = (properties, parent, graph) => { - - let enforceProperties = () => { - let orig = properties; - if(typeof properties === 'function') { - if(isNativeClass(properties)) { //works on custom classes - //console.log(properties); - properties = new properties(); //this is a class that returns a node definition - } else properties = { - __operator:properties, - __node:{ - forward:true, //propagate operator results to children - tag:properties.name - } - }; - } else if (typeof properties === 'string') { - if(graph?.get(properties)) { - properties = graph.get(properties); - } - } - if(!('__node' in properties)) properties.__node = {}; - if(!properties.__node.initial) properties.__node.initial = orig; //original object or function - } - - enforceProperties(); - - if(typeof properties === 'object') { + if (typeof properties === 'object') { - let assignState = () => { - if(properties.__node?.state) this.__node.state = properties.__node.state; //make sure we're subscribing to the right state if we're passing a custom one in - else if(graph) { - properties.__node.state = graph.__node.state; //make sure the node has the graph's state - } - } + // ---------- Set Root Property (uniquely needs graph and this) ---------- + properties = loaders.root.call(this, properties, original, graph) - let setProps = () => { - if(properties.__props) { //e.g. some generic javascript object or class constructor that we want to proxy. Functions passed here are treated as constructors. E.g. pass an HTML canvas element for the node then set this.width on the node to set the canvas width - if (typeof properties.__props === 'function') properties.__props = new properties.__props(); - if (typeof properties.__props === 'object') { - this.__proxyObject(properties.__props); - } - } - } + // ---------- Load Parent Property (uniquely needs parent) ---------- + properties = loaders.parent(properties, parent) - let setTag = () => { - if(!properties.__node.tag) { - if(properties.__operator?.name) - properties.__node.tag = properties.__operator.name; - else - properties.__node.tag = `node${Math.floor(Math.random()*1000000000000000)}`; - } - } + // ---------- Use Other Default Loaders (properties argument only) ---------- + properties = loaders.props(properties) + properties = loaders.operator(properties) + properties = loaders.defaultFunction(properties) + if (properties.default) properties.default = properties.default.bind(this) // TODO: Handle this generically for all functions somewhere else... + properties = loaders.listeners(properties) - let setNode = () => { - if (typeof properties.__node === 'string') { - //copy - if(graph?.get(properties.__node.tag)) { - properties = graph.get(properties.__node.tag); - } else properties.__node = {} - } else if(!properties.__node) properties.__node = {}; - if(graph) { - properties.__node.graph = graph; - } - if(properties instanceof Graph) properties.__node.source = properties; //keep tabs on source graphs passed to make nodes - } + // ---------- Proxy properties object with the GraphNode class ---------- + let keys = Object.getOwnPropertyNames(properties); + for (const key of keys) { - - let setParent = () => { - //child/branch nodes get their parent tags prepended in their tag - if(!properties.__parent && parent) properties.__parent = parent; - if(parent?.__node && (!(parent instanceof Graph || properties instanceof Graph))) - properties.__node.tag = parent.__node.tag + '.' + properties.__node.tag; //load parents first - if(parent instanceof Graph && properties instanceof Graph) { - if(properties.__node.loaders) Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, properties.__node.loaders); //let the parent graph adopt the child graph's loaders - if(parent.__node.mapGraphs) { - //do we still want to register the child graph's nodes on the parent graph with unique tags for navigation? Need to add cleanup in this case - properties.__node.nodes.forEach((n) => {parent.set(properties.__node.tag+'.'+n.__node.tag,n)}); - let ondelete = () => { properties.__node.nodes.forEach((n) => {parent.__node.nodes.delete(properties.__node.tag+'.'+n.__node.tag)}); } - this.__addOndisconnected(ondelete); - } + // Redefine graphscript properties as non-enumerable + const isGraphScriptProperty = key.includes('__') + if (isGraphScriptProperty) { + const desc = Object.getOwnPropertyDescriptor(properties, key) + if (desc.enumerable !== false) Object.defineProperty(properties, key, Object.assign(desc, {enumerable: false})) } - } - - let setOp = () => { - if(typeof properties.default === 'function' && !properties.__operator) { - properties.__operator = properties.default; - } //handle a default export treated as an operator - if(properties.__operator) { - if (typeof properties.__operator === 'string') { - if(graph) { - let n = graph.get(properties.__operator); - if(n) properties.__operator = n.__operator; - if(!properties.__node.tag && (properties.__operator as Function).name) - properties.__node.tag = (properties.__operator as Function).name; - } - } - if(typeof properties.__operator === 'function') - properties.__operator = this.__setOperator(properties.__operator); - if(properties.default) properties.default = properties.__operator; - } - } - - let assignProps = () => { - properties.__node = Object.assign(this.__node,properties.__node); - let keys = Object.getOwnPropertyNames(properties).filter((v)=>{if(!objProps[v]) return true;}); - for(const key of keys) { if(key in properties && key !== 'name') this[key] = properties[key]; } + // Proxy properties with getters and setters + Object.defineProperty(this, key, { + get: () => properties[key], + set: (val) => properties[key] = val, + enumerable: key.includes('__') ? false : true, // hide graphscript properties + }) } - let bindCallbacks = () => { - if(this.__onconnected) { - if(typeof this.__onconnected === 'function') { - this.__onconnected = this.__onconnected.bind(this); - } else if (Array.isArray(this.__onconnected)) { - this.__onconnected = this.__onconnected.map((f) => { return f.bind(this); }) - } - if(typeof this.__ondisconnected === 'function') { - this.__ondisconnected = this.__ondisconnected.bind(this); - } else if (Array.isArray(this.__ondisconnected)) { - this.__ondisconnected = this.__ondisconnected.map((f) => { return f.bind(this); }) - } - } - } + // ---------- Track source graphs passed to make nodes ---------- + if (properties instanceof Graph) this.__node.source = properties; - //specific load order!! - assignState(); - setTag(); - setProps(); - setNode(); - setParent(); - assignProps(); - bindCallbacks(); - setOp(); - + // ---------- Load Children as the Absolute Last Step---------- + properties = loaders.children(properties) } } - - //subscribe an output or input with an arbitrary callback - __subscribe = (callback:string|GraphNode|((res)=>void), key?:string, subInput?:boolean, target?:string, tkey?:string, args?:any[], callbackStr?:string) => { - - //console.log('subbing', this.__node.tag, key) - const subscribeToFunction = (k, setTarget = (callback, target?) => (target ? target : callback), triggerCallback=callback as (res: any) => void) => { - - let wrappedArgs; - if(args) { - let wrapped = wrapArgs(triggerCallback, args, this.__node.graph); - triggerCallback = wrapped.__callback; - wrappedArgs = wrapped.__args; - } - let sub = this.__node.state.subscribeEvent(k, triggerCallback, this, key); - - // Add details to trigger - let trigger = this.__node.state.getEvent(k,sub) as any as Listener; - if(!this.__listeners) this.__listeners = {}; - this.__listeners[k] = this.__node.state.triggers[k]; - - - if(!trigger) return sub; - trigger.source = this.__node.tag; //source being subscribed too - if(key) trigger.key = key; //source key being subscribed to - trigger.target = setTarget(callback, target); // target is node subscribing to source - if(tkey) trigger.tkey = tkey; //e.g. function or variable on the target receiving the subscription output - if(subInput) trigger.subInput = subInput; - if(args) { - trigger.arguments = wrappedArgs; //wrapped argument functions, hot swappable - trigger.__args = args; //prototype args - } - if(callbackStr) trigger.__callback = callbackStr; - - trigger.node = this; - trigger.graph = this.__node.graph; - - return sub; - } - - const getCallbackFromGraph = (callback) => { - let fn = this.__node.graph.get(callback); - if(!fn && callback.includes('.')) { - target = callback.substring(0,callback.lastIndexOf('.')); - let n = this.__node.graph.get(callback.substring(0,target)); - tkey = callback.lastIndexOf('.')+1; - if(n && typeof n[key] === 'function') callback = (...args) => { return n[tkey](...args); }; - //console.log(n, fn); - } else if (fn.__operator) { - callback = fn.__operator; - tkey = '__operator'; - } - return callback; - } - - if(key) { - // console.log(key,this.__node.tag, 'callback:', callback); - if(!this.__node.localState || !this.__node.localState[key]) { - this.__addLocalState(this, key); - } - - if(typeof callback === 'string') { - callbackStr = this.__node.tag+'.'+callback; - tkey = callback; - if(target) { - if(this.__node.graph?.get(target)) { - let n = this.__node.graph?.get(target); - if(typeof n[callback] === 'function') { - let fn = n[callback]; - callback = (...inp) => { fn(...inp); }; - } else { - let k = callback; - let setter = (inp) => { - n[k] = inp; //this callback is now a setter for a property on the target node - } - callback = setter; - } - } - } - else if(typeof this[callback] === 'function') { - let fn = this[callback]; - callback = (...inp) => {fn(...inp);}; - } else if(this.__node.graph?.get(callback)) callback = getCallbackFromGraph(callback); - if(typeof callback !== 'function') return undefined; - } - - let sub; - - let k = subInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key; - if(typeof callback === 'function' && !(callback as any)?.__node) - sub = subscribeToFunction(k, (callback, target) => (target ? target : callback), callback as (...res:any)=>void) - else if((callback as GraphNode)?.__node) sub = subscribeToFunction(k, - (callback, target) => (target ? target : (callback as GraphNode).__node.unique), - (...inp:any)=>{ if((callback as any).__operator) (callback as any).__operator(...inp); } - ) - - return sub; - } - else { - - // Get node based on the graph - if(typeof callback === 'string') { - callbackStr = callback; - if(!target) target = callback as string; - if(this.__node.graph.get(callback)) callback = this.__node.graph.get(callback); - tkey = '__operator'; - if(typeof callback !== 'object') return undefined; - } - - let sub; - - let k = subInput ? this.__node.unique+'input' : this.__node.unique; - - if(typeof callback === 'function' && !(callback as any)?.__node) sub = subscribeToFunction(k, (callback, target) => (target ? target : callback), callback as (...res:any)=>void) - else if((callback as GraphNode)?.__node) { - sub = subscribeToFunction(k, - (callback, target) => target ? target : (callback as GraphNode).__node.unique, - (...inp:any)=>{ if((callback as any).__operator) (callback as any).__operator(...inp); } - ); - } - - return sub; - } - } - - //unsub the callback - __unsubscribe = (sub?:number, key?:string, unsubInput?:boolean) => { - - //console.log('unsubbing', this.__node.tag, sub, key) - if(key) { - return this.__node.state.unsubscribeEvent( - unsubInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key, - sub - ); - } - else - return this.__node.state.unsubscribeEvent( - unsubInput ? this.__node.unique+'input' : this.__node.unique, sub - ); - } - - __setOperator = (fn:(...args:any[])=>any) => { - fn = fn.bind(this); - if(this.__args && this.__node.graph) { fn = wrapArgs(fn, this.__args, this.__node.graph).__callback; } - let inpstr = `${this.__node.unique}input`; - this.__operator = (...args) => { - if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,args); - let result = fn(...args); - if(this.__node.state.triggers[this.__node.unique]) { //don't set state (i.e. copy the result) if no subscriptions - if(typeof result?.then === 'function') { - result.then((res)=>{ if(res !== undefined) this.__node.state.setValue( this.__node.unique,res ) }).catch(console.error); - } else if(result !== undefined) this.__node.state.setValue(this.__node.unique, result); - } - return result; - } - - if(this.__parent instanceof GraphNode && !this.__subscribedToParent) { //for child nodes - if(this.__parent.__operator) { - let sub = this.__parent.__subscribe(this); - let ondelete = () => { this.__parent?.__unsubscribe(sub); delete this.__subscribedToParent;} - this.__addOndisconnected(ondelete); - this.__subscribedToParent = true; - } - } - - return this.__operator; - } - - __addLocalState = (props?:{[key:string]:any}, key?:string) => { //add easy state functionality to properties on this node using getters/setters or function wrappers - if(!props) return; - if(!this.__node.localState) { - this.__node.localState = {}; - } - const localState = this.__node.localState; - const initState = (props,k) => { - let str = this.__node.unique+'.'+k; - let inpstr = `${str}input`; //for input tracking - let get:()=>any, set:(v)=>void; - let obj, descriptor; - if(typeof props[k] === 'function' && k !== '__operator') { - if(this.__props?.[k]) { - obj = this.__props; - } - else { - obj = localState; - } - - get = () => { - return obj[k]; - } - set = (fn:Function) => { - if(!this.__props?.[k]) fn = fn.bind(this); //make sure function remains bound to node if not for a proxy - obj[k] = (...args) => { - if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,args); - let result = fn(...args); - if(this.__node.state.triggers[str]) { - if(typeof result?.then === 'function') { //assume promise (faster than instanceof) - result.then((res)=>{ this.__node.state.triggerEvent( str, res ) }).catch(console.error); - } else this.__node.state.triggerEvent(str,result); - } - - return result; - } - } - - localState[k] = props[k].bind(this) as Function; - - descriptor = { - get, set, - enumerable: true, - configurable: true - }; - - } else if (k !== '__graph') { - let get:()=>any, set:(v)=>void; - let obj; - if(this.__props?.[k]) { - obj = this.__props; - } else { - obj = localState; - } - - get = () => { - return obj[k]; - }; - - set = (v) => { - //if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,v); - obj[k] = v; - if(this.__node.state.triggers[str]) this.__node.state.triggerEvent(str,v); //this will update localState and trigger local key subscriptions - }; - - localState[k] = props[k]; - //console.log(k, localState[k]); - - descriptor = { - get, set, - enumerable: true, - configurable: true - }; - } - - - Object.defineProperty(props, k, descriptor); - - if(typeof this.__node.initial === 'object') { - let dec = Object.getOwnPropertyDescriptor(this.__node.initial,k); - if(dec === undefined || dec?.configurable) { - Object.defineProperty(this.__node.initial, k, descriptor); - } - } - } - - if(key) initState(props,key); - else { - for (let k in props) {initState(props,k);} - } - } - - //we can proxy an original object and function outputs on the node - __proxyObject = (obj) => { - const allProps = getAllProperties(obj); - - for(const k of allProps) { - //if(!(k in this)) { - const descriptor = { - get:()=>{return obj[k]}, - set:(value) => { - obj[k] = value; - }, - enumerable: true, - configurable: true - } - - Object.defineProperty(this, k, descriptor); - - if(typeof this.__node.initial === 'object') { - let dec = Object.getOwnPropertyDescriptor(this.__node.initial,k); - if(dec === undefined || dec?.configurable) { - Object.defineProperty(this.__node.initial, k, descriptor); - } - } - //} - } - } - - __addOnconnected(callback:(node)=>void) { - callback = callback.bind(this); - if(Array.isArray(this.__onconnected)) { this.__onconnected.push(callback); } - else if (typeof this.__onconnected === 'function') { this.__onconnected = [callback,this.__onconnected] } - else this.__onconnected = callback; - } - - __addOndisconnected(callback:(node)=>void) { - callback = callback.bind(this); - if(Array.isArray(this.__ondisconnected)) { this.__ondisconnected.push(callback); } - else if (typeof this.__ondisconnected === 'function') { this.__ondisconnected = [callback,this.__ondisconnected] } - else this.__ondisconnected = callback; - } - - __callConnected(node=this) { - if(typeof this.__onconnected === 'function') { this.__onconnected(this); } - else if (Array.isArray(this.__onconnected)) { - let fn = (o:Function) => { o(this); } - this.__onconnected.forEach(fn) - } - } - - __callDisconnected(node=this) { - if(typeof this.__ondisconnected === 'function') this.__ondisconnected(this); - else if (Array.isArray(this.__ondisconnected)) { - let fn = (o:Function) => {o(this)}; - this.__ondisconnected.forEach(fn); - } - } - } export class Graph { @@ -618,15 +145,16 @@ export class Graph { unique:string, state:EventHandler, nodes:Map, - roots:{[key:string]:any}, + roots?:{[key:string]:any} mapGraphs?:boolean, + loaders: Loaders, [key:string]:any } = { tag:`graph${Math.floor(Math.random()*1000000000000000)}`, unique:`${Math.random()}`, nodes:new Map(), state, - roots:{} + loaders: {}, // mapGraphs:false //if adding a Graph as a node, do we want to map all the graph's nodes with the parent graph tag denoting it (for uniqueness)? // roots:undefined as any, // loaders:undefined as any, @@ -639,110 +167,64 @@ export class Graph { this.init(options); } - init = (options?:GraphOptions) => { + init = (options:GraphOptions) => { if(options) { - let cpy = Object.assign({},options); - delete cpy.roots; //prevent overflow - recursivelyAssign(this.__node, cpy); //assign loaders etc + // if (options.loaders) options.loaders = Object.assign(options.loaders, defaultLoaders); // Merge loaders + recursivelyAssign(this.__node, options); //assign loaders etc if(options.roots) this.load(options.roots); } } - load = (roots:{[key:string]:any}, overwrite = false) => { - function recursivelyAssignChildren (target, obj, inChildren=true, top=true) { - if(top) { - if(!target) target = {}; - for(const key in obj) { - if(!key.startsWith('__') && obj[key] && typeof obj[key] === 'object') { - //test for node keys - //if(obj[key].__operator || obj[key].__node || obj[key].__props || obj[key].__children || obj[key].__parent) { - target[key] = obj[key]; - if(obj[key]?.__children) { - recursivelyAssignChildren({},obj[key].__children,false,false); - } - //} - } else if(typeof obj[key] === 'function') target[key] = obj[key]; //only copy functions for now - } - recursivelyAssignChildren(target,obj,true,false); - } else { - if(obj?.__children && !inChildren) { - if(obj.__children?.constructor.name === 'Object') { - if(target.__children?.constructor.name === 'Object') - target.__children = recursivelyAssignChildren(target.__children, obj.__children, true, false); - else target.__children = recursivelyAssignChildren({},obj.__children, true, false); - } else { - target.__children = obj.__children; - //if(typeof target[key] === 'function') target[key] = target[key].bind(this); - } - } else if (inChildren) { - for(const key in obj) { - if(!key.startsWith('__') && obj[key] && typeof obj[key] === 'object') { - //test for node keys - //if(obj[key].__operator || obj[key].__node || obj[key].__props || obj[key].__children || obj[key].__parent) { - target[key] = Object.assign({}, obj[key]); - if(obj[key]?.__children) { - target[key].__children = recursivelyAssignChildren({},obj[key].__children,false,false); - } - //} - } else if(typeof obj[key] === 'function') target[key] = obj[key]; //only copy functions for now - } - } - } + load = (roots:{[key:string]:any}) => { - return target; - } - - this.__node.roots = recursivelyAssignChildren(this.__node.roots ? this.__node.roots : {}, roots); - - //console.log('ROOTS',this.__node.roots); + this.__node.roots = Object.assign(this.__node.roots ? this.__node.roots : {}, roots); - let cpy = Object.assign({}, roots); + let cpy = Object.assign({},roots); if(cpy.__node) delete cpy.__node; //we can specify __node behaviors on the roots too to specify listeners - let listeners = this.recursiveSet(cpy,this,undefined,roots,overwrite); + recursiveSet(cpy,this,roots, this); - //make the root a node + //make the roots a node (TODO: Make this the default behavior) if(roots.__node) { - if(!roots.__node.tag) roots.__node._tag = `roots${Math.floor(Math.random()*1000000000000000)}`; + if(!roots.__node.tag) roots.__node._tag = `roots${Math.floor(Math.random()*1000000000000000)}` else if (!this.get(roots.__node.tag)) { let node = new GraphNode(roots,this,this); //blank node essentially for creating listeners - this.set(node.__node.tag,node); - - this.runLoaders(node,this, roots, roots.__node.tag); - if(node.__listeners) { - listeners[node.__node.tag] = node.__listeners; - } //now the roots can specify nodes + this.set(node.__node.tag,node); + this.runLoaders(node); } - } else if (roots.__listeners) { - this.setListeners(roots.__listeners) - } + } else if (roots.__listeners) setListeners(roots.__listeners, this) - //now setup event listeners - this.setListeners(listeners); + for (let key in roots) { + if (!key.includes('__')) { + const node = this.get(key) + if (node) node.__node.callConnected() + } + } return cpy; //should be the node roots } - setLoaders = (loaders:{[key:string]:(node:GraphNode,parent:Graph|GraphNode,graph:Graph,roots:any,props:any,key:string)=>void}, replace?:boolean) => { - if(replace) this.__node.loaders = loaders; + setLoaders = (loaders:Loaders, replace?:boolean) => { + if(replace) this.__node.loaders = loaders; else Object.assign(this.__node.loaders,loaders); return this.__node.loaders; } - runLoaders = (node, parent, properties, key) => { - for(const l in this.__node.loaders) { - if(typeof this.__node.loaders[l] === 'object') { - if(this.__node.loaders[l].init) this.__node.loaders[l](node, parent, this,this.__node.roots,properties, key); - if(this.__node.loaders[l].connected) node.__addOnconnected(this.__node.loaders[l].connect); - if(this.__node.loaders[l].disconnected) node.__addOndisconnected(this.__node.loaders[l].disconnect); - } else if (typeof this.__node.loaders[l] === 'function') this.__node.loaders[l](node, parent, this, this.__node.roots, properties, key); } //run any passes on the nodes to set things up further + runLoaders = ( node ) => { + for(const name in this.__node.loaders) { + const loader = this.__node.loaders[name]; + const root = node.__node + if(typeof loader === 'object') { + if(loader.init) loader(root.properties); + if(loader.connected) root.addOnConnected(loader.connect); + if(loader.disconnected) root.addOnDisconnected(loader.disconnect); + } else if (typeof loader === 'function') loader(root.properties); } //run any passes on the nodes to set things up further } - add = (properties:any, parent?:GraphNode|string, overwrite=true):GraphNode => { + add = (properties:any, parent?:GraphNode|string) => { - let listeners = {}; //collect listener props declared if(typeof parent === 'string') parent = this.get(parent); let instanced; @@ -750,177 +232,35 @@ export class Graph { if(isNativeClass(properties)) { //works on custom classes if(properties.prototype instanceof GraphNode) { properties = properties.prototype.constructor(properties,parent,this); instanced = true; } //reinstantiate a new node with the old node's props else properties = new properties(); //this is a class that returns a node definition - } else properties = { __operator:properties, __callable:true }; + } else properties = { __operator:properties }; } - else if (typeof properties === 'string') { - properties = this.__node.roots[properties]; - } - if(!properties) return; + else if (typeof properties === 'string') properties = this.__node.roots[properties]; if(!instanced) { - let keys = Object.getOwnPropertyNames(properties); //lets us copy e.g. Math - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(properties)); - keys.push(...nonArrowFunctions); - keys = keys.filter(v => !objProps.includes(v) ); - let cpy = {}; - for(const key of keys) { cpy[key] = properties[key]; } //make sure we don't mutate the original object - properties = cpy; + properties = Object.assign({},properties); //make sure we don't mutate the original object } - if(!properties.__node) properties.__node = {}; properties.__node.initial = properties; - - if(typeof properties === 'object' && this.get(properties.__node.tag)) { - if(overwrite) this.remove(properties.__node.tag, true); //clear the previous node and the subscriptions - else return; - } else if(properties.__node.tag && this.get(properties.__node.tag)) return this.get(properties.__node.tag); - - let node; - let root = recursivelyAssign({},properties,2); - if(instanced) node = properties; - else node = new GraphNode(properties, parent as GraphNode, this); - this.set(node.__node.tag,node); - this.runLoaders(node, parent, properties, node.__node.tag); - this.__node.roots[node.__node.tag] = root; //reference the original props by tag in the roots for children - //console.log('old:',properties.__node,'new:',node.__node); - - if(node.__children) { - node.__children = Object.assign({},node.__children); - this.recursiveSet(node.__children, node, listeners,node.__children); - } - - if(node.__listeners) { - listeners[node.__node.tag] = Object.assign({},node.__listeners); - for(const key in node.__listeners) { - let listener = node.__listeners[key]; - if(node[key]) { //subscribe to a key on the node - delete listeners[node.__node.tag][key]; - listeners[node.__node.tag][node.__node.tag+'.'+key] = listener; - } - if (typeof listener === 'string') { - if(node.__children?.[listener]) { - listeners[node.__node.tag][key] = node.__node.tag+'.'+listener; - } else if (parent instanceof GraphNode && (parent.__node.tag === listener || (parent.__node.tag.includes('.') && parent.__node.tag.split('.').pop() === listener))) { - listeners[node.__node.tag][key] = parent.__node.tag; - } - } - - } - } - //now setup event listeners - this.setListeners(listeners); - - node.__callConnected(); - return node; + if(typeof properties === 'object' && (!properties?.__node?.tag || !this.get(properties.__node.tag))) { + let node; + if(instanced) node = properties; + else node = new GraphNode(properties, parent as GraphNode, this); + this.set(node.__node.tag,node); + this.runLoaders(node); + this.__node.roots[node.__node.tag] = properties; //reference the original props by tag in the roots for children + //console.log('old:',properties.__node,'new:',node.__node); + + node.__node.callConnected(); // Ensure this node is initialized at the right time - } + return node; - recursiveSet = (originCpy, parent, listeners:any={}, origin, overwrite=false) => { - let keys = Object.getOwnPropertyNames(origin).filter((v) => !objProps.includes(v)); - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter((v) => !objProps.includes(v)); - keys.push(...nonArrowFunctions); //this is weird but it works - - for(const key of keys) { - if(key.includes('__')) continue; - let p = origin[key]; - if(Array.isArray(p)) continue; - let instanced; - if(typeof p === 'function') { - if(isNativeClass(p)) { //works on custom classes - p = new p(); //this is a class that returns a node definition - if(p instanceof GraphNode) { p = p.prototype.constructor(p,parent,this); instanced = true; } //re-instance a new node - } else p = { __operator:p, __callable:true }; - } else if (typeof p === 'string') { - if(this.__node.nodes.get(p)) p = this.__node.nodes.get(p); - else p = this.__node.roots[p]; - } else if (typeof p === 'boolean') { - if(this.__node.nodes.get(key)) p = this.__node.nodes.get(key); - else p = this.__node.roots[key]; - } - - if(p && typeof p === 'object') { - if(!instanced && !(p instanceof GraphNode)) { - let ks = Object.getOwnPropertyNames(p).filter((v) => !objProps.includes(v)); //lets us copy e.g. Math - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter((v) => !objProps.includes(v)); - nonArrowFunctions.splice(nonArrowFunctions.indexOf('constructor'),1); - ks.push(...nonArrowFunctions); - let cpy = {}; - for(const key of ks) { cpy[key] = p[key]; } //make sure we don't mutate the original object - p = cpy; - } - if(!p.__node) p.__node = {}; - if(!p.__node.tag) p.__node.tag = key; - if(!p.__node.initial) p.__node.initial = originCpy[key]; - if(overwrite && this.get(p.__node.tag)) { - this.remove(p.__node.tag, true); //clear the previous node - } - else if(( - ( - this.get(p.__node.tag) && - !(!(parent instanceof Graph) && - parent?.__node) - ) || - ( - parent?.__node && - this.get(parent.__node.tag + '.' + p.__node.tag) - ) - )) continue; //don't duplicate a node we already have in the graph by tag, todo: maybe rethink this a little bit - - let node: GraphNode; - let newnode = false; - let root = recursivelyAssign({},p,2); //preserve an unwrapped prototype, as the initial props will gain the getters/setters of the node if possible - if(instanced || p instanceof GraphNode) { - node = p; - } else { - node = new GraphNode(p, parent as GraphNode, this); - newnode = true; - } - if(!newnode && p instanceof GraphNode && !instanced && parent instanceof GraphNode) { //make sure this node is subscribed to the parent, can use this to subscribe a node multiple times as a child - let sub = this.subscribe(parent.__node.tag, node.__node.tag); - let ondelete = (node) => {this.unsubscribe(parent.__node.tag, sub);} - node.__addOndisconnected(ondelete); //cleanup sub - } else if(node) { //fresh node, run loaders etc. - //console.log(node, instanced, newnode); - this.set(node.__node.tag,node); - this.runLoaders(node, parent, originCpy[key], key); //run any passes on the nodes to set things up further - originCpy[key] = node; //replace child with a graphnode - this.__node.roots[node.__node.tag] = root; //reference the original node props by tag in the root - - if(node.__children) { - node.__children = Object.assign({}, node.__children); - this.recursiveSet(node.__children, node, listeners,node.__children); - } + } - if(node.__listeners) { - listeners[node.__node.tag] = Object.assign({},node.__listeners); - for(const key in node.__listeners) { - let listener = node.__listeners[key]; - let k = key; - if(node[key]) { //subscribe to a key on the node - delete listeners[node.__node.tag][key]; - k = node.__node.tag+'.'+key; - listeners[node.__node.tag][k] = listener; - } - if (typeof listener === 'string') { - if(node.__children?.[listener]) { - listeners[node.__node.tag][k] = node.__node.tag+'.'+listener; - } else if (parent instanceof GraphNode && (parent.__node.tag === listener || (parent.__node.tag.includes('.') && parent.__node.tag.split('.').pop() === listener))) { - listeners[node.__node.tag][k] = parent.__node.tag; - } - } - } - } - - node.__callConnected(); - } - } - } - return listeners; + return; } remove = (node:GraphNode|string, clearListeners:boolean=true) => { - this.unsubscribe(node); if(typeof node === 'string') node = this.get(node); @@ -933,7 +273,7 @@ export class Graph { this.clearListeners(node); } - node.__callDisconnected(); + node.__node.callDisconnected(); const recursiveRemove = (t) => { for(const key in t) { @@ -950,9 +290,7 @@ export class Graph { this.clearListeners(t[key]); } - //console.log(key,t[key].__listeners); - - t[key].__callDisconnected(); + t[key].__node.callDisconnected(); if(t[key].__children) { recursiveRemove(t[key].__children); @@ -967,18 +305,15 @@ export class Graph { } } - if((node as GraphNode)?.__node.tag && (node as GraphNode)?.__parent) { - delete (node as GraphNode)?.__parent; - (node as GraphNode).__node.tag = (node as GraphNode).__node.tag.substring((node as GraphNode).__node.tag.indexOf('.')+1); + if((node as any)?.__node.tag && (node as any)?.__parent) { + (node as any).__parent = null; + (node as any).__node.tag = (node as any).__node.tag.substring((node as any).__node.tag.indexOf('.')+1); } - if((node as GraphNode)?.__node.graph) (node as GraphNode).__node.graph = undefined; - - return node; + return node as GraphNode } run = (node:string|GraphNode, ...args:any[]) => { - if(typeof node === 'string') { let nd = this.get(node); if(!nd && node.includes('.')) { @@ -991,342 +326,126 @@ export class Graph { } } - -/** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners = (listeners:{[key:string]:{[key:string]:any}}) => { - - /** - * type Listener = { - * source: the source node (if any) - * key: the source key listened to (if any) - * target: the target node (if any), - * tkey: the target method key (if any) - * sub: the number for the subscription in state - * __callback:Function, - * __args:Function[], wrapped argument functions that get iterated over when a trigger is called - * arguments:any[] //the original arguments - * } - */ - - //now setup event listeners - for(const key in listeners) { - let node = this.get(key); - if(typeof listeners[key] === 'object') { - for(const k in listeners[key]) { - let n = this.get(k); - let sub; - if( typeof listeners[key][k] !== 'object' ) - listeners[key][k] = { __callback:listeners[key][k] }; - else if(!listeners[key][k].__callback) { - for(const kk in listeners[key][k]) { - if(typeof listeners[key][k][kk] !== 'object') { - listeners[key][k][kk] = {__callback: listeners[key][k][kk]} - if(node.__operator && - (listeners[key][k][kk].__callback === true || - typeof listeners[key][k][kk].__callback === 'undefined') - ) - listeners[key][k][kk].__callback = node.__operator; - } - let nn = this.get(kk); - - if(!nn) { - let tag = k.substring(0,k.lastIndexOf('.')); - nn = this.get(tag); - if(nn) { - let prop = k.substring(k.lastIndexOf('.')+1); - sub = this.subscribe( - nn, - listeners[key][k][kk].__callback, - listeners[key][k][kk].__args, - prop, - listeners[key][k][kk].subInput, - key //if the key as the target is a node tag, this lets you specify callbacks as keys of that node so e.g. {console:{'Button.onclick':'log'}} - ); - } - } else { - sub = this.subscribe( - nn, - listeners[key][k][kk].__callback, - listeners[key][k][kk].__args, - undefined, - listeners[key][k][kk].subInput, - key - ); - - } - } - } - if('__callback' in listeners[key][k]) { - if(node){ - if(listeners[key][k].__callback === true || typeof listeners[key][k].__callback === 'undefined') listeners[key][k].__callback = node.__operator; - if( typeof listeners[key][k].__callback === 'function') listeners[key][k].__callback = listeners[key][k].__callback.bind(node); - } - if(!n) { - let tag = k.substring(0,k.lastIndexOf('.')); - n = this.get(tag); - if(n) { - sub = this.subscribe( - n, - listeners[key][k].__callback, - listeners[key][k].__args, - k.substring(k.lastIndexOf('.')+1), - listeners[key][k].subInput, - key - ); - - } - } else { - sub = this.subscribe( - n, - listeners[key][k].__callback, - listeners[key][k].__args, - undefined, - listeners[key][k].subInput, - key - ); - - } - } - } - } - } - } - - clearListeners = (node:GraphNode|string, listener?:string) => { + clearListeners = (node:GraphNode|string,listener?:string) => { if(typeof node === 'string') node = this.get(node) as GraphNode; if(node?.__listeners) { //console.log(node?.__listeners); + //console.log(node.__listeners); for(const key in node.__listeners) { if(listener && key !== listener) continue; - if(typeof node.__listeners[key]?.sub !== 'number') continue; + if(typeof node.__listeners[key].sub !== 'number') continue; let n = this.get(key); if(!n) { n = this.get(key.substring(0,key.lastIndexOf('.'))); //console.log(key.substring(0,key.lastIndexOf('.')),key,n,node.__listeners[key]); if(n) { - if(typeof node.__listeners[key] === 'object' && !node.__listeners[key]?.__callback) { + if(!node.__listeners[key].__callback) { for(const k in node.__listeners[key]) { - if(typeof node.__listeners[key][k]?.sub === 'number') { - this.unsubscribe(n,node.__listeners[key][k].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key][k].subInput); - node.__listeners[key][k].sub = undefined; - } + this.unsubscribe(n,node.__listeners[key][k].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key][k].inputState); } - } else if(typeof node.__listeners[key]?.sub === 'number') { - this.unsubscribe(n,node.__listeners[key].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key].subInput); - node.__listeners[key].sub = undefined; - } + } else this.unsubscribe(n,node.__listeners[key].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key].inputState); } } else { - if(typeof !node.__listeners[key]?.__callback === 'number') { + if(!node.__listeners[key].__callback) { for(const k in node.__listeners[key]) { - if(node.__listeners[key][k]?.sub) { - this.unsubscribe(n,node.__listeners[key][k].sub, undefined, node.__listeners[key][k].subInput); - node.__listeners[key][k].sub = undefined; - } + this.unsubscribe(n,node.__listeners[key][k].sub, undefined, node.__listeners[key][k].inputState); } - } else if(typeof node.__listeners[key]?.sub === 'number') { - this.unsubscribe(n,node.__listeners[key].sub, undefined, node.__listeners[key].subInput); - node.__listeners[key].sub = undefined; - } + } else this.unsubscribe(n,node.__listeners[key].sub, undefined, node.__listeners[key].inputState); } + + //console.log('unsubscribed', key) + delete node.__listeners[key]; } } } get = (tag:string) => { return this.__node.nodes.get(tag); }; - getByUnique = (unique:string) => { return Array.from(this.__node.nodes.values()).find((node) => { if(node.__node.unique === unique) return true; })} //just in case we want to source a node by state keys - set = (tag:string,node:GraphNode) => { return this.__node.nodes.set(tag, node); }; + set = (tag:string,node:GraphNode) => { return this.__node.nodes.set(tag,node); }; delete = (tag:string) => { return this.__node.nodes.delete(tag); } - list = () => { return Array.from(this.__node.nodes.keys()); } //list loaded nodes - getListener = (nodeTag:string,key?:string,sub?:number) => { - let node = this.get(nodeTag); - if(node) { - let k = node.__node.unique; - if(key) { k += '.'+key } - return this.__node.state.getEvent(k,sub) as any as Listener; - } - } getProps = (node:GraphNode|string, getInitial?:boolean) => { if(typeof node === 'string') node = this.get(node); + if(node instanceof GraphNode) { + let cpy; if(getInitial) cpy = Object.assign({}, this.__node.roots[node.__node.tag]); else { cpy = Object.assign({},node) as any; //remove graphnode methods to return the arbitrary props - for(const key in cpy) { - if(key.includes('__')) delete cpy[key]; //remove node methods - } + delete cpy.__unsubscribe; + // delete cpy.__setOperator; + delete cpy.__node; + delete cpy.__subscribeState; + delete cpy.__subscribe; } } } subscribe = ( - nodeEvent:GraphNode|string, - onEvent:string|GraphNode|((...res:any)=>void), - args?:any[], + node:GraphNode|string, + callback:string|GraphNode|((res:any)=>void), key?:string|undefined, subInput?:boolean, - target?:string|GraphNode, - tkey?:string + target?:string, bound?:string ) => { - let nd = nodeEvent; - if(typeof nodeEvent === 'string') { - nd = this.get(nodeEvent); - if(!nd && nodeEvent.includes('.')) { - nd = this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf('.'))) - key = nodeEvent.substring(nodeEvent.lastIndexOf('.')+1); - } - } - if(target instanceof GraphNode) target = target.__node.tag; + let nd = node; + if(!(node instanceof GraphNode)) nd = this.get(node); - let callbackStr; - if(typeof onEvent === 'string') { - //console.log(node, callback, this.__node.nodes.keys()); - callbackStr = onEvent; - let setOnEventFromString = (onEvent:any) => { - if(this.get(onEvent)?.__operator) { - let node = this.get(onEvent); - target = onEvent; - onEvent = function(...inp) { return node.__operator(...inp); }; - } else if(onEvent.includes('.')) { - target = onEvent.substring(0,onEvent.lastIndexOf('.')); - let n = this.get(target as string); - let k = onEvent.substring(onEvent.lastIndexOf('.')+1); - tkey = k; - if(typeof n[k] === 'function') { - if(n[k] instanceof GraphNode) onEvent = n[k]; - else onEvent = function(...inp) { return n[k](...inp); }; - } else { - onEvent = function(inp) { n[k] = inp; return n[k]; }; //setter - } - //console.log(n, fn); - } - return onEvent; - } + let sub; + if(typeof callback === 'string') { + //console.log(node, callback, this.__node.nodes.keys()); if(target) { - let node = this.get(target); - if(typeof node?.[onEvent] === 'function') { - tkey = onEvent; - onEvent = function(...inp) { return node[key](...inp)}; - } else if(node?.[key]) { - tkey = key; - if(node[key] instanceof GraphNode) onEvent = node[key]; - else onEvent = function(inp) { node[key] = inp; return node[key]; } //setter - } else { - onEvent = setOnEventFromString(onEvent); + if(typeof this.get(target)?.[callback] === 'function') { + let key = callback; + let node = this.get(target); + callback = function(inp) {node[key](inp)}; } - } else { - onEvent = setOnEventFromString(onEvent); - } + } else callback = this.get(callback)?.__operator; } - let sub:number; - - //TODO: clean up all this samey stuff - if(nd instanceof GraphNode) { - const doSub = () => { - sub = (nd as GraphNode).__subscribe(onEvent, key, subInput, target as string, tkey, args, callbackStr); - - let ondelete = () => { - if(sub !== undefined) (nd as GraphNode).__unsubscribe(sub, key, subInput); - sub = undefined; - } - - (nd as GraphNode).__addOndisconnected(()=>{ - ondelete(); - (nd as GraphNode).__addOnconnected(() => { //need to update the listener object on the listening node - if(sub === undefined && (nd as GraphNode).__node.graph.__node.tag === this.__node.tag) doSub(); - - //console.log(key,bound,this.get(target as string).__listeners[bound]); - }) - }); - - if(typeof onEvent === 'string' && this.get(onEvent)) onEvent = this.get(onEvent); - if(onEvent instanceof GraphNode) { - onEvent.__addOndisconnected(() => { - ondelete(); - }); - } - } - - doSub(); - - } else if (typeof nodeEvent === 'string') { - let node = this.get(nodeEvent) as GraphNode; - if(node) { - if(onEvent instanceof GraphNode && onEvent.__operator) { - const doSub = () => { - sub = node.__subscribe((onEvent as GraphNode).__operator, key, subInput, target as string, tkey, args, callbackStr); - - let ondelete = () => { - if(sub !== undefined) node.__unsubscribe(sub, key, subInput); - } - - node.__addOndisconnected(()=>{ - ondelete(); - (node as GraphNode).__addOnconnected(() => { //if reconnected - if(sub === undefined && node.__node.graph.__node.tag === this.__node.tag) doSub(); - }); - }); - - (onEvent as GraphNode).__addOndisconnected(ondelete); + sub = nd.__node.listeners.subscribe(callback,key,subInput,target,bound); + + let ondelete = () => { + (nd as GraphNode).__node.listeners.unsubscribe(sub,key,subInput); + } + + const root = nd.__node + root.addOnDisconnected(ondelete); + } else if (typeof node === 'string') { + if(this.get(node)) { + if(callback instanceof GraphNode && callback.__operator) { + sub = (this.get(node) as GraphNode).__node.listeners.__node.listeners.subscribe(callback.__operator,key,subInput,target,bound); + let ondelete = () => { + this.get(node).__node.listeners.unsubscribe(sub) + //console.log('unsubscribed', key) } - - doSub(); - } - else if (typeof onEvent === 'function' || typeof onEvent === 'string') { - const doSub = () => { - sub = node.__subscribe(onEvent, key, subInput, target as string, tkey, args, callbackStr); - - let ondelete = () => { - if(sub !== undefined) node.__unsubscribe(sub, key, subInput); - sub = undefined; - } - - node.__addOndisconnected(()=>{ - ondelete(); - //console.log('unsubscribed', key) - (node as GraphNode).__addOnconnected(() => { //if reconnected - if(sub === undefined && node.__node.graph.__node.tag === this.__node.tag) doSub(); - }); - }); - - if(typeof onEvent === 'string' && this.get(onEvent)) this.get(onEvent).__addOndisconnected(ondelete); - - } - doSub(); + const root = callback.__node + root.addOnDisconnected(ondelete); + } + else if (typeof callback === 'function' || typeof callback === 'string') { + sub = (this.get(node) as GraphNode).__node.listeners.subscribe(callback,key,subInput,target,bound); + + this.__node.state.getEvent(this.get(node).__node.unique,sub).source = node; } } else { - if(typeof onEvent === 'string') onEvent = this.__node.nodes.get(onEvent).__operator; - if(typeof onEvent === 'function' && !(onEvent as any)?.__node) sub = this.__node.state.subscribeEvent(nodeEvent, onEvent as (...res:any)=>void); + if(typeof callback === 'string') callback = this.__node.nodes.get(callback).__operator; + if(typeof callback === 'function') sub = this.__node.state.subscribeEvent(node, callback); } } return sub; } unsubscribe = ( node:GraphNode|string, sub?:number, key?:string, subInput?:boolean) => { - if(node instanceof GraphNode) { - return node.__unsubscribe(sub,key,subInput); + return node.__node.listeners.unsubscribe(sub,key,subInput); } - else return this.get(node)?.__unsubscribe(sub,key,subInput); + else return this.get(node)?.__node.listeners.unsubscribe(sub,key,subInput); } setState = (update:{[key:string]:any}) => { @@ -1336,191 +455,64 @@ export class Graph { } -function recursivelyAssign (target,obj, maxDepth=Infinity,curDepth=0) { +function recursivelyAssign (target,obj) { for(const key in obj) { - if(obj[key]?.constructor.name === 'Object' && curDepth < maxDepth) { - curDepth++; - if(target[key]?.constructor.name === 'Object') - recursivelyAssign(target[key], obj[key], maxDepth, curDepth); - else target[key] = recursivelyAssign({},obj[key],maxDepth, curDepth); - } else { - target[key] = obj[key]; - //if(typeof target[key] === 'function') target[key] = target[key].bind(this); - } + if(obj[key]?.constructor.name === 'Object' && !Array.isArray(obj[key])) { + if(target[key]?.constructor.name === 'Object' && !Array.isArray(target[key])) recursivelyAssign(target[key], obj[key]); + else target[key] = recursivelyAssign({},obj[key]); + } else target[key] = obj[key]; } return target; } -export function getAllProperties(obj){ //https://stackoverflow.com/questions/8024149/is-it-possible-to-get-the-non-enumerable-inherited-property-names-of-an-object - var allProps = [] as any[], curr = obj - do{ - var props = Object.getOwnPropertyNames(curr); - let fn = function(prop){ - if (allProps.indexOf(prop) === -1) - allProps.push(prop) - } - props.forEach(fn) - } while(curr = Object.getPrototypeOf(curr)) - return allProps; -} +// export function getAllProperties(obj){ //https://stackoverflow.com/questions/8024149/is-it-possible-to-get-the-non-enumerable-inherited-property-names-of-an-object +// var allProps = [], curr = obj +// do{ +// var props = Object.getOwnPropertyNames(curr) +// props.forEach(function(prop){ +// if (allProps.indexOf(prop) === -1) +// allProps.push(prop) +// }) +// }while(curr = Object.getPrototypeOf(curr)) +// return allProps; +// } -export function instanceObject(obj) { - let props = getAllProperties(obj); //e.g. Math - let instance = {} as any; - for(const key of props) { - instance[key] = obj[key]; - } - return instance; - //simply copies methods, nested objects will not be instanced to limit recursion, unless someone wants to add circular reference detection >___> ... <___< -} - -export function isNativeClass (thing: any) { - return isFunction(thing) === 'class' -} +const rawProperties = {} +const globalObjects = ['Object', 'Array', 'Map', 'Set'] -export function isFunction(x: any) { - const res = typeof x === 'function' - ? x.prototype - ? Object.getOwnPropertyDescriptor(x, 'prototype')?.writable - ? 'function' - : 'class' - : x.constructor.name === 'AsyncFunction' - ? 'async' - : 'arrow' - : ''; - - return res -} +export function getAllProperties( obj: any ) { -// export default Graph - -//we can provide an argument list to structure inputs into a function from a set of getters for other node properties and functions etc. -//e.g. argOrder = ['__output','nodeA.x','nodeB.z'] - - -export let getCallbackFromString = (a, graph) => { - if(graph.get(a)?.__operator) { - let node = graph.get(a); - return (...inp) => { node.__operator(...inp); }; - } else if(a.includes('.')) { - let split = a.split('.'); - let popped = split.pop() as any; - let joined = split.join('.'); - let node = graph.get(joined); - if(typeof graph.get(joined)?.[popped] === 'function') { - return (...inp) => { return node[popped](...inp); }; - } else return () => { return node[popped]; }; - } else if (graph.get(a)) { //return the node itself (pass by reference :D) - let node = graph.get(a); - return () => { return node; }; - } else { - let arg = a; - return () => { return arg; }; - } -} + var props: string[] = []; + if (obj) { + do { -export const wrapArgs = (callback,argOrder,graph) => { - let args = [] as any[]; - //set up getters - - - let forArg = (a,i) => { - if(a === '__output' || a === '__input' || a === '__callback') { - args[i] = {__callback:(inp) => { return inp; }, __args:undefined, idx:i}; - } else if(typeof a === 'string') { - args[i] = {__callback:getCallbackFromString(a, graph), __args:undefined, idx:i}; - } else if (typeof a === 'function') { - let fn = a; - args[i] = {__callback:(...inp) => { return fn(...inp); }, __args:undefined, idx:i} - } else if (typeof a === 'object' && (a.__input || a.__callback)) { - //wrap i/o functions and get methods from nodes, - // recursively set arguments and the last nested - // input will resolve a value - function recursivelyCreateCallback (c:argObject) { - let input = c.__input ? c.__input : c.__callback as any; - if(typeof c.__input === 'string') { - input = {__callback:getCallbackFromString(c.__input, graph), __args:undefined, idx:i}; - //console.log('input',input); - } - if(c.__args) { - let wrapped = wrapArgs(input, c.__args, graph); - input = {__callback:wrapped.__callback, __args:wrapped.__args, idx:i}; - } else { - input = {__callback:input, __args:undefined, idx:i}; - } - if(c.__output) { - let output = c.__output as any; - if(typeof c.__output === 'string') { - output = {__callback:getCallbackFromString(output, graph), __args:undefined, idx:i}; - } else if (typeof a.__output === 'object') { - output = recursivelyCreateCallback(output as argObject); - } - if(typeof output?.__callback === 'function') { - let fn = input.__callback; - let callback = output.__callback; - input = {__callback:(...inp) => { return (callback as Function)((fn as Function)(...inp));}, __args:output.__args, idx:i} - } - } - return input; + const name = obj.constructor?.name + const isGlobalObject = globalObjects.includes(name) + if (globalObjects.includes(name)) { + if (!rawProperties[name]) rawProperties[name] = [...Object.getOwnPropertyNames(globalThis[name].prototype)] } - args[i] = recursivelyCreateCallback(a); - } else { - let arg = a; - args[i] = {__callback:() => { return arg; }, __args: undefined, idx:i}; - } - } - - argOrder.forEach(forArg); - if(typeof callback === 'string') callback = {__callback:getCallbackFromString(callback,graph), __args:undefined}; + Object.getOwnPropertyNames( obj ).forEach(function ( prop ) { + const ignore = isGlobalObject && rawProperties[name].includes(prop) + if (isGlobalObject && rawProperties[name].includes(prop)) return; // Skip inbuilt class prototypes + else if (obj.constructor?.name && prop === 'constructor') return; // Skip constructor + if ( props.indexOf( prop ) === -1 ) props.push( prop ) + }); + } while ( obj = Object.getPrototypeOf( obj )); + } - let fn = typeof callback === 'function' ? callback : callback.__callback; - callback = function (...inp) { - let mapArg = (arg) => { - return arg.__callback(...inp); - }; - const result = fn(...args.map(mapArg)); - return result; - } + return props; +} - return {__callback:callback, __args:args}; //args enable hot-swapping nested function calls - +export function instanceObject(obj) { + let props = getAllProperties(obj); //e.g. Math + let instance = {}; + for(const key of props) instance[key] = obj[key]; + return instance; + //simply copies methods, nested objects will not be instanced to limit recursion, unless someone wants to add circular reference detection >___> ... <___< } -let objProps = Object.getOwnPropertyNames(Object.getPrototypeOf({})); - - - - - -// class AnotherCallable extends Callable { -// constructor() { -// super() -// this.person = 'Dean' -// } - -// suffix(arg) { -// return `${this.person} ${arg || ''}` -// } - -// _call(arg) { -// return `${this.person} ${arg || ''}` -// } -// } - - -// var obj1 = new AnotherCallable() - -// // Method and prop access is maintained. -// console.log('Method and prop access is maintained:') -// console.log(obj1.person, obj1.suffix('Venture'), obj1('Venture')) - -// // Inheritance is correctly maintained. -// console.log('\nInheritance is maintained:') -// console.log(obj1 instanceof Function) // true -// console.log(obj1 instanceof Callable) // true -// console.log(obj1 instanceof AnotherCallable) // true - \ No newline at end of file +// export default Graph \ No newline at end of file diff --git a/src/core/loaders/graphscript-children-loader/index.ts b/src/core/loaders/graphscript-children-loader/index.ts new file mode 100644 index 00000000..ca594ac3 --- /dev/null +++ b/src/core/loaders/graphscript-children-loader/index.ts @@ -0,0 +1,68 @@ +import { root } from ".."; +import { GraphNode } from "../../Graph"; +import { isNativeClass } from "../../parsers/function"; + +export default (properties) => { + const root = properties.__node; + const graph = root.graph; + if(properties.__children) { + const children = properties.__children = Object.assign({},properties.__children); + recursiveSet(children, properties, children, graph) + } + + const parent = properties.__parent; + if (parent) { + const parentRoot = parent.__node; + if (parentRoot.addOnConnected) parentRoot.addOnConnected(root.callConnected) // Connect children of the parent + } + + return properties +} + +export function recursiveSet (t,parent,origin, graph) { + let keys = Object.getOwnPropertyNames(origin); + for(const key of keys) { + if(key.includes('__')) continue; + let p = origin[key]; + if(Array.isArray(p)) continue; + let instanced; + if(typeof p === 'function') { + if(isNativeClass(p)) { //works on custom classes + p = new p(); //graph is a class that returns a node definition + if(p instanceof GraphNode) { p = p.prototype.constructor(p,parent,graph); instanced = true; } //re-instance a new node + } else p = { __operator:p }; + } else if (typeof p === 'string') { + if(graph.__node.nodes.get(p)) p = graph.__node.nodes.get(p); + else p = graph.__node.roots[p]; + } else if (typeof p === 'boolean') { + if(graph.__node.nodes.get(key)) p = graph.__node.nodes.get(key); + else p = graph.__node.roots[key]; + } + + if(typeof p === 'object') { + + if(!instanced && !(p instanceof GraphNode)) { + p = Object.assign({},p); //make sure we don't mutate the original object + } + if(!p.__node) p.__node = {}; + if(!p.__node.tag) p.__node.tag = key; + if(!p.__node.initial) p.__node.initial = t[key]; + if((graph.get(p.__node.tag) && !(parent?.__node && graph.get(parent.__node.tag + '.' + p.__node.tag))) || (parent?.__node && graph.get(parent.__node.tag + '.' + p.__node.tag))) continue; //don't duplicate a node we already have in the graph by tag + let node: GraphNode; + if(instanced || p instanceof GraphNode) { + node = p; + } else node = new GraphNode(p, parent as GraphNode, graph); + if(p instanceof GraphNode && !instanced && parent instanceof GraphNode) { //make sure graph node is subscribed to the parent, can use graph to subscribe a node multiple times as a child + let sub = graph.subscribe(parent.__node.tag, node.__node.tag); + let ondelete = (node) => {graph.unsubscribe(parent.__node.tag, sub);} + node.addOnDisconnected(ondelete); //cleanup sub + } else { //fresh node, run loaders etc. + graph.set(node.__node.tag,node); + graph.runLoaders(node); // Setup node further + + t[key] = node; //replace child with a graphnode + graph.__node.roots[node.__node.tag] = p; //reference the original props by tag in the roots for children + } + } + } +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-children-loader/package.json b/src/core/loaders/graphscript-children-loader/package.json new file mode 100644 index 00000000..734909f5 --- /dev/null +++ b/src/core/loaders/graphscript-children-loader/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-children-loader", + "type": "module" +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-default-loader/index.ts b/src/core/loaders/graphscript-default-loader/index.ts new file mode 100644 index 00000000..3ac7efc0 --- /dev/null +++ b/src/core/loaders/graphscript-default-loader/index.ts @@ -0,0 +1,18 @@ +export default (properties) => { + + if (typeof properties.default === 'function' && !properties.__operator) { //make it so the node is subscribable + let fn = properties.default + const defaultFunction = (...args) => { + if(properties.__node.inputState) properties.__node.state.setValue(properties.__node.unique+'input',args); + let result = fn(...args); + if(typeof result?.then === 'function') { + result.then((res)=>{ if(res !== undefined) properties.__node.state.setValue( properties.__node.unique,res ) }).catch(console.error); + } else if(result !== undefined) properties.__node.state.setValue(properties.__node.unique,result); + return result; + } + + properties.default = defaultFunction; + } + + return properties +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-default-loader/package.json b/src/core/loaders/graphscript-default-loader/package.json new file mode 100644 index 00000000..82a4b331 --- /dev/null +++ b/src/core/loaders/graphscript-default-loader/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-default-loader", + "type": "module" +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-listeners-loader/index.ts b/src/core/loaders/graphscript-listeners-loader/index.ts new file mode 100644 index 00000000..76226a81 --- /dev/null +++ b/src/core/loaders/graphscript-listeners-loader/index.ts @@ -0,0 +1,230 @@ +import { Graph, GraphNode } from "../../Graph"; + +export const setListeners = (listeners, graph: Graph) => { + + //now setup event listeners + for(const key in listeners) { + let node = graph.get(key); + if(typeof listeners[key] === 'object') { + for(const k in listeners[key]) { + let n = graph.get(k); + let sub; + if( typeof listeners[key][k] !== 'object' ) listeners[key][k] = { __callback:listeners[key][k] }; + else if(!listeners[key][k].__callback) { //this is an object specifying multiple input + for(const kk in listeners[key][k]) { + if(typeof listeners[key][k][kk] !== 'object') { + listeners[key][k][kk] = {__callback: listeners[key][k][kk]} + if(listeners[key][k][kk].__callback === true) listeners[key][k][kk].__callback = node.__operator; + } + let nn = graph.get(kk); + if(nn) { + if(!nn) { + let tag = k.substring(0,k.lastIndexOf('.')); + nn = graph.get(tag); + if(nn) { + sub = graph.subscribe(nn, listeners[key][k][kk].__callback, k.substring(k.lastIndexOf('.')+1), listeners[key][k][kk].inputState, key, k); + if(typeof node.__listeners[k][kk] !== 'object') node.__listeners[k][kk] = { __callback: listeners[key][k][kk].__callback, inputState:listeners[key][k][kk]?.inputState }; + node.__listeners[k][kk].sub = sub; + } + } else { + sub = graph.subscribe(nn, listeners[key][k][kk].__callback, undefined, listeners[key][k].inputState, key, k); + if(typeof node.__listeners[k][kk] !== 'object') node.__listeners[k][kk] = { __callback: listeners[key][k][kk].__callback, inputState: listeners[key][k][kk]?.inputState }; + node.__listeners[k][kk].sub = sub; + } + } + } + } + if(listeners[key][k].__callback) { + if(listeners[key][k].__callback === true) listeners[key][k].__callback = node.__operator; + if( typeof listeners[key][k].__callback === 'function') listeners[key][k].__callback = listeners[key][k].__callback.bind(node); + if(!n) { + let tag = k.substring(0,k.lastIndexOf('.')); + n = graph.get(tag); + if(n) { + sub = graph.subscribe(n, listeners[key][k].__callback, k.substring(k.lastIndexOf('.')+1), listeners[key][k].inputState, key, k); + if(typeof node.__listeners[k] !== 'object') node.__listeners[k] = { __callback: listeners[key][k].__callback, inputState:listeners[key][k]?.inputState }; + node.__listeners[k].sub = sub; + } + } else { + sub = graph.subscribe(n, listeners[key][k].__callback, undefined, listeners[key][k].inputState, key, k); + if(typeof node.__listeners[k] !== 'object') node.__listeners[k] = { __callback: listeners[key][k].__callback, inputState: listeners[key][k]?.inputState }; + node.__listeners[k].sub = sub; + } + //console.log(sub); + } + } + } + } +} + +export default (properties) => { + const graph = properties.__node.graph + const listeners = properties.__listeners + const root = properties.__node + + + let queue = [] + let connected = false + root.listeners = { + set: (listeners) => { + if (connected) setListeners(listeners, graph) + else queue.push(listeners) + }, + subscribe: subscribe.bind(properties), + unsubscribe: unsubscribe.bind(properties), + addLocalState: addLocalState.bind(properties), + } + + Object.defineProperty(properties, '__listeners', { + value: listeners ?? {}, + enumerable: false, + writable: false, + configurable: false, + }) + + if (listeners) root.listeners.set({ [root.tag]: listeners }) + + root.addOnConnected(() => { + connected = true + queue.forEach(listeners => setListeners(listeners, graph)) + queue = [] + }) + return properties +} + + + + //subscribe an output or input with an arbitrary callback + function subscribe (callback:string|GraphNode|((res)=>void), key?:string, subInput?:boolean, bound?:string, target?:string) { + + const subscribeToFunction = (k, setTarget = (callback, target?) => callback, triggerCallback=callback as (res: any) => void) => { + let sub = this.__node.state.subscribeEvent(k, triggerCallback, this, key); + + // Add details to trigger + let trigger = this.__node.state.getEvent(k,sub); + trigger.source = this.__node.tag; + if(key) trigger.key = key; + trigger.target = setTarget(callback) // Non-string value + if(bound) trigger.bound = bound; + + return sub + } + + const subscribeToGraph = (callback) => { + let fn = this.__node.graph.get(callback); + if(!fn && callback.includes('.')) { + let n = this.__node.graph.get(callback.substring(0,callback.lastIndexOf('.'))) + let key = callback.substring(callback.lastIndexOf('.')+1); + if(n && typeof n[key] === 'function') callback = (...args) => { return n[key](...args); }; + //console.log(n, fn); + } + } + + if(key) { + // console.log(key,this.__node.tag, 'callback:', callback); + if(!this.__node.localState || !this.__node.localState[key]) this.__node.listeners.addLocalState(this.__node.properties,key); + + if(typeof callback === 'string') { + if(typeof this[callback] === 'function') callback = this[callback]; + else if(this.__node.graph) subscribeToGraph(callback) + } + let sub; + + let k = subInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key; + + if(typeof callback === 'function') sub = subscribeToFunction(k) + else if((callback as GraphNode)?.__node) sub = subscribeToFunction(k, + (callback, target) => target ? target : (callback as GraphNode).__node.unique, + (state:any)=>{ if((callback as any).__operator) (callback as any).__operator(state); } + ) + + return sub; + } + else { + + // Get node based on the graph + if(typeof callback === 'string') { + if(this.__node.graph) callback = this.__node.graph.get(callback); + else callback = this.__node.graph.nodes.get(callback); + } + + let sub; + let k = subInput ? this.__node.unique+'input' : this.__node.unique; + if(typeof callback === 'function') sub = subscribeToFunction(k) + else if((callback as GraphNode)?.__node) sub = subscribeToFunction(k, + (callback, target) => target ? target : (callback as GraphNode).__node.unique, + (state:any)=>{ if((callback as any).__operator) (callback as any).__operator(state); } + ) + + return sub; + } + } + + //unsub the callback + function unsubscribe(sub?:number, key?:string, unsubInput?:boolean) { + if(key) return this.__node.state.unsubscribeEvent(unsubInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key, sub); + else return this.__node.state.unsubscribeEvent(unsubInput ? this.__node.unique+'input' : this.__node.unique, sub); + } + + function addLocalState (props?:{[key:string]:any}, key?:string) { //add easy state functionality to properties on this node using getters/setters or function wrappers + if(!props) return; + if(!this.__node.localState) { + this.__node.localState = {}; + } + const localState = this.__node.localState; + const initState = (props,k) => { + let str = this.__node.unique+'.'+k; + let inpstr = `${str}input`; //for input tracking + if(typeof props[k] === 'function' && k !== '__operator') { + let fn = props[k].bind(this) as Function; + props[k] = (...args) => { //all functions get state functionality when called, incl resolving async results for you + if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,args); + let result = fn(...args); + if(this.__node.state.triggers[str]) { + if(typeof result?.then === 'function') { //assume promise (faster than instanceof) + result.then((res)=>{ this.__node.state.triggerEvent( str, res ) }).catch(console.error); + } else this.__node.state.triggerEvent(str,result); + } + + return result; + } + } else { + let get:()=>any, set:(v)=>void; + if(this.__props?.[k]) { + get = () => {return this.__props[k];}; + set = (v) => { + //if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,v); + this.__props[k] = v; + if(this.__node.state.triggers[str]) this.__node.state.triggerEvent(str,v); //this will update localState and trigger local key subscriptions + }; + } else { + localState[k] = props[k]; + get = () => {return localState[k];}; + set = (v) => { + //if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,v); + localState[k] = v; + if(this.__node.state.triggers[str]) this.__node.state.triggerEvent(str,v); //this will update localState and trigger local key subscriptions + }; + } + //console.log(k, localState[k]); + + const descriptor = { + get, set, + enumerable: true, + configurable: true + }; + + Object.defineProperty(props, k, descriptor); + + if(typeof this.__node.initial === 'object') { + let dec = Object.getOwnPropertyDescriptor(this.__node.initial,k); + if(dec === undefined || dec?.configurable) { + Object.defineProperty(this.__node.initial, k, descriptor); + } + } + } + } + + if(key) initState(props,key); + else {for (let k in props) {initState(props,k);}} + } \ No newline at end of file diff --git a/src/core/loaders/graphscript-listeners-loader/package.json b/src/core/loaders/graphscript-listeners-loader/package.json new file mode 100644 index 00000000..15612d65 --- /dev/null +++ b/src/core/loaders/graphscript-listeners-loader/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-listeners-loader", + "type": "module" +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-operator-loader/index.ts b/src/core/loaders/graphscript-operator-loader/index.ts new file mode 100644 index 00000000..c71513e2 --- /dev/null +++ b/src/core/loaders/graphscript-operator-loader/index.ts @@ -0,0 +1,75 @@ +import { GraphNode } from "../../Graph"; + + +const checkIfSubscribed = (node) => { + const root = node.__node + if(!root.operator.subscribedToParent) { //for child nodes + + const parent = node.__parent + const parentRef = parent ? node.__parent.__node.ref : null; + if(parentRef instanceof GraphNode && node.__parent.__operator) { + let sub = parentRef.__node.listeners.subscribe(node); + let ondelete = () => { if (parent) parent.__node.listeners.unsubscribe(sub); delete root.__subscribedToParent;} + + // TODO: Ensure this is available on the properties... + root.addOnDisconnected(ondelete); + root.operator.subscribedToParent = true; + } + } +} + +export default (properties) => { + + const root = properties.__node; + const graph = properties.__node.graph; + const ref = properties.__node.ref; + + let value = properties.__operator + + root.operator = { + subscribedToParent: false + } + + Object.defineProperty(properties, '__operator', { + get: () => value, + set: (fn:(...args:any[])=>any) => { + fn = fn.bind(ref); // Bind to node reference + + let inpstr = `${properties.__node.unique}input`; + + value = (...args) => { + if(properties.__node.state.triggers[inpstr]) properties.__node.state.setValue(inpstr,args); + let result = fn(...args); + if(properties.__node.state.triggers[properties.__node.unique]) { //don't set state (i.e. copy the result) if no subscriptions + if(typeof result?.then === 'function') { + result.then((res)=>{ if(res !== undefined) properties.__node.state.setValue( properties.__node.unique,res ) }).catch(console.error); + } else if(result !== undefined) properties.__node.state.setValue(properties.__node.unique,result); + } + return result; + } + + checkIfSubscribed(properties); // Check this for parent node + + const children = properties.__children; + for (let key in children) checkIfSubscribed(children[key]); // Check this for child nodes + + } + }) + + + if (value) { + + if (typeof value === 'string') { + if(graph) { + let n = graph.get(value); + if(n) value = n.__operator; + if(!properties.__node.tag && (value as Function).name) properties.__node.tag = (value as Function).name; + } + } + + if (typeof value === 'function') properties.__operator = value; + + } + + return properties +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-operator-loader/package.json b/src/core/loaders/graphscript-operator-loader/package.json new file mode 100644 index 00000000..6f581e7a --- /dev/null +++ b/src/core/loaders/graphscript-operator-loader/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-operator-loader", + "type": "module" +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-parent-loader/README.md b/src/core/loaders/graphscript-parent-loader/README.md new file mode 100644 index 00000000..082aafe2 --- /dev/null +++ b/src/core/loaders/graphscript-parent-loader/README.md @@ -0,0 +1,2 @@ +# graphscript-parent-loader +This is a `non-standard` loader that initializes the graphscript parent property (`__parent`). \ No newline at end of file diff --git a/src/core/loaders/graphscript-parent-loader/index.ts b/src/core/loaders/graphscript-parent-loader/index.ts new file mode 100644 index 00000000..84ce324f --- /dev/null +++ b/src/core/loaders/graphscript-parent-loader/index.ts @@ -0,0 +1,35 @@ +import { Graph } from "../../Graph"; + +export default (properties, parent) => { + if(!properties.__parent && parent) properties.__parent = parent; + + const root = properties.__node + + if(parent?.__node && (!(parent instanceof Graph || properties instanceof Graph))) + root.tag = parent.__node.tag + '.' + root.tag; //load parents first + + // TODO: Allow for directly setting this to reparent? + Object.defineProperty(properties, '__parent', { + value: parent, + enumerable: false, + writable: true, + configurable: false + }) + + if(parent instanceof Graph && properties instanceof Graph) { + + if(root.loaders) Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, root.loaders); //let the parent graph adopt the child graph's loaders + + if(parent.__node.mapGraphs) { + //do we still want to register the child graph's nodes on the parent graph with unique tags for navigation? Need to add cleanup in this case + root.nodes.forEach((n) => {parent.set(root.tag+'.'+n.__node.tag,n)}); + + let ondelete = () => { root.nodes.forEach((n) => {parent.__node.nodes.delete(root.tag+'.'+n.__node.tag)}); } + root.addOnDisconnected(ondelete); + + } + } + + + return properties +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-parent-loader/package.json b/src/core/loaders/graphscript-parent-loader/package.json new file mode 100644 index 00000000..7341a9b2 --- /dev/null +++ b/src/core/loaders/graphscript-parent-loader/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-parent-loader", + "type": "module" +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-props-loader/index.ts b/src/core/loaders/graphscript-props-loader/index.ts new file mode 100644 index 00000000..0bd4667e --- /dev/null +++ b/src/core/loaders/graphscript-props-loader/index.ts @@ -0,0 +1,50 @@ +import { getAllProperties } from "../../Graph"; + + +const proxyFunction = (k, obj) => { + const fn = obj[k]; + return (...args) => fn.call(obj, ...args) //simple proxy to preserve original function scope +} +export default (properties) => { + + let proxied= {} + let ogProxy = properties.__props; + Object.defineProperty(properties, '__props', { + get: () => ogProxy, // TODO: Make this adapt to additional changes... + + set: (obj) => { + if (!ogProxy) ogProxy = obj + const allProps = getAllProperties(obj); + for(const k of allProps) { + if(!(k in proxied)) { + + const ogValue = properties[k] + const hasOGValue = k in properties + const isFunction = typeof obj[k] === 'function' + if (isFunction) properties[k] = proxyFunction(k, obj) + else Object.defineProperty(properties, k, { + // get: ()=> wasFunction ? fn : obj[k], + get: () => obj[k], + set: (value) => { + // if (typeof value === 'function') fn = proxyFunction(k, obj) // Proxy new functions + // else + obj[k] = value + }, + // enumerable: true, + configurable: true // Can add a getter / setter + }); + + proxied[k] = true + if (hasOGValue) properties[k] = ogValue // setting original value + } + } + } + }) + + if(ogProxy) { //e.g. some generic javascript object or class constructor that we want to proxy. Functions passed here are treated as constructors. E.g. pass an HTML canvas element for the node then set this.width on the node to set the canvas width + if (typeof ogProxy === 'function') ogProxy = new ogProxy(); + if (typeof ogProxy === 'object') properties.__props = ogProxy ; // Trigger the setter + } + + return properties +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-props-loader/package.json b/src/core/loaders/graphscript-props-loader/package.json new file mode 100644 index 00000000..47c2a4d2 --- /dev/null +++ b/src/core/loaders/graphscript-props-loader/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-props-loader", + "type": "module" +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-root-loader/README.md b/src/core/loaders/graphscript-root-loader/README.md new file mode 100644 index 00000000..a5bd644c --- /dev/null +++ b/src/core/loaders/graphscript-root-loader/README.md @@ -0,0 +1,2 @@ +# graphscript-root-loader +This is a `non-standard` loader that initializes the graphscript root property (`__node`). \ No newline at end of file diff --git a/src/core/loaders/graphscript-root-loader/index.ts b/src/core/loaders/graphscript-root-loader/index.ts new file mode 100644 index 00000000..6955af13 --- /dev/null +++ b/src/core/loaders/graphscript-root-loader/index.ts @@ -0,0 +1,67 @@ + +function addOnConnected(callback:(node)=>void) { + this.__node.connectCallbacks.push(callback); +} + +function addOnDisconnected(callback:(node)=>void) { + this.__node.disconnectCallbacks.push(callback); +} + +function callConnected() { + const ref = this.__node.ref; + this.__node.connectCallbacks.forEach((o:Function) => { o.call(ref,ref); }) +} + +function callDisconnected() { + const ref = this.__node.ref; + this.__node.disconnectCallbacks.forEach((o:Function) => { o.call(ref, ref) }); +} + +export default function (properties, original, graph) { + + // Create a new object to store the properties + if (typeof properties.__node === 'string') { + if(graph?.get(properties.__node.tag)) properties = graph.get(properties.__node.tag); + } + + let root = properties.__node ?? {} + if (root?.state) this.__node.state = root.state; //make sure we're subscribing to the right state if we're passing a custom one in + root = Object.assign(this.__node, root) + root.properties = properties // track properties object + root.ref = this; // track the reference to the node + + const desc = { + value: root, + enumerable: false, + writable: false, + configurable: false + } + + Object.defineProperty(properties, '__node', desc); + + // Add lifecycle methods + root.addOnConnected = addOnConnected.bind(properties); + root.addOnDisconnected = addOnDisconnected.bind(properties); + root.callConnected = callConnected.bind(properties); + root.callDisconnected = callDisconnected.bind(properties); + const onconnect = properties.__onconnected + const ondisconnect = properties.__ondisconnected + + root.connectCallbacks = onconnect ? [onconnect] : []; + root.disconnectCallbacks = ondisconnect ? [ondisconnect] : []; + + // Ensure you track the graph + if(graph) root.graph = graph; + + + // Track Original + if (!properties.__node.initial) properties.__node.initial = original; //original object or function + + // Provide the node with a name + if(!root.tag) { + if(properties.__operator?.name) root.tag = properties.__operator.name; + else root.tag = `node${Math.floor(Math.random()*1000000000000000)}`; + } + + return properties +} \ No newline at end of file diff --git a/src/core/loaders/graphscript-root-loader/package.json b/src/core/loaders/graphscript-root-loader/package.json new file mode 100644 index 00000000..a096e407 --- /dev/null +++ b/src/core/loaders/graphscript-root-loader/package.json @@ -0,0 +1,4 @@ +{ + "name": "graphscript-root-loader", + "type": "module" +} \ No newline at end of file diff --git a/src/core/loaders/index.ts b/src/core/loaders/index.ts new file mode 100644 index 00000000..e70372db --- /dev/null +++ b/src/core/loaders/index.ts @@ -0,0 +1,17 @@ +import children from './graphscript-children-loader/index' +import listeners from './graphscript-listeners-loader/index' +import operator from './graphscript-operator-loader/index' +import parent from './graphscript-parent-loader/index' +import props from './graphscript-props-loader/index' +import root from './graphscript-root-loader/index' +import defaultFunction from './graphscript-default-loader/index' + +export { + children, + defaultFunction, + listeners, + operator, + parent, + props, + root +} \ No newline at end of file diff --git a/src/core/parsers/function.ts b/src/core/parsers/function.ts new file mode 100644 index 00000000..8c8a1aa2 --- /dev/null +++ b/src/core/parsers/function.ts @@ -0,0 +1,34 @@ + +// export function isNativeClass (thing) { +// return typeof thing === 'function' && thing.hasOwnProperty('prototype') && !thing.hasOwnProperty('arguments') +// } + +export function isNativeClass (thing) { + return isFunction(thing) === 'class' +} + + +export function isFunction(x) { + const res = typeof x === 'function' + ? x.prototype + ? Object.getOwnPropertyDescriptor(x, 'prototype').writable + ? 'function' + : 'class' + : x.constructor.name === 'AsyncFunction' + ? 'async' + : 'arrow' + : ''; + + return res +} + +export default (properties) => { + if ( isNativeClass(properties) ) return new properties(); //this is a class that returns a node definition + else return { + __operator:properties, + __node:{ + forward:true, //propagate operator results to children + tag:properties.name + } + }; +} \ No newline at end of file diff --git a/src/core/parsers/index.ts b/src/core/parsers/index.ts new file mode 100644 index 00000000..4a99850d --- /dev/null +++ b/src/core/parsers/index.ts @@ -0,0 +1,7 @@ +import functions from './function' +import string from './string' + +export { + functions, + string +} \ No newline at end of file diff --git a/src/core/parsers/string.ts b/src/core/parsers/string.ts new file mode 100644 index 00000000..165e2d16 --- /dev/null +++ b/src/core/parsers/string.ts @@ -0,0 +1,4 @@ +export default (properties, graph) => { + if(graph?.get(properties)) return graph.get(properties); + else return properties +} \ No newline at end of file diff --git a/src/extras/README.md b/src/extras/README.md index 4dc34cc1..fd7f3143 100644 --- a/src/extras/README.md +++ b/src/extras/README.md @@ -1,5 +1 @@ -Keep the bloatware here so it's out of the main NPM dist - -TODO: We still need to break up the dists so the NPM all doesn't have the same files - -Also need to fix types dist \ No newline at end of file +Keep the bloatware here so it's out of the main NPM dist \ No newline at end of file diff --git a/src/extras/____package.json b/src/extras/____package.json deleted file mode 100644 index 7de86a76..00000000 --- a/src/extras/____package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "graphscript-services-node", - "version": "0.3.2", - "description": "Extra services for graphscript.", - "main": "dist/index.services.node.js", - "types": "dist/src/extras/index.services.d.ts", - "scripts": { - "start": "tinybuild path=tinybuild.config.js && tinybuild path=tinybuild.gpu.config.js && tinybuild path=tinybuild.storage.config.js", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \"npm run python\" \"npm start\"", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", - "dependencies": { - "brainsatplay-math": "~0.1.0", - "browserfs": "~1.4.3", - "gpujsutils": "~1.0.15", - "web-worker": "~1.2.0", - "webgl-plot-utils": "~0.4.2" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - }, - "devDependencies": { - "@types/node": "~18.7.15" - } -} diff --git a/src/extras/algorithms/accel_gyro.ts b/src/extras/algorithms/accel_gyro.ts index fc1c3bff..4dd3bb81 100644 --- a/src/extras/algorithms/accel_gyro.ts +++ b/src/extras/algorithms/accel_gyro.ts @@ -1,21 +1,23 @@ import { Math2 } from 'brainsatplay-math'; -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; //convert accelerometer and gyro data into cartesian position changes //https://howtomechatronics.com/tutorials/arduino/arduino-and-mpu6050-accelerometer-and-gyroscope-tutorial/ export const accel_gyro = { - accelConstant: 1/8192, //+/-4g mpu6050 //1/16384, //+/- 2g mpu6050 - gyroConstant: 1/65.5, //500deg/s //1/131, //250deg/s mpu6050 - gyroXAngle:0, - gyroYAngle:0, - gyroZAngle:0, - px:0, - py:0, - pz:0, - sps:100, - lastAccelTime:Date.now(), - lastGyroTime:Date.now(), - __operator:function(data:{ + structs:{ + accelConstant: 1/8192, //+/-4g mpu6050 //1/16384, //+/- 2g mpu6050 + gyroConstant: 1/65.5, //500deg/s //1/131, //250deg/s mpu6050 + gyroXAngle:0, + gyroYAngle:0, + gyroZAngle:0, + px:0, + py:0, + pz:0, + sps:100, + lastAccelTime:Date.now(), + lastGyroTime:Date.now() + }, + ondata:(ctx, data:{ ax:number|number[], ay:number|number[], az:number|number[], @@ -35,7 +37,7 @@ export const accel_gyro = { gz:number|number[], [key:string]:any, timestamp?:number|number[] - }) { + })=>{ if(!('ax' in data) && !('gx' in data)) return undefined; //invalid data @@ -43,7 +45,7 @@ export const accel_gyro = { if((data.ax && Array.isArray(data.ax)) || (data.gx && Array.isArray(data.gx))) { //assume timestamp let len = data.ax ? data.ax.length : data.gx.length; let now = Date.now(); - let toInterp = [now - len*this.sps*1000, now]; + let toInterp = [now - len*ctx.sps*1000, now]; data.timestamp = Math2.upsample(toInterp,len); } else { data.timestamp = Date.now(); @@ -55,12 +57,12 @@ export const accel_gyro = { if(data.ax) { let apass = (timestamp,ax,ay,az) => { - ax = ax*this.accelConstant; //assume raw data - ay = ay*this.accelConstant; - az = az*this.accelConstant; + ax = ax*ctx.accelConstant; //assume raw data + ay = ay*ctx.accelConstant; + az = az*ctx.accelConstant; - const accelXAngle = Math.atan((ay/Math.sqrt(ax*ax)) + az*az*180/Math.PI) + this.accelXError; - const accelYAngle = Math.atan((-ax/Math.sqrt(ay*ay)) + az*az*180/Math.PI) + this.accelYError; + const accelXAngle = Math.atan((ay/Math.sqrt(ax*ax)) + az*az*180/Math.PI) + ctx.accelXError; + const accelYAngle = Math.atan((-ax/Math.sqrt(ay*ay)) + az*az*180/Math.PI) + ctx.accelYError; return { ax, @@ -79,24 +81,24 @@ export const accel_gyro = { } if(data.gx) { let gpass = (timestamp,gx,gy,gz) => { - const elapsed = timestamp - this.lastGyroTime; - this.lastGyroTime = timestamp; + const elapsed = timestamp - ctx.lastGyroTime; + ctx.lastGyroTime = timestamp; - gx = gx*this.gyroConstant+this.gyroXError; //assume raw data - gy = gy*this.gyroConstant+this.gyroYError; - gz = gz*this.gyroConstant+this.gyroZError; + gx = gx*ctx.gyroConstant+ctx.gyroXError; //assume raw data + gy = gy*ctx.gyroConstant+ctx.gyroYError; + gz = gz*ctx.gyroConstant+ctx.gyroZError; - this.gyroXAngle += gx*elapsed; - this.gyroYAngle += gy*elapsed; - this.gyroZAngle += gz*elapsed; + ctx.gyroXAngle += gx*elapsed; + ctx.gyroYAngle += gy*elapsed; + ctx.gyroZAngle += gz*elapsed; return { gx, gy, gz, - roll:this.gyroXAngle, - pitch:this.gyroYAngle, - yaw:this.gyroZAngle + roll:ctx.gyroXAngle, + pitch:ctx.gyroYAngle, + yaw:ctx.gyroZAngle } } @@ -122,26 +124,26 @@ export const accel_gyro = { result.yaw = res.yaw; } else result = res; } - } else if(this.gyroXAngle || this.gyroYAngle || this.gyroZAngle) { //e.g. if accel and gyro are reported separately (looking at you, muse O__O) - result.roll = result.roll*0.04 + this.gyroXAngle*0.96; //complementary filter - result.pitch = result.pitch*0.04 + this.gyroYAngle*0.96; - result.yaw = this.gyroXAngle; + } else if(ctx.gyroXAngle || ctx.gyroYAngle || ctx.gyroZAngle) { //e.g. if accel and gyro are reported separately (looking at you, muse O__O) + result.roll = result.roll*0.04 + ctx.gyroXAngle*0.96; //complementary filter + result.pitch = result.pitch*0.04 + ctx.gyroYAngle*0.96; + result.yaw = ctx.gyroXAngle; } //add estimated position offsets px, py, pz if(result.ax) { const setPositionOffset = (timestamp, result) => { - const elapsed = timestamp - this.lastAccelTime; - this.lastAccelTime = timestamp; + const elapsed = timestamp - ctx.lastAccelTime; + ctx.lastAccelTime = timestamp; - this.px += result.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*0.005555555555); //correct for angle in local coordinate space - this.py += result.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*0.005555555555); - this.pz += result.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*0.005555555555); + ctx.px += result.ax*elapsed*elapsed*Math.cos(ctx.pitch*Math.PI*0.005555555555); //correct for angle in local coordinate space + ctx.py += result.ay*elapsed*elapsed*Math.cos(ctx.roll*Math.PI*0.005555555555); + ctx.pz += result.az*elapsed*elapsed*Math.sin(ctx.pitch*Math.PI*0.005555555555); - result.px = this.px; - result.py = this.py; - result.pz = this.pz; + result.px = ctx.px; + result.py = ctx.py; + result.pz = ctx.pz; return result; @@ -159,6 +161,6 @@ export const accel_gyro = { return result; } -} as GraphNodeProperties +} as SubprocessContextProps //e.g. combine with gps to get local absolute position changes \ No newline at end of file diff --git a/src/extras/algorithms/beat_detect.ts b/src/extras/algorithms/beat_detect.ts index 67280e8b..c01dd62b 100644 --- a/src/extras/algorithms/beat_detect.ts +++ b/src/extras/algorithms/beat_detect.ts @@ -1,41 +1,44 @@ //AlgorithmContext implementation for a basic low-pass peak finding algorithm with some basic error correction import { Math2 } from 'brainsatplay-math'; +import { SubprocessContext, SubprocessContextProps } from '../../services/worker/Subprocess'; import { Biquad } from './util/BiquadFilters'; -import { GraphNodeProperties } from '../../core/Graph'; export const beat_detect = { - refdata:[] as any, - lowpass:undefined, - smoothed:[] as any, - //dsmoothed:[] as any, //slope - timestamp:[] as any, - peaks:[] as any, - valleys:[] as any, - peak_distances:[] as any, - valley_distances:[] as any, - beats:[] as any, - lastPeak:0, - lastValley:0, - sps:100, //set the sample rate, e.g. 100 - maxFreq:4, //the max frequency of peaks we want to detect, we will create a moving average and peak finding interval based on this and the sample rate. //e.g. 4hz for heart rate, or 1/3rd hz for breathing - limit:10, //limit number of last-values stored on the peak/valley/beat arrays to save memory, can just collect externally when a beat is returned - __onconnected:function() { - if(!this.lowpass) { //init lowpass filter with up to date sample rate - let freq = this.maxFreq; + structs:{ //assign key data structures to the context for reference on each pass + refdata:[] as any, + lowpass:undefined, + smoothed:[] as any, + //dsmoothed:[] as any, //slope + timestamp:[] as any, + peaks:[] as any, + valleys:[] as any, + peak_distances:[] as any, + valley_distances:[] as any, + beats:[] as any, + lastPeak:0, + lastValley:0, + sps:100, //set the sample rate, e.g. 100 + maxFreq:4, //the max frequency of peaks we want to detect, we will create a moving average and peak finding interval based on this and the sample rate. //e.g. 4hz for heart rate, or 1/3rd hz for breathing + limit:10, //limit number of last-values stored on the peak/valley/beat arrays to save memory, can just collect externally when a beat is returned + }, + oncreate:(context) => { + if(!context.lowpass) { //init lowpass filter with up to date sample rate + let freq = context.maxFreq; if(!freq) freq = 1; if(freq > 1) freq *= 0.5; //helps smooth more on faster sine waves, for low freqs this starts to be too smooth //lowpass filter constraints - this.lowpass = new Biquad('lowpass', this.maxFreq, this.sps); + context.lowpass = new Biquad('lowpass', context.maxFreq, context.sps); - this.peakFinderWindow = Math.floor(this.sps/this.maxFreq) - if(this.peakFinderWindow%2 === 0) this.peakFinderWindow+=1; - if(this.peakFinderWindow < 5) this.peakFinderWindow = 5; - this.midpoint = Math.round(this.peakFinderWindow*.5); + context.peakFinderWindow = Math.floor(context.sps/context.maxFreq) + if(context.peakFinderWindow%2 === 0) context.peakFinderWindow+=1; + if(context.peakFinderWindow < 5) context.peakFinderWindow = 5; + context.midpoint = Math.round(context.peakFinderWindow*.5); } }, - __operator:function( + ondata:( + context:SubprocessContext, data:{ //general use data key raw?:number|number[], @@ -48,7 +51,7 @@ export const beat_detect = { //used for frequency finding timestamp?:number|number[] } - ){ + )=>{ if(!('red' in data) && !('heg' in data) && !('raw' in data)) return undefined; //invalid data @@ -59,7 +62,7 @@ export const beat_detect = { let now = Date.now(); let len; if(refdata) len = (refdata as number[]).length; - let toInterp = [now - (refdata as number[]).length*this.sps*1000, now]; + let toInterp = [now - (refdata as number[]).length*context.sps*1000, now]; data.timestamp = Math2.upsample(toInterp,(refdata as number[]).length); } else { data.timestamp = Date.now(); @@ -68,28 +71,28 @@ export const beat_detect = { let pass = (amplitude, timestamp) => { if(amplitude) { - this.refdata.push(amplitude); + context.refdata.push(amplitude); } - this.timestamp.push(timestamp); + context.timestamp.push(timestamp); let beat; - if(this.refdata.length > this.peakFinderWindow) { //we only need to store enough data in a buffer to run the algorithm (to limit buffer overflow) - this.refdata.shift(); - this.timestamp.shift(); + if(context.refdata.length > context.peakFinderWindow) { //we only need to store enough data in a buffer to run the algorithm (to limit buffer overflow) + context.refdata.shift(); + context.timestamp.shift(); } - this.smoothed.push( - this.lowpass.applyFilter(this.refdata[this.refdata.length - 1]) + context.smoothed.push( + context.lowpass.applyFilter(context.refdata[context.refdata.length - 1]) ); - if(this.smoothed.length > this.peakFinderWindow) { - this.smoothed.shift(); + if(context.smoothed.length > context.peakFinderWindow) { + context.smoothed.shift(); } - if(this.smoothed.length === this.peakFinderWindow) { + if(context.smoothed.length === context.peakFinderWindow) { // context.dsmoothed.push( // ( context.refdata[context.refdata.length-1] - // context.refdata[context.refdata.length-2] @@ -97,100 +100,99 @@ export const beat_detect = { // ); //context.smoothed.indexOf(Math.max(...context.smoothed)) === context.midpoint - if(Math2.isExtrema(this.smoothed,'valley')) { - this.valleys.push({ - value:this.smoothed[this.smoothed.length - this.midpoint ? this.midpoint : 1], - timestamp:this.timestamp[this.timestamp.length - this.midpoint ? this.midpoint : 1] + if(Math2.isExtrema(context.smoothed,'valley')) { + context.valleys.push({ + value:context.smoothed[context.smoothed.length - context.midpoint ? context.midpoint : 1], + timestamp:context.timestamp[context.timestamp.length - context.midpoint ? context.midpoint : 1] }); - } else if (Math2.isExtrema(this.smoothed,'peak')) { - this.peaks.push({ - value:this.smoothed[this.smoothed.length - this.midpoint ? this.midpoint : 1], - timestamp:this.timestamp[this.timestamp.length - this.midpoint ? this.midpoint : 1] + } else if (Math2.isExtrema(context.smoothed,'peak')) { + context.peaks.push({ + value:context.smoothed[context.smoothed.length - context.midpoint ? context.midpoint : 1], + timestamp:context.timestamp[context.timestamp.length - context.midpoint ? context.midpoint : 1] }); } - if(this.valleys.length > 2 && this.peaks.length > 2) { + if(context.valleys.length > 2 && context.peaks.length > 2) { //if we have 3+ peaks or 3+ valleys in front of the previous peak or valley, we need to shave them off as we are looking for a sine wave (1 peak 1 valley). - if(this.valleys[this.valleys.length-1].timestamp < this.peaks[this.peaks.length - 2].timestamp) - this.peaks.splice(this.peaks.length-1); - if(this.peaks[this.peaks.length-1].timestamp < this.valleys[this.valleys.length - 2].timestamp) - this.valleys.splice(this.valleys.length-1); - - this.valley_distances.push({ - distance:this.valleys[this.valleys.length - 1].timestamp - this.valleys[this.valleys.length - 2].timestamp, - timestamp:this.valleys[this.valleys.length - 1].timestamp, - peak0:this.valleys[this.valleys.length - 1].value, - peak1:this.valleys[this.valleys.length - 2].value + if(context.valleys[context.valleys.length-1].timestamp < context.peaks[context.peaks.length - 2].timestamp) + context.peaks.splice(context.peaks.length-1); + if(context.peaks[context.peaks.length-1].timestamp < context.valleys[context.valleys.length - 2].timestamp) + context.valleys.splice(context.valleys.length-1); + + context.valley_distances.push({ + distance:context.valleys[context.valleys.length - 1].timestamp - context.valleys[context.valleys.length - 2].timestamp, + timestamp:context.valleys[context.valleys.length - 1].timestamp, + peak0:context.valleys[context.valleys.length - 1].value, + peak1:context.valleys[context.valleys.length - 2].value }); - this.peak_distances.push({ - distance:this.peaks[this.peaks.length - 1].timestamp - this.peaks[this.peaks.length - 2].timestamp, - timestamp:this.peaks[this.peaks.length - 1].timestamp, - peak0:this.peaks[this.peaks.length - 1].value, - peak1:this.peaks[this.peaks.length - 2].value + context.peak_distances.push({ + distance:context.peaks[context.peaks.length - 1].timestamp - context.peaks[context.peaks.length - 2].timestamp, + timestamp:context.peaks[context.peaks.length - 1].timestamp, + peak0:context.peaks[context.peaks.length - 1].value, + peak1:context.peaks[context.peaks.length - 2].value }); - if(this.peak_distances.length > 1 && this.valley_distances.length > 1) { - if(this.lastPeak < this.peaks[this.peaks.length-1].timestamp && this.lastValley < this.peaks[this.peaks.length-1].timestamp) { - if(this.valley_distances[this.valley_distances.length -1].timestamp > this.peak_distances[this.peak_distances.length-1].timestamp) { + if(context.peak_distances.length > 1 && context.valley_distances.length > 1) { + if(context.lastPeak < context.peaks[context.peaks.length-1].timestamp && context.lastValley < context.peaks[context.peaks.length-1].timestamp) { + if(context.valley_distances[context.valley_distances.length -1].timestamp > context.peak_distances[context.peak_distances.length-1].timestamp) { let bpm, change = 0; - if(this.beats.length < 1) { - bpm = 60/(0.0005 * (this.peak_distances[this.peak_distances.length-1].distance + - this.valley_distances[this.valley_distances.length-1].distance)); + if(context.beats.length < 1) { + bpm = 60/(0.0005 * (context.peak_distances[context.peak_distances.length-1].distance + + context.valley_distances[context.valley_distances.length-1].distance)); - } else if (this.beats[this.beats.length-1].timestamp !== this.peak_distances[this.peak_distances.length-1].timestamp) { - bpm = 60/(0.0005*(this.peak_distances[this.peak_distances.length-1].dt + this.valley_distances[this.valley_distances.length-1].dt)); - change = Math.abs(bpm - this.beats[this.beats.length - 1].bpm); + } else if (context.beats[context.beats.length-1].timestamp !== context.peak_distances[context.peak_distances.length-1].timestamp) { + bpm = 60/(0.0005*(context.peak_distances[context.peak_distances.length-1].dt + context.valley_distances[context.valley_distances.length-1].dt)); + change = Math.abs(bpm - context.beats[context.beats.length - 1].bpm); } beat = { - timestamp:this.peak_distances[this.peak_distances.length - 1].timestamp, + timestamp:context.peak_distances[context.peak_distances.length - 1].timestamp, change, bpm, - height0:this.peak_distances[this.peak_distances.length-1].peak0 - - this.valley_distances[this.valley_distances.length-1].peak0, - height1:this.peak_distances[this.peak_distances.length-1].peak1 - - this.valley_distances[this.valley_distances.length-1].peak1 - }; + height0:context.peak_distances[context.peak_distances.length-1].peak0 - + context.valley_distances[context.valley_distances.length-1].peak0, + height1:context.peak_distances[context.peak_distances.length-1].peak1 - + context.valley_distances[context.valley_distances.length-1].peak1 + } - this.beats.push(beat); + context.beats.push(beat); - this.lastPeak = this.peaks[this.peaks.length-1].timestamp; - this.lastValley = this.peaks[this.peaks.length-1].timestamp; + context.lastPeak = context.peaks[context.peaks.length-1].timestamp; + context.lastValley = context.peaks[context.peaks.length-1].timestamp; } else { let bpm, change = 0; - if(this.beats.length < 2) { - bpm = 60/(0.0005*(this.peak_distances[this.peak_distances.length-2].distance + this.valley_distances[this.valley_distances.length-2].distance)); //(averaged peak + valley distance (msec)) * msec/sec * 60sec/min - } else if(this.beats[this.beats.length-1].timestamp !== this.peak_distances[this.peak_distances.length-2].timestamp) { - bpm = 60/(0.0005*(this.peak_distances[this.peak_distances.length-2].distance + this.valley_distances[this.valley_distances.length-2].distance)); - change = Math.abs(bpm-this.beats[this.beats.length-2].bpm); + if(context.beats.length < 2) { + bpm = 60/(0.0005*(context.peak_distances[context.peak_distances.length-2].distance + context.valley_distances[context.valley_distances.length-2].distance)); //(averaged peak + valley distance (msec)) * msec/sec * 60sec/min + } else if(context.beats[context.beats.length-1].timestamp !== context.peak_distances[context.peak_distances.length-2].timestamp) { + bpm = 60/(0.0005*(context.peak_distances[context.peak_distances.length-2].distance + context.valley_distances[context.valley_distances.length-2].distance)); + change = Math.abs(bpm-context.beats[context.beats.length-2].bpm); } beat = { - timestamp:this.peak_distances[this.peak_distances.length-2].timestamp, + timestamp:context.peak_distances[context.peak_distances.length-2].timestamp, change, bpm, - height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0, - height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1 - }; - if(Array.isArray(beat.timestamp)) beat.timestamp = beat.timestamp[0]; //some kind of bug + height0:context.peak_distances[context.peak_distances.length-2].peak0-context.valley_distances[context.valley_distances.length-2].peak0, + height1:context.peak_distances[context.peak_distances.length-2].peak1-context.valley_distances[context.valley_distances.length-2].peak1 + } - this.beats.push(beat); + context.beats.push(beat); - this.lastPeak = this.peaks[this.peaks.length-1].timestamp; - this.lastValley = this.peaks[this.peaks.length-1].timestamp; + context.lastPeak = context.peaks[context.peaks.length-1].timestamp; + context.lastValley = context.peaks[context.peaks.length-1].timestamp; } } } //limits memory usage - if(this.peaks.length > this.limit) { this.peaks.shift(); } - if(this.valleys.length > this.limit) { this.valleys.shift(); } - if(this.peak_distances.length > this.limit) { this.peak_distances.shift(); } - if(this.valley_distances.length > this.limit) { this.valley_distances.shift(); } - if(this.beats.length > this.limit) { this.beats.shift(); } + if(context.peaks.length > context.limit) { context.peaks.shift(); } + if(context.valleys.length > context.limit) { context.valleys.shift(); } + if(context.peak_distances.length > context.limit) { context.peak_distances.shift(); } + if(context.valley_distances.length > context.limit) { context.valley_distances.shift(); } + if(context.beats.length > context.limit) { context.beats.shift(); } } } @@ -198,35 +200,26 @@ export const beat_detect = { return beat; } - //console.log(context); + //console.log(context); console.log(data); if(data.red) { if(('ir' in data) && !Array.isArray(data.red)) return pass((data.red as number)+(data.ir as number),data.timestamp); - + let result; - if(data.ir) result = (data.red as number[]).map((v,i) => { - return pass(v+(data as any).ir[i],(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - else result = (data.red as number[]).map((v,i) => { - return pass(v,(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - - return result; //will return an array, defined results will be + if(data.ir) (data.red as number[]).map((v,i) => { return pass(v+(data as any).ir[i],(data.timestamp as number[])[i]); }); + else (data.red as number[]).map((v,i) => { return pass(v,(data.timestamp as number[])[i]); }); + return result; } else if (data.raw) { if(!Array.isArray(data.raw)) return pass(data.raw,data.timestamp); - let result = data.raw.map((v,i) => { - return pass(v,(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - return result; //will return an array + let result = data.raw.map((v,i) => { return pass(v,(data.timestamp as number[])[i]); }); + return result; } else if (Array.isArray(data.heg)) { if(!Array.isArray(data.heg)) return pass(data.heg,data.timestamp); - let result = data.heg.map((v,i) => { - return pass(v,(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - return result; //will return an array + let result = data.heg.map((v,i) => { return pass(v,(data.timestamp as number[])[i]); }); + return result; } //returns a beat when one is detected with the latest data passed in, else returns undefined } -} as GraphNodeProperties; \ No newline at end of file +} as SubprocessContextProps; \ No newline at end of file diff --git a/src/extras/algorithms/blink.ts b/src/extras/algorithms/blink.ts index bb4d55fc..901e53d5 100644 --- a/src/extras/algorithms/blink.ts +++ b/src/extras/algorithms/blink.ts @@ -1,23 +1,25 @@ -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; import { Biquad } from './util/BiquadFilters'; import { Math2 } from 'brainsatplay-math'; export const blink_detect = { - sps:250, - intervals:{}, - watch:['0'], - tolerance:0.2, //e.g. mV - __onconnected:(node) => { - node.watch.forEach((ch) => node.intervals[ch] = { - lowpass:new Biquad('lowpass',20,node.sps), + structs:{ + sps:250, + intervals:{}, + watch:['0'], + tolerance:0.2 //absolute tolerance e.g. 0.2mV + }, + oncreate:(ctx) => { + ctx.watch.forEach((ch) => ctx.intervals[ch] = { + lowpass:new Biquad('lowpass',20,ctx.sps), filtered:[] as number[], averaged:[] as number[] }) }, - __operator:function(data:{ + ondata:(ctx,data:{ [key:string]:number|number[] - }) { + }) => { let checkCt = 5; let averageCt = 50; @@ -26,25 +28,25 @@ export const blink_detect = { let pass = (key,n) => { - let next = this.intervals[key].lowpass.applyFilter(n) - this.intervals[key].filtered.push(next); - this.intervals[key].averaged.push(next); - if(this.intervals[key].filtered.length > checkCt) { - if(this.intervals[key].averaged.length > averageCt) { - this.intervals[key].averaged.splice(0,checkCt); - let mean = Math2.mean(this.intervals[key].averaged); - if(Math.abs(Math.min(...this.intervals[key].filtered)) > Math.abs(mean) + this.tolerance) { - this.intervals[key].filtered.length = 0; //reset + let next = ctx.intervals[key].lowpass.applyFilter(n) + ctx.intervals[key].filtered.push(next); + ctx.intervals[key].averaged.push(next); + if(ctx.intervals[key].filtered.length > checkCt) { + if(ctx.intervals[key].averaged.length > averageCt) { + ctx.intervals[key].averaged.splice(0,checkCt); + let mean = Math2.mean(ctx.intervals[key].averaged); + if(Math.abs(Math.min(...ctx.intervals[key].filtered)) > Math.abs(mean) + ctx.tolerance) { + ctx.intervals[key].filtered.length = 0; //reset passed = true; found[key] = true; } } else - this.intervals[key].filtered.shift(); + ctx.intervals[key].filtered.shift(); } } - for(const key in this.intervals) { + for(const key in ctx.intervals) { if(data[key]) { if(Array.isArray(data[key])) { (data[key] as any).forEach((n) => { @@ -57,4 +59,4 @@ export const blink_detect = { if(passed) return found; } -} as GraphNodeProperties \ No newline at end of file +} as SubprocessContextProps \ No newline at end of file diff --git a/src/extras/algorithms/buffering.ts b/src/extras/algorithms/buffering.ts index 504944a1..74514fbf 100644 --- a/src/extras/algorithms/buffering.ts +++ b/src/extras/algorithms/buffering.ts @@ -1,28 +1,29 @@ //we need to buffer before doing bulk blocking operations on separate threads sometimes (ffts in our case) so we are splitting this into 2 algos -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; import { ByteParser } from './util/ByteParser'; -export const circularBuffer2d:GraphNodeProperties = { - bufferSize:250, //e.g. sps * nsec of data to buffer - watch:['0','1','2','3'], - data:{}, - blocking:false, - - __onconnected:function (node) { - for(const key in node.watch) { - node.data[key] = new Array(node.bufferSize).fill(0); +export const circularBuffer2d:SubprocessContextProps = { + structs:{ + bufferSize:250, //e.g. sps * nsec of data to buffer + watch:['0','1','2','3'], + data:{}, + blocking:false + }, + oncreate:(ctx) => { + for(const key in ctx.watch) { + ctx.data[key] = new Array(ctx.bufferSize).fill(0); } }, - __operator:function (data) { + ondata:(ctx,data) => { let buffer2d = [] as number[][]; - this.watch.forEach((key) => { + ctx.watch.forEach((key) => { if(data[key]) { - ByteParser.circularBuffer(this.data[key], data[key]) - buffer2d.push(this.data[key]) + ByteParser.circularBuffer(ctx.data[key], data[key]) + buffer2d.push(ctx.data[key]) } }); diff --git a/src/extras/algorithms/coherence.ts b/src/extras/algorithms/coherence.ts index dfb96641..8308fd60 100644 --- a/src/extras/algorithms/coherence.ts +++ b/src/extras/algorithms/coherence.ts @@ -1,46 +1,47 @@ - -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; import { GPUService } from '../gpu/GPU.service'; if(!globalThis.gpu) globalThis.gpu = new GPUService(); // contains macros for persistent kernels (programs) on the gpu using an instance of gpujs, using the same instance lets us reuse the same kernel instances -export const coherence:GraphNodeProperties = { - sps:250, //sample rate of data - nSec:1, //number of seconds of data to buffer - freqStart:0, - freqEnd:125, //default full nyquist range - tags:['0','1','2','3'], - coherenceTags:[] as any[], - __onconnected:function (node) { - node.tags.forEach((tag,i) => { - if(i !== node.tags.length-1){ - for(let j = i+1; j < node.tags.length; j++) { - node.coherenceTags.push(node.tags[i]+'_'+node.tags[j]); +export const coherence:SubprocessContextProps = { + structs:{ + sps:250, //sample rate of data + nSec:1, //number of seconds of data to buffer + freqStart:0, + freqEnd:125, //default full nyquist range + tags:['0','1','2','3'], + coherenceTags:[] as any[] + }, + oncreate:(ctx) => { + ctx.tags.forEach((tag,i) => { + if(i !== ctx.tags.length-1){ + for(let j = i+1; j < ctx.tags.length; j++) { + ctx.coherenceTags.push(ctx.tags[i]+'_'+ctx.tags[j]); } } }) }, - __operator:function(arraybuffer) { + ondata:(ctx,arraybuffer) => { let ts = Date.now(); //console.log('buffer', arraybuffer) let results = (globalThis.gpu as GPUService).coherence( arraybuffer, - this.nSec, - this.freqStart, - this.freqEnd + ctx.nSec, + ctx.freqStart, + ctx.freqEnd ) as [number[],number[][],number[][]] //frequency (x), power spectrums (y), coherence per channel (in order of channels) let dft = {}; - this.tags.forEach((tag,i) => { + ctx.tags.forEach((tag,i) => { dft[tag] = results[1][i]; }); let coherence = {}; - this.coherenceTags.forEach((tag,i) => { + ctx.coherenceTags.forEach((tag,i) => { coherence[tag] = results[2][i]; }); diff --git a/src/extras/algorithms/dft.ts b/src/extras/algorithms/dft.ts index f9356062..5796136f 100644 --- a/src/extras/algorithms/dft.ts +++ b/src/extras/algorithms/dft.ts @@ -1,30 +1,33 @@ -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; import { GPUService } from '../gpu/GPU.service'; if(!globalThis.gpu) globalThis.gpu = new GPUService(); // contains macros for persistent kernels (programs) on the gpu using an instance of gpujs, using the same instance lets us reuse the same kernel instances -export const dft:GraphNodeProperties = { - sps:250, //sample rate of data - nSec:1, //number of seconds of data to buffer - freqStart:0, - freqEnd:125, //default full nyquist range - watch:['0','1','2','3'], - blocking:false, - //__onconnected:(ctx) => {}, - __operator:function (arraybuffer) { +export const dft:SubprocessContextProps = { + structs:{ + sps:250, //sample rate of data + nSec:1, //number of seconds of data to buffer + freqStart:0, + freqEnd:125, //default full nyquist range + watch:['0','1','2','3'], + blocking:false + }, + oncreate:(ctx) => { + }, + ondata:(ctx,arraybuffer) => { //console.log('buffer', arraybuffer) let results = (globalThis.gpu as GPUService).multidftbandpass( arraybuffer, - this.nSec, - this.freqStart, - this.freqEnd, + ctx.nSec, + ctx.freqStart, + ctx.freqEnd, 1 ) as [number[],number[][],number[][]] //frequency (x), power spectrums (y), coherence per channel (in order of channels) let dft = {}; - this.watch.forEach((tag,i) => { + ctx.watch.forEach((tag,i) => { dft[tag] = results[1][i]; }); diff --git a/src/extras/algorithms/index.ts b/src/extras/algorithms/index.ts index 89dc133f..197080c9 100644 --- a/src/extras/algorithms/index.ts +++ b/src/extras/algorithms/index.ts @@ -1,13 +1,12 @@ - +import { algorithms, SubprocessContextProps } from "../../services/worker/Subprocess"; import { accel_gyro } from "./accel_gyro"; import { beat_detect } from "./beat_detect"; import { blink_detect } from './blink'; import { rms } from './rms'; import { circularBuffer2d } from './buffering'; -import { GraphNodeProperties } from "../../core/Graph"; //data in, interpretation out (with unique key:value pairs) -const algorithms = { +Object.assign(algorithms,{ beat_detect, //beat detection, set sps and maxFreq detection (for low passing) accel_gyro, //get absolute angle and position change from starting point (need magnetometer for global position, the gyro is relative) heartrate:beat_detect, //alias @@ -16,9 +15,10 @@ const algorithms = { rms, circularBuffer2d } as { - [key:string]:GraphNodeProperties -}; + [key:string]:SubprocessContextProps +}); -algorithms['breath'].maxFreq = 0.2; //another quick preset +algorithms['breath'].structs = JSON.parse( JSON.stringify( algorithms['breath'].structs )); +(algorithms['breath'].structs as any).maxFreq = 0.2; //another quick preset export { algorithms }; \ No newline at end of file diff --git a/src/extras/algorithms/rms.ts b/src/extras/algorithms/rms.ts index bbe26d21..1c64ddc5 100644 --- a/src/extras/algorithms/rms.ts +++ b/src/extras/algorithms/rms.ts @@ -1,43 +1,45 @@ //root mean square doer thinger -import { GraphNodeProperties } from "../../core/Graph"; +import { SubprocessContextProps } from "../../services/worker/Subprocess"; import { ByteParser } from "./util/ByteParser"; -export const rms:GraphNodeProperties = { - sps:250, //sample rate of data - nSec:1, //number of seconds of data to buffer - watch:['0','1','2','3'], - data:{}, - rms:{}, - //__onconnected:(node) => { }, - __operator:function (data) { - - this.watch.forEach((key) => { +export const rms:SubprocessContextProps = { + structs:{ + sps:250, //sample rate of data + nSec:1, //number of seconds of data to buffer + watch:['0','1','2','3'], + data:{}, + rms:{} + }, + //oncreate:(ctx) => { }, + ondata:(ctx,data) => { + + ctx.watch.forEach((key) => { if(data[key]) { - if(!this.data[key]) { + if(!ctx.data[key]) { if(Array.isArray(data[key])) { - this.data[key] = new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0]); - } else this.data[key] = new Array(Math.floor(this.sps*this.nSec)).fill(data[key]); + ctx.data[key] = new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key][0]); + } else ctx.data[key] = new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key]); } - ByteParser.circularBuffer(this.data[key],data[key]); + ByteParser.circularBuffer(ctx.data[key],data[key]); } }); if(data.timestamp) { if(Array.isArray(data.timestamp)) { - this.rms.timestamp = data.timestamp[data.timestamp.length - 1]; - } else this.rms.timestamp = data.timestamp; - } else this.rms.timestamp = Date.now(); + ctx.rms.timestamp = data.timestamp[data.timestamp.length - 1]; + } else ctx.rms.timestamp = data.timestamp; + } else ctx.rms.timestamp = Date.now(); //console.log(ctx.rms,ctx.data); return new Promise(async res => { - await Promise.all(this.watch.map(async (key) => { - if(this.data[key]) this.rms[key] = Math.sqrt(Math.abs((this.data[key] as number[]).reduce((p,v,i) => p + v*v )/this.data[key].length)); //root mean square sum - else delete this.rms[key]; + await Promise.all(ctx.watch.map(async (key) => { + if(ctx.data[key]) ctx.rms[key] = Math.sqrt(Math.abs((ctx.data[key] as number[]).reduce((p,v,i) => p + v*v )/ctx.data[key].length)); //root mean square sum + else delete ctx.rms[key]; })) - res(this.rms); + res(ctx.rms); }) } diff --git a/src/extras/build/gpu/index.gpu.services.ts b/src/extras/build/gpu/index.gpu.services.ts new file mode 100644 index 00000000..829ec8e2 --- /dev/null +++ b/src/extras/build/gpu/index.gpu.services.ts @@ -0,0 +1,4 @@ +//for all the extra services we want to export but are too bulky for the core + +export * from '../../gpu/GPU.service' //~500kb +export { gpualgorithms } from '../../algorithms/index.gpu'; //modified algorithms object with presets \ No newline at end of file diff --git a/src/extras/package-lock.json b/src/extras/build/gpu/package-lock.json similarity index 55% rename from src/extras/package-lock.json rename to src/extras/build/gpu/package-lock.json index a36fd11d..75eec857 100644 --- a/src/extras/package-lock.json +++ b/src/extras/build/gpu/package-lock.json @@ -1,44 +1,28 @@ { - "name": "graphscript-services", - "version": "0.3.1", + "name": "graphscript-services.gpu", + "version": "0.2.27", "lockfileVersion": 2, "requires": true, "packages": { "": { - "name": "graphscript-services", - "version": "0.3.1", - "license": "LGPL-3.0-or-later", + "name": "graphscript-services.gpu", + "version": "0.2.27", + "license": "AGPL-3.0-or-later", "dependencies": { - "brainsatplay-math": "~0.1.0", - "browserfs": "~1.4.3", - "gpujsutils": "~1.0.15", - "web-worker": "~1.2.0", - "webgl-plot-utils": "~0.4.2" + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.3", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" }, "devDependencies": { "@types/node": "~18.7.15" } }, - "../../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.181", - "extraneous": true, - "license": "LGPL-3.0-or-later", - "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.14.49", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.6.4" - } - }, "node_modules/@types/node": { - "version": "18.7.15", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.15.tgz", - "integrity": "sha512-XnjpaI8Bgc3eBag2Aw4t2Uj/49lLBSStHWfqKvIuXD7FIrZyMLWp8KuAFHAqxMZYTF9l08N1ctUn9YNybZJVmQ==", + "version": "18.7.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.23.tgz", + "integrity": "sha512-DWNcCHolDq0ZKGizjx2DZjR/PqsYwAcYUJmfMWqtVU2MBMG5Mo+xFZrhGId5r/O5HOuMPyQEcM6KUBp5lBZZBg==", "dev": true }, "node_modules/async": { @@ -50,9 +34,9 @@ } }, "node_modules/brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" }, "node_modules/browserfs": { "version": "1.4.3", @@ -69,10 +53,15 @@ "node": ">= 0.10" } }, + "node_modules/bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, "node_modules/gpujsutils": { - "version": "1.0.15", - "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.15.tgz", - "integrity": "sha512-V6AevSRCmAPm7+Y8Wl+aqP1Q4+6iJQbFDImsdQkX082ZWgBvN/ALK8uY8bhHqceWUzgsW6aVDZG/pdrDaPKHlA==" + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" }, "node_modules/lodash": { "version": "4.17.21", @@ -84,30 +73,25 @@ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" }, - "node_modules/web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - }, "node_modules/webgl-plot": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.1.tgz", - "integrity": "sha512-CSLgEj+Xerd+SZoBpIWMiHk/AhoPb8ZokqmTGPaGOra0++9e5LsiAWIuUWGunOHjllvKAhSKPg7yG4+kiHifew==" + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" }, "node_modules/webgl-plot-utils": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.4.2.tgz", - "integrity": "sha512-mS4vI7O7lPNZLvd3iLIpaYAsD+kr//zvfTvGsOYRTJ4JZ/b6/ybxMELFDbtw0j1w3UWInU872ogUEnniTpGDzQ==", + "version": "0.3.15", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", + "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", "dependencies": { - "webgl-plot": "~0.7.1" + "webgl-plot": "~0.7.0" } } }, "dependencies": { "@types/node": { - "version": "18.7.15", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.15.tgz", - "integrity": "sha512-XnjpaI8Bgc3eBag2Aw4t2Uj/49lLBSStHWfqKvIuXD7FIrZyMLWp8KuAFHAqxMZYTF9l08N1ctUn9YNybZJVmQ==", + "version": "18.7.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.23.tgz", + "integrity": "sha512-DWNcCHolDq0ZKGizjx2DZjR/PqsYwAcYUJmfMWqtVU2MBMG5Mo+xFZrhGId5r/O5HOuMPyQEcM6KUBp5lBZZBg==", "dev": true }, "async": { @@ -119,9 +103,9 @@ } }, "brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" }, "browserfs": { "version": "1.4.3", @@ -132,10 +116,15 @@ "pako": "^1.0.4" } }, + "bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, "gpujsutils": { - "version": "1.0.15", - "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.15.tgz", - "integrity": "sha512-V6AevSRCmAPm7+Y8Wl+aqP1Q4+6iJQbFDImsdQkX082ZWgBvN/ALK8uY8bhHqceWUzgsW6aVDZG/pdrDaPKHlA==" + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" }, "lodash": { "version": "4.17.21", @@ -147,22 +136,17 @@ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" }, - "web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - }, "webgl-plot": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.1.tgz", - "integrity": "sha512-CSLgEj+Xerd+SZoBpIWMiHk/AhoPb8ZokqmTGPaGOra0++9e5LsiAWIuUWGunOHjllvKAhSKPg7yG4+kiHifew==" + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" }, "webgl-plot-utils": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.4.2.tgz", - "integrity": "sha512-mS4vI7O7lPNZLvd3iLIpaYAsD+kr//zvfTvGsOYRTJ4JZ/b6/ybxMELFDbtw0j1w3UWInU872ogUEnniTpGDzQ==", + "version": "0.3.15", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", + "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", "requires": { - "webgl-plot": "~0.7.1" + "webgl-plot": "~0.7.0" } } } diff --git a/src/extras/___package.json b/src/extras/build/gpu/package.json similarity index 77% rename from src/extras/___package.json rename to src/extras/build/gpu/package.json index 1d05fe29..c879eade 100644 --- a/src/extras/___package.json +++ b/src/extras/build/gpu/package.json @@ -1,12 +1,13 @@ { "name": "graphscript-services.gpu", - "version": "0.3.2", + "version": "0.2.27", "description": "Extra services for graphscript.", "main": "dist/index.gpu.services.js", "module": "dist/index.gpu.services.esm.js", - "types": "dist/index.gpu.services.d.ts", + "types": "dist/extras/index.gpu.services.d.ts", + "type": "module", "scripts": { - "start": "tinybuild path=tinybuild.config.js && tinybuild path=tinybuild.gpu.config.js && tinybuild path=tinybuild.storage.config.js", + "start": "tinybuild", "build": "tinybuild build", "serve": "tinybuild serve", "init": "node tinybuild/init.js", @@ -21,12 +22,13 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "^0.0.25", "browserfs": "^1.4.3", - "webgl-plot-utils":"~0.4.2", - "gpujsutils":"~1.0.15" + "bson-objectid": "~2.0.3", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" }, "nodemonConfig": { "env": { diff --git a/src/extras/tinybuild.gpu.config.js b/src/extras/build/gpu/tinybuild.config.js similarity index 98% rename from src/extras/tinybuild.gpu.config.js rename to src/extras/build/gpu/tinybuild.config.js index fd0a0e63..ebca90fd 100644 --- a/src/extras/tinybuild.gpu.config.js +++ b/src/extras/build/gpu/tinybuild.config.js @@ -37,4 +37,4 @@ const config = { // } } -module.exports = config; //es5 //export default config; // \ No newline at end of file +export default config; // \ No newline at end of file diff --git a/src/extras/build/services/index.services.ts b/src/extras/build/services/index.services.ts new file mode 100644 index 00000000..a5d83794 --- /dev/null +++ b/src/extras/build/services/index.services.ts @@ -0,0 +1,16 @@ +//for all the extra services we want to export but are too bulky for the core + +//e.g. babylonjs service, threejs service + +export * from '../../struct/Struct.frontend' +export * from '../../struct/Struct.backend' + +export * from '../../ecs/ECS.systems' + +export * from '../../webgl-plot/webglplot.routes' + +import gsworker from '../../../services/worker/Worker' //compiles the worker in the dist + +export { algorithms } from '../../algorithms/index'; //modified algorithms object with presets + +export { gsworker } //available as a dataurl \ No newline at end of file diff --git a/examples/editing/package.json b/src/extras/build/services/package.json similarity index 77% rename from examples/editing/package.json rename to src/extras/build/services/package.json index fc7fc57e..97bc758e 100644 --- a/examples/editing/package.json +++ b/src/extras/build/services/package.json @@ -1,8 +1,10 @@ { - "name": "tinybuildapp5363", + "name": "graphscript-services", "version": "0.0.0", "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", + "main": "dist/index.services.js", + "module": "dist/index.services.esm.js", + "types": "dist/index.services.d.ts", "type": "module", "scripts": { "start": "tinybuild", @@ -20,10 +22,11 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "litegraph.js": "^0.7.14", - "web-worker": "^1.2.0" + "brainsatplay-math": "^0.0.25", + "bson-objectid": "^2.0.4", + "webgl-plot-utils": "^0.3.15" }, "nodemonConfig": { "env": { diff --git a/src/extras/tinybuild.config.js b/src/extras/build/services/tinybuild.config.js similarity index 94% rename from src/extras/tinybuild.config.js rename to src/extras/build/services/tinybuild.config.js index 73cadfe9..3ae29451 100644 --- a/src/extras/tinybuild.config.js +++ b/src/extras/build/services/tinybuild.config.js @@ -9,7 +9,7 @@ const config = { bundleBrowser: true, //create plain js build? Can include globals and init scripts bundleESM: true, //create esm module js files bundleTypes: true, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: true, //create node platform plain js build, specify platform:'node' to do the rest of the files + bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. //minify: false, minifyWhitespace:true, @@ -37,4 +37,4 @@ const config = { // } } -module.exports = config; //es5 //export default config; // \ No newline at end of file +export default config; // \ No newline at end of file diff --git a/src/extras/build/storage/index.storage.services.ts b/src/extras/build/storage/index.storage.services.ts new file mode 100644 index 00000000..adb8d736 --- /dev/null +++ b/src/extras/build/storage/index.storage.services.ts @@ -0,0 +1,5 @@ +//for all the extra services we want to export but are too bulky for the core + +export * from '../../storage/csv' +export * from '../../storage/BFSUtils' +export * from '../../storage/BFS_CSV' diff --git a/src/extras/build/storage/package-lock.json b/src/extras/build/storage/package-lock.json new file mode 100644 index 00000000..c3b9913c --- /dev/null +++ b/src/extras/build/storage/package-lock.json @@ -0,0 +1,153 @@ +{ + "name": "graphscript-services.storage", + "version": "0.2.27", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "graphscript-services.storage", + "version": "0.2.27", + "license": "AGPL-3.0-or-later", + "dependencies": { + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" + }, + "devDependencies": { + "@types/node": "~18.7.15" + } + }, + "node_modules/@types/node": { + "version": "18.7.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.23.tgz", + "integrity": "sha512-DWNcCHolDq0ZKGizjx2DZjR/PqsYwAcYUJmfMWqtVU2MBMG5Mo+xFZrhGId5r/O5HOuMPyQEcM6KUBp5lBZZBg==", + "dev": true + }, + "node_modules/async": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", + "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/brainsatplay-math": { + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + }, + "node_modules/browserfs": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/browserfs/-/browserfs-1.4.3.tgz", + "integrity": "sha512-tz8HClVrzTJshcyIu8frE15cjqjcBIu15Bezxsvl/i+6f59iNCN3kznlWjz0FEb3DlnDx3gW5szxeT6D1x0s0w==", + "dependencies": { + "async": "^2.1.4", + "pako": "^1.0.4" + }, + "bin": { + "make_xhrfs_index": "dist/scripts/make_xhrfs_index.js" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, + "node_modules/gpujsutils": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" + }, + "node_modules/webgl-plot": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" + }, + "node_modules/webgl-plot-utils": { + "version": "0.3.15", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", + "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", + "dependencies": { + "webgl-plot": "~0.7.0" + } + } + }, + "dependencies": { + "@types/node": { + "version": "18.7.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.23.tgz", + "integrity": "sha512-DWNcCHolDq0ZKGizjx2DZjR/PqsYwAcYUJmfMWqtVU2MBMG5Mo+xFZrhGId5r/O5HOuMPyQEcM6KUBp5lBZZBg==", + "dev": true + }, + "async": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", + "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", + "requires": { + "lodash": "^4.17.14" + } + }, + "brainsatplay-math": { + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + }, + "browserfs": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/browserfs/-/browserfs-1.4.3.tgz", + "integrity": "sha512-tz8HClVrzTJshcyIu8frE15cjqjcBIu15Bezxsvl/i+6f59iNCN3kznlWjz0FEb3DlnDx3gW5szxeT6D1x0s0w==", + "requires": { + "async": "^2.1.4", + "pako": "^1.0.4" + } + }, + "bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, + "gpujsutils": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" + }, + "webgl-plot": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" + }, + "webgl-plot-utils": { + "version": "0.3.15", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", + "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", + "requires": { + "webgl-plot": "~0.7.0" + } + } + } +} diff --git a/src/extras/__package.json b/src/extras/build/storage/package.json similarity index 82% rename from src/extras/__package.json rename to src/extras/build/storage/package.json index 32f52858..b1911a49 100644 --- a/src/extras/__package.json +++ b/src/extras/build/storage/package.json @@ -1,12 +1,13 @@ { "name": "graphscript-services.storage", - "version": "0.3.2", + "version": "0.2.27", "description": "Extra services for graphscript.", "main": "dist/index.storage.services.js", "module": "dist/index.storage.services.esm.js", "types": "dist/index.storage.services.d.ts", + "type": "module", "scripts": { - "start": "tinybuild path=tinybuild.config.js && tinybuild path=tinybuild.gpu.config.js && tinybuild path=tinybuild.storage.config.js", + "start": "tinybuild", "build": "tinybuild build", "serve": "tinybuild serve", "init": "node tinybuild/init.js", @@ -21,11 +22,13 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", - "webgl-plot-utils":"~0.4.2" + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "webgl-plot-utils": "~0.3.15" }, "nodemonConfig": { "env": { diff --git a/src/extras/tinybuild.storage.config.js b/src/extras/build/storage/tinybuild.config.js similarity index 98% rename from src/extras/tinybuild.storage.config.js rename to src/extras/build/storage/tinybuild.config.js index 87424eb8..27b8de13 100644 --- a/src/extras/tinybuild.storage.config.js +++ b/src/extras/build/storage/tinybuild.config.js @@ -37,4 +37,4 @@ const config = { // } } -module.exports = config; //es5 //export default config; // \ No newline at end of file +export default config; // \ No newline at end of file diff --git a/src/extras/dist/Worker.js b/src/extras/dist/Worker.js deleted file mode 100644 index 2de70544..00000000 --- a/src/extras/dist/Worker.js +++ /dev/null @@ -1 +0,0 @@ -(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browser=__commonJS({"../../node_modules/web-worker/cjs/browser.js"(exports,module){module.exports=Worker}});var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers["__state__"])this.triggers["__state__"].forEach(fn=>{fn(updateObj)});return this.data};this.setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};this.triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>obj.onchange(value);this.triggers[key].forEach(fn)}};this.subscribeState=onchange=>{return this.subscribeEvent("__state__",onchange)};this.unsubscribeState=sub=>{return this.unsubscribeEvent("__state__",sub)};this.subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let biggest=0;for(const trigger of this.triggers[key]){if(trigger.sub>biggest)biggest=trigger.sub}let l=biggest+1;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub){delete this.triggers[key];delete this.data[key]}else{let sub2=void 0;let obj=triggers.find((o,i2)=>{if(o.sub===sub2){sub2=i2;return true}});if(obj)triggers.splice(sub2,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed)};this.getEvent=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};this.getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};this.__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state};let setProps2=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys2=Object.getOwnPropertyNames(properties);for(const key of keys2){this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps2();setNode();setParent();assignProps();bindCallbacks();setOp()}};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))subscribeToGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}};this.__unsubscribe=(sub,key,unsubInput)=>{if(key)return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub);else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph)}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;if(typeof props2[k]==="function"&&k!=="__operator"){let fn=props2[k].bind(this);props2[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}}else{let get,set;if(this.__props?.[k]){get=()=>{return this.__props[k]};set=v=>{this.__props[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)}}else{localState[k]=props2[k];get=()=>{return localState[k]};set=v=>{localState[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)}}const descriptor={get,set,enumerable:true,configurable:true};Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};this.__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){if(typeof obj[k]==="function"){this[k]=(...args)=>{return obj[k](...args)}}else{const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}}};this.__setProperties(properties,parent,graph)}__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};this.init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};this.load=roots=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(target)Object.assign(target,obj);else target=Object.assign({},obj);recursivelyAssignChildren(target,obj,true,false)}if(obj.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){target[key]=Object.assign({},obj[key]);if(obj[key].__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};this.add=(properties,parent)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys2=Object.getOwnPropertyNames(properties);let cpy={};for(const key of keys2){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=properties;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent,listeners={},origin)=>{let keys2=Object.getOwnPropertyNames(origin);for(const key of keys2){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let keys3=Object.getOwnPropertyNames(p);let cpy={};for(const key2 of keys3){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(!(parent instanceof Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else{this.set(node.__node.tag,node);this.runLoaders(node,parent,t[key],key);t[key]=node;this.__node.roots[node.__node.tag]=p;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}console.log(key,t[key].__listeners);t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined")listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k].__args,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if("__callback"in listeners[key][k]){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState);node.__listeners[key].sub=void 0}}}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};this.subscribe=(nodeEvent,onEvent,args,key,subInput,target,bound)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}let sub;if(target instanceof GraphNode)target=target.__node.tag;if(typeof onEvent==="string"){let key2=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){let n=this.get(onEvent2.substring(0,onEvent2.lastIndexOf(".")));let key3=onEvent2.substring(onEvent2.lastIndexOf(".")+1);if(typeof n[key3]==="function"){if(n[key3]instanceof GraphNode)onEvent2=n[key3];else onEvent2=function(...inp){return n[key3](...inp)}}else{onEvent2=function(inp){n[key3]=inp;return n[key3]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){onEvent=function(...inp){return node[key2](...inp)}}else if(node[key2]){if(node[key2]instanceof GraphNode)onEvent=node[key2];else onEvent=function(inp){node[key2]=inp;return node[key2]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}if((typeof onEvent==="function"||onEvent instanceof GraphNode)&&args){if(onEvent instanceof GraphNode&&onEvent.__operator)onEvent=function(inp){return onEvent.__operator(inp)};onEvent=wrapArgs(onEvent,args,this)}if(nd instanceof GraphNode){sub=nd.__subscribe(onEvent,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof nodeEvent==="string"){if(this.get(nodeEvent)){if(onEvent instanceof GraphNode&&onEvent.__operator){sub=this.get(nodeEvent).__subscribe(onEvent.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(nodeEvent).__unsubscribe(sub)};onEvent.__addOndisconnected(ondelete)}else if(typeof onEvent==="function"||typeof onEvent==="string"){sub=this.get(nodeEvent).__subscribe(onEvent,key,subInput,target,bound);this.__node.state.getEvent(this.get(nodeEvent).__node.unique,sub).source=nodeEvent}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function")sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"){if(target[key]?.constructor.name==="Object")recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);let fn=function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)};props.forEach(fn)}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return isFunction(thing)==="class"}function isFunction(x2){const res=typeof x2==="function"?x2.prototype?Object.getOwnPropertyDescriptor(x2,"prototype")?.writable?"function":"class":x2.constructor.name==="AsyncFunction"?"async":"arrow":"";return res}var wrapArgs=(callback,argOrder,graph)=>{let args=[];let getCallbackFromString=a=>{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};let forArg=(a,i2)=>{if(a==="__output"){args[i2]=inp=>{return inp}}else if(typeof a==="string"){args[i2]=getCallbackFromString(a)}else if(typeof a==="function"){let fn2=a;args[i2]=(...inp)=>{return fn2(...inp)}}else if(typeof a==="object"&&a.__input){let recursivelyCreateCallback=function(c){let input=c.__input;if(typeof c.__input==="string"){input=getCallbackFromString(c.__input)}if(c.__args){input=wrapArgs(input,c.__args,graph)}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output=getCallbackFromString(output)}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output==="function"){let fn2=input;input=(...inp)=>{return output(fn2(...inp))}}}return input};args[i2]=recursivelyCreateCallback(a)}else{let arg=a;args[i2]=()=>{return arg}}};argOrder.forEach(forArg);if(typeof callback==="string")callback=getCallbackFromString(callback);let fn=callback;callback=function(...inp){let mapArg=arg=>{return arg(...inp)};return fn(...args.map(mapArg))};return callback};var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator&&!node.__node.looperSet){if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i2=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i2,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){node.__node.looperSet=true;let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.load(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt)}rt.worker=worker;if(!rt.worker.__ondisconnected){let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,void 0,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent,graph,roots)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent?.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&roots[rt.__parent]?.worker){roots[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,method,transfer)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,args,key,subInput,blocking)=>{return this.subscribeToWorker(route,options._id,callback,args,key,subInput,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,void 0,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,void 0,workerSubs[key].callback,void 0,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub});console.log(JSON.stringify(workerSubs))}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]).then(console.log)}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.open=this.addWorker;this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys2=Object.keys(this.workers);this.workers[keys2[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys2.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}else if(typeof worker==="object"){if(worker?._id){worker=worker.worker;delete this.workers[worker?._id]}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,args,key,subInput,blocking)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,args,key,subInput)};this.subscribeToWorker=(route,workerId,callback,args,key,subInput,blocking)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeEvent(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,args,key,subInput,blocking])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i2=0;i2{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,args,key,subInput,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof sourceWorker==="object"){return sourceWorker.run("unsubscribe",[sourceRoute,sub])}};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.load(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn){if(event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){if(event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name2 of properties){dst[name2]=src[name2]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev2){eventHandlers.keydown(ev2,sendEvent)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev2){eventHandlers.keyup(ev2,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}blur(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){console.log(options);if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText2(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str=properties.toString();else if(typeof properties==="string")str=properties;if(str){if(connection.run)return connection.run("setNode",[str]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){console.log("setting node",properties);if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText2(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(properties);nodeTemplates[node.__node.tag]=template;return node.__node.tag}else return false},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]==="function"){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str=recursivelyStringifyFunctions(properties);return str},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText2(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText2(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key in properties){result[key]=typeof node[key]}return result}return void 0},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};if(connection.run)return connection.run("receiveClass",[str,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str=fn.toString();let message={route:"setNode",args:[str,fnName]};if(connection.run)return connection.run("setNode",[str,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str,fnName]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str,fnName]}));return new Promise(r=>r(name))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i2=0;i2a+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i2=0;i2{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i2)=>{dsqrd+=(point2[i2]-c)*(point2[i2]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i2)=>{return(c+point2[i2])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i2)=>{vecn[i2]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i2=0;i2precision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i22)=>{if(Math.abs(xn1-root){vec.push(point2[i2]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i2,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i2},y:${j}`);return v+i2+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i2=0;if(typeof asIndex==="function"){while(i2{result[i2]=func(buffer[i2],i2,...coordinate);i2++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i2=0;i2upperBounds[i2]){let temp=upperBounds[i2];upperBounds[i2]=lowerBounds[i2];lowerBounds[i2]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i2=0;i2x2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i2=0;i20){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i2=start;i20){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i22=0;i22{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i2].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i2]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i2]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i2){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i2-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window){var smaArr=[];for(var i2=0;i2current+=previous)/(i2+1))}else{var arrslice=arr.slice(i2-window,i2);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i2=0;i2y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i2=incr;i2lastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i2=0;i2=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i2>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(i2Math.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(i2Math.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i2=0;i2=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i2>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i2=0;i2ref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i2=0){pass=false;break}else if(i2>ref.length*.5&&val<0){pass=false;break}}else{if(i2=0){pass=false;break}else if(i2>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i2=0;i2ref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i2)=>{if(peakIndices.indexOf(i2)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i2=0;i2new Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i2=range[0];i2{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i2=range[0][0]+stepx;i2{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i2=range[0][0]+stepx;i2{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i2=range[0];i2{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i2=1;i2<=fit2;i2++){result[i2]=lerp(v02,v12,a*i2);if(floor2)result[i2]=Math.floor(result[i2])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i2=0;i2 { - [key: string]: any; - }; - setValue: (key: any, value: any) => void; - triggerEvent: (key: any, value: any) => void; - subscribeState: (onchange: (res: any) => void) => number; - unsubscribeState: (sub: number) => boolean; - subscribeEvent: (key: string, onchange: (res: any) => void, refObject?: { - [key: string]: any; - }, refKey?: string) => number; - unsubscribeEvent: (key: string, sub?: number) => boolean; - subscribeEventOnce: (key: string, onchange: (res: any) => void) => any; - getEvent: (key: any, sub?: any) => { - [key: string]: any; - sub: number; - onchange: Function; - } | { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - getSnapshot: () => void; - onRemoved: (trigger: { - sub: number; - onchange: Function; - }) => void; -} diff --git a/src/extras/dist/core/Graph.d.ts b/src/extras/dist/core/Graph.d.ts deleted file mode 100644 index f77b09bd..00000000 --- a/src/extras/dist/core/Graph.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { EventHandler } from "./EventHandler"; -export declare const state: EventHandler; -export type GraphNodeProperties = { - __props?: Function | { - [key: string]: any; - } | GraphNodeProperties | GraphNode; - __operator?: ((...args: any[]) => any) | string; - __children?: { - [key: string]: any; - }; - __listeners?: { - [key: string]: true | string | ((result: any) => void) | { - __callback: string | ((result: any) => void) | true; - subInput?: boolean; - [key: string]: any; - }; - } | { - [key: string]: ((result: any) => void) | true | string; - }; - __onconnected?: ((node: any) => void | ((node: any) => void)[]); - __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); - __node?: { - tag?: string; - state?: EventHandler; - [key: string]: any; - }; - __args?: any[]; - __callable?: boolean; - [key: string]: any; -}; -export type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; -export type Roots = { - [key: string]: any; -}; -export type GraphOptions = { - roots?: Roots; - loaders?: { - [key: string]: Loader | { - init?: Loader; - connected?: (node: any) => void; - disconnected?: (node: any) => void; - }; - }; - state?: EventHandler; - mapGraphs?: false; - [key: string]: any; -}; -export type argObject = { - __input?: string | ((...args: any[]) => any); - __callback: string | ((...args: any[]) => any); - __args?: any[]; - __output?: string | argObject | ((...args: any[]) => any); -}; -export type Listener = { - __callback?: string; - __args?: (argObject | Function | string)[]; - sub: number; - node: GraphNode; - graph: Graph; - source?: string; - key?: string; - target?: string; - tkey?: string; - arguments?: Function[]; - subInput?: boolean; - onchange: Function; -}; -export declare class Callable extends Function { - __bound: Callable; - __call: ((...args: any[]) => any); - [key: string]: any; - constructor(); -} -export declare class GraphNode { - __node: { - tag: string; - unique: string; - state: EventHandler; - [key: string]: any; - }; - __children?: { - [key: string]: GraphNode; - }; - __parent?: Graph | GraphNode; - __operator?: any; - __listeners?: any; - __props?: any; - __args: any[]; - [key: string]: any; - constructor(properties: GraphNodeProperties, parent?: { - [key: string]: any; - }, graph?: Graph); - get __graph(): any; - set __graph(graph: any); - __setProperties: (properties: any, parent: any, graph: any) => void; - __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, target?: string, tkey?: string, args?: any[], callbackStr?: string) => any; - __unsubscribe: (sub?: number, key?: string, unsubInput?: boolean) => boolean; - __setOperator: (fn: (...args: any[]) => any) => any; - __addLocalState: (props?: { - [key: string]: any; - }, key?: string) => void; - __proxyObject: (obj: any) => void; - __addOnconnected(callback: (node: any) => void): void; - __addOndisconnected(callback: (node: any) => void): void; - __callConnected(node?: this): void; - __callDisconnected(node?: this): void; -} -export declare class Graph { - [key: string]: any; - __node: { - tag: string; - unique: string; - state: EventHandler; - nodes: Map; - roots: { - [key: string]: any; - }; - mapGraphs?: boolean; - [key: string]: any; - }; - constructor(options?: GraphOptions); - init: (options?: GraphOptions) => void; - load: (roots: { - [key: string]: any; - }, overwrite?: boolean) => { - [key: string]: any; - }; - setLoaders: (loaders: { - [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, props: any, key: string) => void; - }, replace?: boolean) => any; - runLoaders: (node: any, parent: any, properties: any, key: any) => void; - add: (properties: any, parent?: GraphNode | string, overwrite?: boolean) => GraphNode; - recursiveSet: (originCpy: any, parent: any, listeners: any, origin: any, overwrite?: boolean) => any; - remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; - run: (node: string | GraphNode, ...args: any[]) => any; - /** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners: (listeners: { - [key: string]: { - [key: string]: any; - }; - }) => void; - clearListeners: (node: GraphNode | string, listener?: string) => void; - get: (tag: string) => any; - getByUnique: (unique: string) => any; - set: (tag: string, node: GraphNode) => Map; - delete: (tag: string) => boolean; - list: () => string[]; - getListener: (nodeTag: string, key?: string, sub?: number) => Listener; - getProps: (node: GraphNode | string, getInitial?: boolean) => void; - subscribe: (nodeEvent: GraphNode | string, onEvent: string | GraphNode | ((...res: any) => void), args?: any[], key?: string | undefined, subInput?: boolean, target?: string | GraphNode, tkey?: string) => number; - unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; - setState: (update: { - [key: string]: any; - }) => void; -} -export declare function getAllProperties(obj: any): any[]; -export declare function instanceObject(obj: any): any; -export declare function isNativeClass(thing: any): boolean; -export declare function isFunction(x: any): "function" | "class" | "async" | "arrow" | ""; -export declare let getCallbackFromString: (a: any, graph: any) => (...inp: any[]) => any; -export declare const wrapArgs: (callback: any, argOrder: any, graph: any) => { - __callback: any; - __args: any[]; -}; diff --git a/src/extras/dist/extras/algorithms/accel_gyro.d.ts b/src/extras/dist/extras/algorithms/accel_gyro.d.ts deleted file mode 100644 index c98cb706..00000000 --- a/src/extras/dist/extras/algorithms/accel_gyro.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const accel_gyro: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/beat_detect.d.ts b/src/extras/dist/extras/algorithms/beat_detect.d.ts deleted file mode 100644 index bc3fb33d..00000000 --- a/src/extras/dist/extras/algorithms/beat_detect.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const beat_detect: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/blink.d.ts b/src/extras/dist/extras/algorithms/blink.d.ts deleted file mode 100644 index 4743de8d..00000000 --- a/src/extras/dist/extras/algorithms/blink.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const blink_detect: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/buffering.d.ts b/src/extras/dist/extras/algorithms/buffering.d.ts deleted file mode 100644 index 71e1efac..00000000 --- a/src/extras/dist/extras/algorithms/buffering.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const circularBuffer2d: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/coherence.d.ts b/src/extras/dist/extras/algorithms/coherence.d.ts deleted file mode 100644 index 0b35b736..00000000 --- a/src/extras/dist/extras/algorithms/coherence.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const coherence: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/dft.d.ts b/src/extras/dist/extras/algorithms/dft.d.ts deleted file mode 100644 index ccd239c3..00000000 --- a/src/extras/dist/extras/algorithms/dft.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const dft: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/index.d.ts b/src/extras/dist/extras/algorithms/index.d.ts deleted file mode 100644 index c3ec990e..00000000 --- a/src/extras/dist/extras/algorithms/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -declare const algorithms: { - [key: string]: GraphNodeProperties; -}; -export { algorithms }; diff --git a/src/extras/dist/extras/algorithms/index.gpu.d.ts b/src/extras/dist/extras/algorithms/index.gpu.d.ts deleted file mode 100644 index fcfc3ef0..00000000 --- a/src/extras/dist/extras/algorithms/index.gpu.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare const gpualgorithms: { - dft: import("../../core/Graph").GraphNodeProperties; - coherence: import("../../core/Graph").GraphNodeProperties; -}; diff --git a/src/extras/dist/extras/algorithms/rms.d.ts b/src/extras/dist/extras/algorithms/rms.d.ts deleted file mode 100644 index 39ad84d0..00000000 --- a/src/extras/dist/extras/algorithms/rms.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -export declare const rms: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/util/ArrayManip.d.ts b/src/extras/dist/extras/algorithms/util/ArrayManip.d.ts deleted file mode 100644 index b6d5e3ad..00000000 --- a/src/extras/dist/extras/algorithms/util/ArrayManip.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export declare class ArrayManip { - static autoscale(array: any, lineIdx?: number, nLines?: number, centerZero?: boolean, ymin?: number, ymax?: number, clamp?: boolean): any; - static genTimestamps(ct: any, sps: any): any[]; - static absmax(array: any): number; - static downsample(array: any, fitCount: any, scalar?: number): any; - static upsample(array: any, fitCount: any, scalar?: number): any[]; - static interpolate(array: number[], fitCount: number, scalar?: number): any; - static HSLToRGB(h: any, s: any, l: any, scalar?: number): [number, number, number]; - static circularBuffer(arr: any[], newEntries: any[]): any[]; - static reformatData(data: { - [key: string]: number[] | number | { - values: number[] | number; - [key: string]: any; - }; - } | string | ((number | number[])[]) | number, key?: string): string | number | { - [key: string]: number | number[] | { - [key: string]: any; - values: number[] | number; - }; - } | (number | number[])[]; - static padTime(data: number[], //new data, assumed to be sequential between a gap - lastValue: number, //the last data point before the gap - time: number, //interval that's passed to determine slope between samples - targetFit: number): number[]; - static interpolateForTime(data: number[], //new data, assumed to be evenly spread over a time interval - time: number, //the time interval passed (s) - targetSPS: number): any; - static bufferValues: (objects: { - [key: string]: { - [key: string]: any; - }; - }, property: string, keys?: string[] | { - [key: string]: any; - }, buffer?: ArrayBufferLike) => ArrayBufferLike; - isTypedArray(x: any): boolean; - recursivelyAssign: (target: any, obj: any) => any; - spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; -} diff --git a/src/extras/dist/extras/algorithms/util/BiquadFilters.d.ts b/src/extras/dist/extras/algorithms/util/BiquadFilters.d.ts deleted file mode 100644 index fd1d4fc9..00000000 --- a/src/extras/dist/extras/algorithms/util/BiquadFilters.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -export type FilterSettings = { - sps: number; - useSMA4?: boolean; - useNotch50?: boolean; - useNotch60?: boolean; - useLowpass?: boolean; - lowpassHz?: number; - useBandpass?: boolean; - bandpassLower?: number; - bandpassUpper?: number; - useDCBlock?: boolean; - DCBresonance?: number; - useScaling?: boolean; - scalar?: number; - trimOutliers?: boolean; - outlierTolerance?: number; -}; -export declare class BiquadChannelFilterer { - idx: number; - sps: number; - bandpassLower?: number; - bandpassUpper?: number; - useSMA4?: boolean; - last4?: number[]; - filtered: number; - trimOutliers?: boolean; - outlierTolerance?: number; - useNotch50?: boolean; - useNotch60?: boolean; - useLowpass?: boolean; - lowpassHz?: number; - useBandpass?: boolean; - useDCBlock?: boolean; - DCBresonance?: number; - useScaling?: boolean; - scalar?: number; - notch50?: any; - notch60?: any; - lp1?: any; - bp1?: any; - dcb?: any; - constructor(options?: FilterSettings); - reset(sps?: number): void; - setBandpass(bandpassLower?: number, bandpassUpper?: number, sps?: number): void; - apply(latestData?: number): number; -} -export declare class Biquad { - type: string; - freq: number; - sps: number; - Q: number; - dbGain: number; - a0: number; - a1: number; - a2: number; - b0: number; - b1: number; - b2: number; - x1: number; - x2: number; - y1: number; - y2: number; - constructor(type: 'lowpass' | 'highpass' | 'bandpass' | 'notch' | 'peak' | 'lowshelf' | 'highshelf', freq: number, sps: number, Q?: number, dbGain?: number); - lowpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - highpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - bandpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - notch(A: any, sn: any, cs: any, alpha: any, beta: any): void; - peak(A: any, sn: any, cs: any, alpha: any, beta: any): void; - lowshelf(A: any, sn: any, cs: any, alpha: any, beta: any): void; - highshelf(A: any, sn: any, cs: any, alpha: any, beta: any): void; - applyFilter(signal_step: any): number; - zResult(freq: any): number; - static calcCenterFrequency(freqStart: any, freqEnd: any): number; - static calcBandwidth(freqStart: any, freqEnd: any): number; - static calcBandpassQ(frequency: any, bandwidth: any, resonance?: number): number; - static calcNotchQ(frequency: any, bandwidth: any, resonance?: number): number; -} -export declare class DCBlocker { - r: number; - x1: number; - x2: number; - y1: number; - y2: number; - constructor(r?: number); - applyFilter(signal_step: any): number; -} -export declare const makeNotchFilter: (frequency: any, sps: any, bandwidth: any) => Biquad; -export declare const makeBandpassFilter: (freqStart: any, freqEnd: any, sps: any, resonance?: number) => Biquad; diff --git a/src/extras/dist/extras/algorithms/util/ByteParser.d.ts b/src/extras/dist/extras/algorithms/util/ByteParser.d.ts deleted file mode 100644 index 178a7329..00000000 --- a/src/extras/dist/extras/algorithms/util/ByteParser.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { ArrayManip } from "./ArrayManip"; -export declare class ByteParser extends ArrayManip { - static codes: { - '\\n': number; - '\\r': number; - '\\t': number; - '\\s': number; - '\\b': number; - '\\f': number; - '\\': number; - }; - static toDataView(value: string | number | ArrayBufferLike | DataView | number[]): DataView; - static searchBuffer(buffer: number[] | ArrayBuffer, searchString: Uint8Array, limit?: number): any[]; - static bytesToInt16(x0: number, x1: number): number; - static bytesToUInt16(x0: number, x1: number): number; - static Uint16ToBytes(y: number): number[]; - static bytesToInt24(x0: number, x1: number, x2: number): number; - static bytesToUInt24(x0: number, x1: number, x2: number): number; - static Uint24ToBytes(y: number): number[]; - static bytesToInt32(x0: number, x1: number, x2: number, x3: number): number; - static bytesToUInt32(x0: number, x1: number, x2: number, x3: number): number; - static Uint32ToBytes(y: number): number[]; - static get2sCompliment(val: number, nbits: number): number; - static getSignedInt(...args: number[]): number; - static asUint8Array(input: any): Uint8Array; - static boyerMoore(patternBuffer: any): any; - static struct(format: string): Readonly<{ - unpack: (arrb: any) => any[]; - pack: (...values: any[]) => ArrayBuffer; - unpack_from: (arrb: any, offs: any) => any[]; - pack_into: (arrb: any, offs: any, ...values: any[]) => void; - iter_unpack: (arrb: any) => Generator; - format: string; - size: number; - }>; -} diff --git a/src/extras/dist/extras/ecs/ECS.systems.d.ts b/src/extras/dist/extras/ecs/ECS.systems.d.ts deleted file mode 100644 index 34de4406..00000000 --- a/src/extras/dist/extras/ecs/ECS.systems.d.ts +++ /dev/null @@ -1,383 +0,0 @@ -import { Entity } from "../../services/ecs/ECS.service"; -export declare const Systems: { - collision: { - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __node: { - tag: string; - }; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - collisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionEnabled?: boolean; - collisionType: 'sphere' | 'box' | 'point'; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionEnabled?: boolean; - collisionType: 'sphere' | 'box' | 'point'; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => number | false; - sphereCollisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - boxCollisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => boolean; - sphereBoxCollisionCheck: (sphere: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, box: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - isPointInsideSphere: (point: { - x: number; - y: number; - z: number; - }, sphere: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - isPointInsideBox: (point: { - x: number; - y: number; - z: number; - }, box: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => boolean; - closestPointOnLine: (point: { - x: number; - y: number; - z: number; - }, lineStart: { - x: number; - y: number; - z: number; - }, lineEnd: { - x: number; - y: number; - z: number; - }) => { - x: number; - y: number; - z: number; - }; - closestPointOnPolygon: (point: { - x: number; - y: number; - z: number; - }, t0: { - x: number; - y: number; - z: number; - }, t1: { - x: number; - y: number; - z: number; - }, t2: { - x: number; - y: number; - z: number; - }) => { - [key: string]: number; - }; - calcNormal: (t0: { - x: number; - y: number; - z: number; - }, t1: { - x: number; - y: number; - z: number; - }, t2: { - x: number; - y: number; - z: number; - }, positive?: boolean) => {}; - dot: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; - makeVec(p1: { - x: number; - y: number; - z: number; - }, p2: { - x: number; - y: number; - z: number; - }): { - x: number; - y: number; - z: number; - }; - vecadd: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecsub: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecmul: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecdiv: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecscale: (v1: { - [key: string]: number; - }, scalar: number) => { - [key: string]: number; - }; - distance: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; - magnitude: (v: { - [key: string]: number; - }) => number; - normalize: (v: { - [key: string]: number; - }) => {}; - distance3D(v1: { - x: number; - y: number; - z: number; - }, v2: { - x: number; - y: number; - z: number; - }): number; - cross3D(v1: { - x: number; - y: number; - z: number; - }, v2: { - x: number; - y: number; - z: number; - }): { - x: number; - y: number; - z: number; - }; - nearestNeighborSearch(entities: { - [key: string]: Entity; - }, isWithinRadius?: number): {}; - generateBoundingVolumeTree(entities: { - [key: string]: Entity; - }, mode?: 'octree' | 'aabb', withinRadius?: number, minEntities?: number): any; - }; - collider: { - lastTime: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - checkBoundingBox: (entity: any) => void; - resolveBoxCollision: (body1: Entity, box: Entity, negate?: boolean) => void; - resolveSphereCollisions: (entity1: Entity, entity2: Entity, dist?: number) => void; - }; - nbody: { - lastTime: number; - G: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - attract: (body1: any, body2: any, dist?: number, G?: any, vecn?: { - x: number; - y: number; - z: number; - }) => void; - }; - boid: { - lastTime: number; - defaultAnchor: { - x: number; - y: number; - z: number; - mul: number; - }; - setupEntities: (entities: any) => any; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - }; - movement: { - __node: { - tag: string; - }; - lastTime: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => void; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - }; -}; diff --git a/src/extras/dist/extras/gpu/GPU.service.d.ts b/src/extras/dist/extras/gpu/GPU.service.d.ts deleted file mode 100644 index 547ea325..00000000 --- a/src/extras/dist/extras/gpu/GPU.service.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Service } from "../../services/Service"; -import { gpuUtils } from 'gpujsutils'; -export declare class GPUService extends Service { - gpu: gpuUtils; - constructor(options?: any); - addFunc: (fn: string | Function) => void; - addKernel: (name: string, fn: string | Function, options?: any) => void; - combineKernels: (name: string, fs: (string | Function)[], ckrnl?: () => void) => void; - callKernel: (name: string, ...args: any[]) => void; - dft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; - multidft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; - multidftbandpass: (buffered: number[][], nSeconds: number, freqStart: number, freqEnd: number, scalar?: number) => any; - coherence: (buffered: number[][], nSeconds: number, freqStart: number, freqEnd: number) => any[]; -} diff --git a/src/extras/dist/extras/index.gpu.services.d.ts b/src/extras/dist/extras/index.gpu.services.d.ts deleted file mode 100644 index a1d3d930..00000000 --- a/src/extras/dist/extras/index.gpu.services.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './gpu/GPU.service'; -export { gpualgorithms } from './algorithms/index.gpu'; diff --git a/src/extras/dist/extras/index.services.d.ts b/src/extras/dist/extras/index.services.d.ts deleted file mode 100644 index 4c38107e..00000000 --- a/src/extras/dist/extras/index.services.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './struct/Struct.frontend'; -export * from './struct/Struct.backend'; -export * from './struct/genTimestamps'; -export * from './ecs/ECS.systems'; -export * from './webgl-plot/webglplot.routes'; -export { algorithms } from './algorithms/index'; diff --git a/src/extras/dist/extras/struct/Struct.backend.d.ts b/src/extras/dist/extras/struct/Struct.backend.d.ts deleted file mode 100644 index 278d1ebe..00000000 --- a/src/extras/dist/extras/struct/Struct.backend.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { ObjectId } from "./datastructures/bson.cjs"; -import { AuthorizationStruct, GroupStruct, ProfileStruct } from "./datastructures/types"; -import { TimeSpecifier } from './genTimestamps'; -import { Service } from "../../services/Service"; -import { User } from '../../services/router/Router'; -export declare const toObjectId: (str: any) => any; -export declare const getStringId: (mongoid: string | ObjectId) => any; -type CollectionsType = { - [x: string]: CollectionType; -}; -type CollectionType = any | { - instance?: any; - reference: { - [key: string]: any; - }; -}; -export declare class StructBackend extends Service { - name: string; - debug: boolean; - db: any; - users: { - [key: string]: User; - }; - collections: CollectionsType; - mode: 'local' | 'mongo' | string; - useAuths: boolean; - useAccessTokens: boolean; - useRefreshTokens: boolean; - accessTokens: Map; - refreshTokens: Map; - constructor(options?: any, dboptions?: { - users?: { - [key: string]: User; - }; - mode?: 'local' | 'mongo' | string; - db?: any; - collections?: CollectionsType; - useAuths?: boolean; - debug?: boolean; - useAccessTokens?: boolean; - useRefreshTokens?: boolean; - }); - initDB: (dboptions: any) => void; - query: (requestingUserId: string, collection?: any, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - getUser: (requestingUserId: string, lookupId: string, basicInfo?: boolean, token?: string) => Promise; - setUser: (requestingUserId: string, struct: Partial, token: string) => Promise; - getUsersByIds: (requestingUserId: string, userIds: string[], basicInfo?: boolean) => Promise; - getUsersByRole: (requestingUserId: string, role: string) => Promise; - deleteUser: (requestingUserId: string, userId: string, deleteData?: boolean, token?: string) => Promise; - setData: (requestingUserId: string, structs: any[], notify?: boolean, token?: string) => Promise; - getData: (requestingUserId: string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number, token?: string) => Promise; - getDataByIds: (requestingUserId: string, structIds: string[], ownerId?: string, collection?: string, token?: string) => Promise; - getAllData: (requestingUserId: string, ownerId: string, excludedCollections?: string[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - deleteData: (requestingUserId: string, structIds: string[], token?: string) => Promise; - getUserGroups: (requestingUserId: string, userId?: string, groupId?: string) => Promise; - deleteGroup: (requestingUserId: string, groupId: string, token?: string) => Promise; - getAuthorizations: (requestingUserId: string, ownerId?: string, authId?: string, token?: string) => Promise; - deleteAuthorization: (requestingUserId: string, authId: string, token?: string) => Promise; - getToken: (user: Partial) => string; - notificationStruct: (parentStruct?: any) => { - structType: string; - timestamp: number; - _id: string; - note: string; - alert: boolean; - ownerId: string; - parentUserId: string; - parent: { - structType: any; - _id: any; - }; - }; - checkToNotify: (user: Partial, structs?: any[], mode?: string) => Promise; - queryMongo: (user: Partial, collection: string, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - setMongoData: (user: Partial, structs?: any[], notify?: boolean, token?: string) => Promise; - setMongoUser: (user: Partial, struct: Partial, token?: string) => Promise; - setGroup: (user: Partial, struct: any, mode?: string, token?: string) => Promise; - getMongoUser: (user: Partial, info?: string, requireAuth?: boolean, basicInfo?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - queryUsers: (user: Partial, info?: string, limit?: number, skip?: number, requireAuth?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - getMongoUsersByIds: (user: Partial, userIds?: any[], basicInfo?: boolean) => Promise; - getMongoUsersByRole: (user: Partial, role: string) => Promise; - getMongoDataByIds: (user: Partial, structIds: string[], ownerId: string | undefined, collection: string | undefined, token?: string) => Promise; - getMongoData: (user: Partial, collection: string | undefined, ownerId: string | undefined, dict?: any | undefined, limit?: number, skip?: number, token?: string) => Promise; - getAllUserMongoData: (user: Partial, ownerId: any, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - getMongoDataByRefs: (user: Partial, structRefs?: any[], token?: string) => Promise; - getMongoAuthorizations: (user: Partial, ownerId?: any, authId?: string, token?: string) => Promise; - getMongoGroups: (user: Partial, userId?: any, groupId?: string) => Promise; - deleteMongoData: (user: Partial, structRefs?: any[], token?: string) => Promise; - deleteMongoUser: (user: Partial, userId: any, deleteData?: boolean, token?: string) => Promise; - deleteMongoGroup: (user: Partial, groupId: any, token?: string) => Promise; - deleteMongoAuthorization: (user: Partial, authId: any, token?: string) => Promise; - setAuthorization: (user: Partial, authStruct: any, token?: string) => Promise; - checkAuthorization: (user: string | Partial | { - _id: string; - }, struct: any, request?: string, token?: string) => Promise; - wipeDB: () => Promise; - overwriteLocalData: (structs: any) => void; - setLocalData: (structs: any) => void; - getLocalData: (collection: any, query?: any) => any; - deleteLocalData: (struct: any) => boolean; -} -export {}; diff --git a/src/extras/dist/extras/struct/Struct.frontend.d.ts b/src/extras/dist/extras/struct/Struct.frontend.d.ts deleted file mode 100644 index 3b0ef8dc..00000000 --- a/src/extras/dist/extras/struct/Struct.frontend.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { DataTablet } from './datastructures/index'; -import { Data, ProfileStruct, AuthorizationStruct, GroupStruct, DataStruct, EventStruct, ChatroomStruct, CommentStruct, Struct } from './datastructures/types'; -import { TimeSpecifier } from './genTimestamps'; -import { Service } from '../../services/Service'; -import { User } from '../../services/router/Router'; -import { GraphNodeProperties } from '../../core/Graph'; -export declare const randomId: (prefix?: any) => string; -export declare const pseudoObjectId: (m?: Math, d?: DateConstructor, h?: number, s?: (s: any) => string) => string; -export type StructFrontendProps = { - useAccessTokens?: boolean; - useRefreshTokens?: boolean; -} & GraphNodeProperties; -export declare class StructFrontend extends Service { - name: string; - currentUser: User; - tablet: DataTablet; - collections: Map; - id: string; - useAccessTokens: boolean; - useRefreshTokens: boolean; - constructor(options?: any, user?: Partial); - getToken(user: Partial): string; - setupUser: (userinfo: Partial, callback?: (currentUser: any) => void) => Promise; - baseServerCallback: (data: any) => void; - structNotification: () => void; - structDeleted: (struct: { - _id: string; - structType: string; - }) => void; - onResult: (data: any) => void; - randomId(tag?: string): string; - /** - let struct = { - _id: randomId(structType+'defaultId'), //random id associated for unique identification, used for lookup and indexing - structType: structType, //this is how you will look it up by type in the server - ownerId: parentUser?._id, //owner user - timestamp: Date.now(), //date of creation - parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) - } - */ - addStruct: (structType?: string, props?: any, parentUser?: { - [key: string]: any; - }, parentStruct?: { - [key: string]: any; - }, updateServer?: boolean) => Promise; - getUser: (info?: string | number, basicInfo?: boolean, callback?: (data: any) => void) => Promise<{ - user: ProfileStruct; - groups: GroupStruct[]; - authorizations: AuthorizationStruct[]; - }>; - queryUsers: (info: string, skip?: number, limit?: number, callback?: (data: any) => void) => Promise; - getUsers: (ids?: (string | number)[], basicInfo?: boolean, callback?: (data: any) => void) => Promise; - getUsersByRole: (userRole: string, callback?: (data: any) => void) => Promise; - getAllUserData: (ownerId: string | number, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], callback?: (data: any) => void) => Promise; - query: (collection: string, mongoQuery?: {}, findOne?: boolean, skip?: number, callback?: (data: any) => void) => Promise; - getDataByTimeRange(collection: any, timeRange?: [number | TimeSpecifier, number | TimeSpecifier], ownerId?: string | number | undefined, limit?: number, skip?: number, key?: string): Promise; - getData: (collection: string, ownerId?: string | number | undefined, searchDict?: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - getDataByIds: (structIds?: any[], ownerId?: string | number | undefined, collection?: string | undefined, callback?: (data: any) => void) => Promise; - getStructParentData: (struct: Struct, callback?: (data: any) => void) => Promise; - setUser: (userStruct: ProfileStruct, callback?: (data: any) => void) => Promise; - checkUserToken: (usertoken: any, user?: User, callback?: (data: any) => void) => Promise; - setData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; - updateServerData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; - deleteData: (structs?: any[], callback?: (data: any) => void) => Promise; - deleteUser: (userId?: string, deleteData?: boolean, callback?: (data: any) => void) => Promise; - setGroup: (groupStruct: GroupStruct, callback?: (data: any) => void) => Promise; - getUserGroups: (userId?: string, groupId?: string, callback?: (data: any) => void) => Promise; - deleteGroup: (groupId: any, callback?: (data: any) => void) => Promise; - setAuthorization: (authorizationStruct: AuthorizationStruct, callback?: (data: any) => void) => Promise; - getAuthorizations: (userId?: string, authorizationId?: string, callback?: (data: any) => void) => Promise; - deleteAuthorization: (authorizationId: any, callback?: (data: any) => void) => Promise; - checkForNotifications: (userId?: string) => Promise; - resolveNotifications: (notifications?: any[], pull?: boolean, user?: Partial) => Promise; - setAuthorizationsByGroup: (user?: User) => Promise; - deleteRoom: (roomStruct: any) => Promise; - deleteComment: (commentStruct: any) => Promise; - getUserDataByAuthorization: (authorizationStruct: any, collection: any, searchDict: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - getUserDataByAuthorizationGroup: (groupId: string, collection: any, searchDict: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - overwriteLocalData(structs: any): void; - setLocalData(structs: any): void; - getLocalData(collection: any, query?: any): any; - getLocalUserPeerIds: (user?: User) => any; - getLocalReplies(struct: any): any; - hasLocalAuthorization(otherUserId: any, ownerId?: string): any; - deleteLocalData(structs: Struct[]): boolean; - deleteStruct(struct: Struct): boolean; - stripStruct(struct: Struct): Struct; - createStruct(structType: string, props: { - [key: string]: any; - }, parentUser?: User, parentStruct?: Struct): any; - userStruct(props?: Partial, currentUser?: boolean): ProfileStruct; - authorizeUser: (parentUser: Partial, authorizerUserId?: string, authorizerUserName?: string, authorizedUserId?: string, authorizedUserName?: string, authorizations?: {}, structs?: {}, excluded?: {}, groups?: {}, expires?: boolean) => Promise; - addGroup: (parentUser: Partial, name?: string, details?: string, admins?: {}, peers?: {}, clients?: {}, updateServer?: boolean) => Promise; - dataObject(data?: any, type?: string, timestamp?: string | number): { - type: string; - data: any; - timestamp: string | number; - }; - addData: (parentUser: Partial, author?: string, title?: string, type?: string, data?: string | Data[], expires?: boolean, updateServer?: boolean) => Promise; - addEvent: (parentUser: Partial, author?: string, event?: string | number, notes?: string, startTime?: string | number, endTime?: string | number, grade?: string | number, value?: any, units?: string, location?: any, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; - addChatroom: (parentUser: Partial, authorId?: string, message?: string, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; - addComment: (parentUser: Partial, roomStruct?: { - _id: string; - users: any[]; - comments: any[]; - }, replyTo?: { - _id: string; - replies: any[]; - }, authorId?: string, message?: string, attachments?: string | Data[], updateServer?: boolean) => Promise; -} diff --git a/src/extras/dist/extras/struct/datastructures/DataStructures.d.ts b/src/extras/dist/extras/struct/datastructures/DataStructures.d.ts deleted file mode 100644 index 3da6e206..00000000 --- a/src/extras/dist/extras/struct/datastructures/DataStructures.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -import * as types from './types'; -export declare function Struct(structType?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.Struct; -export declare const eegCoordinates: { - [x: string]: number[]; -}; -export declare function setCoordinate(channelDict: any, assignTo?: {}): any; -export declare function EEGCoordinates(channelDicts?: [], genCoherenceMap?: boolean): types.EEGStruct[]; -export declare function FrequencyBandsStruct(additionalBands?: types.FrequencyBandNames[], //add whatever tags -assignTo?: {}): types.FrequencyBandsStruct; -export declare function EEGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EEGStruct; -export declare function CoherenceStruct(coords?: { - 0: types.EEGStruct; - 1: types.EEGStruct; -}, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.CoherenceStruct; -export declare function CoherenceMap(opts?: { - channelDicts: any[]; - taggedOnly?: boolean; -}, _?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.CoherenceStruct[]; -export declare function FNIRSStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.FNIRSStruct; -export declare function IMUStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.IMUStruct; -export declare function EyeTrackerStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EyeTrackerStruct; -export declare function ECGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ECGStruct; -export declare function EDAStruct(_?: string, __?: {}, ___?: { - _id: string; -}, ____?: { - structType: string; - _id: string; -}): void; -export declare function PPGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.FNIRSStruct; -export declare function HRVStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ECGStruct; -export declare function EMGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EEGStruct; -export declare function ProfileStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ProfileStruct; -export declare function AuthorizationStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.AuthorizationStruct; -export declare function GroupStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.GroupStruct; -export declare function Data(type: string, data: any): { - type: string; - data: any; - timestamp: number; -}; -export declare function DataStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.DataStruct; -export declare function EventStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.EventStruct; -export declare function ChatroomStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.ChatroomStruct; -export declare function CommentStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.CommentStruct; -export declare function NotificationStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.NotificationStruct; -export declare function ScheduleStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.ScheduleStruct; -export declare function DateStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.DateStruct; -export declare const structRegistry: { - Struct: typeof Struct; - EEGStruct: typeof EEGStruct; - FNIRSStruct: typeof FNIRSStruct; - CoherenceStruct: typeof CoherenceStruct; - CoherenceMap: typeof CoherenceMap; - FrequencyBandsStruct: typeof FrequencyBandsStruct; - IMUStruct: typeof IMUStruct; - EyeTrackerStruct: typeof EyeTrackerStruct; - ECGStruct: typeof ECGStruct; - EDAStruct: typeof EDAStruct; - PPGStruct: typeof PPGStruct; - HRVStruct: typeof HRVStruct; - EMGStruct: typeof EMGStruct; - ProfileStruct: typeof ProfileStruct; - AuthorizationStruct: typeof AuthorizationStruct; - GroupStruct: typeof GroupStruct; - DataStruct: typeof DataStruct; - EventStruct: typeof EventStruct; - ChatroomStruct: typeof ChatroomStruct; - CommentStruct: typeof CommentStruct; - NotificationStruct: typeof NotificationStruct; - ScheduleStruct: typeof ScheduleStruct; - DateStruct: typeof DateStruct; -}; diff --git a/src/extras/dist/extras/struct/datastructures/DataTablet.d.ts b/src/extras/dist/extras/struct/datastructures/DataTablet.d.ts deleted file mode 100644 index 967adeae..00000000 --- a/src/extras/dist/extras/struct/datastructures/DataTablet.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { ArbitraryObject, Struct } from './types'; -export declare class DataTablet { - workerId: any; - id: any; - threaded: boolean; - workers: any; - DS: any; - collections: Map; - data: any; - rolloverLimit: number; - dataSorts: Map; - watches: any; - constructor(props?: {}); - randomId(tag?: string): string; - setLocalData(structs: (Partial)[] | (Partial)): void; - getLocalData(collection: string, query: any): any; - onCollectionSet: (type: any, collection: any) => void; - runSort(key: string, dataObj?: {}, newdata?: any[], tablet?: this): any; - /** - * Unsorted data structs come in with a minimum 'structType' and 'timestamp' set of values. - * - * If a sort key matches the structType or dataType (from a data struct.data array), - * it can return a modified struct or push to the newdata array with a set of newly made structs. - * Return undefined to process the input data by default structType/dataType and timestamp into the tablet, so you can do this - * plus split up additional structs or processed structs into each other. This is intentionally vague until we refine this idea into clearer hooks. - * The newdata array accumulates all of the data structs supplied on a sort pass which gets sent to this.onSorted() at the end of the sorting pass. - */ - setSort(key: string | string[], response?: (data: any, newdata?: any[], tablet?: this) => void): void; - getSort(key: string): any; - checkWatches(sorted?: ArbitraryObject): void; - /** - * - pass the sorted structure to the accumulator object which is just an empty object you can do whatever with - * - ondata checks the data if it's relevant and keeps a record via the accumulator - * - if the accumlator condition is satisfied, return true which triggers ontrigger(accum), else return a falsey value - * - ontrigger function then is passed the accumulator object to do whatever with, - * e.g. supply it to an 'alert' struct, set alert:true, and data:accum, and update the server to notify any connected peers. - */ - setWatch(name: string, ownerId: string | undefined, ondata?: (sorted: any, accum: any, ownerId: string) => boolean, ontrigger?: (accum: any) => void): void; - getWatch(name: string): any; - sortStructsIntoTable(datastructs?: Struct[]): Promise; - onUpdate(_: any, __: any, ___?: any): void; - onSorted(_?: any[]): void; - getDataByTimestamp(timestamp: number, ownerId: string): any; - getDataByTimeRange(begin: number, end: number, type: string, ownerId: string): ArbitraryObject; - getDataByType(type: string, timestamp: number, ownerId: string): any; - filterSleepResults(unfiltered?: ArbitraryObject): ArbitraryObject; - sortObjectByPropName(object: ArbitraryObject): ArbitraryObject; - checkRollover(collection: string, limit?: number): boolean; -} diff --git a/src/extras/dist/extras/struct/datastructures/bson.d.cts b/src/extras/dist/extras/struct/datastructures/bson.d.cts deleted file mode 100644 index 2efd64df..00000000 --- a/src/extras/dist/extras/struct/datastructures/bson.d.cts +++ /dev/null @@ -1,419 +0,0 @@ -declare var bson: Readonly<{ - __proto__: any; - Code: typeof Code; - BSONSymbol: typeof BSONSymbol; - DBRef: typeof DBRef; - Binary: typeof Binary; - ObjectId: typeof ObjectId; - UUID: typeof UUID; - Long: typeof Long; - Timestamp: typeof Timestamp; - Double: typeof Double; - Int32: typeof Int32; - MinKey: typeof MinKey; - MaxKey: typeof MaxKey; - BSONRegExp: typeof BSONRegExp; - Decimal128: typeof Decimal128; - setInternalBufferSize: typeof setInternalBufferSize; - serialize: typeof serialize; - serializeWithBufferAndIndex: typeof serializeWithBufferAndIndex; - deserialize: typeof deserialize; - calculateObjectSize: typeof calculateObjectSize; - deserializeStream: typeof deserializeStream; - BSONValue: typeof BSONValue; - BSONError: typeof BSONError; - BSONVersionError: typeof BSONVersionError; - BSONRuntimeError: typeof BSONRuntimeError; - BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; - }>; - EJSON: any; -}>; -export class BSONError extends Error { - static isBSONError(value: any): boolean; - constructor(message: any); - get bsonError(): boolean; - get name(): string; -} -export class BSONRegExp extends BSONValue { - static parseOptions(options: any): any; - static fromExtendedJSON(doc: any): any; - constructor(pattern: any, options: any); - get _bsontype(): string; - pattern: any; - options: any; - toExtendedJSON(options: any): { - $regex: any; - $options: any; - $regularExpression?: undefined; - } | { - $regularExpression: { - pattern: any; - options: any; - }; - $regex?: undefined; - $options?: undefined; - }; - inspect(): string; -} -export class BSONRuntimeError extends BSONError { -} -export class BSONSymbol extends BSONValue { - static fromExtendedJSON(doc: any): BSONSymbol; - constructor(value: any); - get _bsontype(): string; - value: any; - valueOf(): any; - toString(): any; - inspect(): string; - toJSON(): any; - toExtendedJSON(): { - $symbol: any; - }; -} -export const BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; -}>; -export class BSONValue { -} -export class BSONVersionError extends BSONError { - constructor(); -} -export class Binary extends BSONValue { - static fromExtendedJSON(doc: any, options: any): Binary; - constructor(buffer: any, subType: any); - get _bsontype(): string; - sub_type: any; - buffer: any; - position: any; - put(byteValue: any): void; - write(sequence: any, offset: any): void; - read(position: any, length: any): any; - value(asRaw: any): any; - length(): any; - toJSON(): any; - toString(encoding: any): any; - toExtendedJSON(options: any): { - $binary: any; - $type: string; - } | { - $binary: { - base64: any; - subType: string; - }; - $type?: undefined; - }; - toUUID(): UUID; - inspect(): string; -} -export namespace Binary { - let BSON_BINARY_SUBTYPE_DEFAULT: number; - let BUFFER_SIZE: number; - let SUBTYPE_DEFAULT: number; - let SUBTYPE_FUNCTION: number; - let SUBTYPE_BYTE_ARRAY: number; - let SUBTYPE_UUID_OLD: number; - let SUBTYPE_UUID: number; - let SUBTYPE_MD5: number; - let SUBTYPE_ENCRYPTED: number; - let SUBTYPE_COLUMN: number; - let SUBTYPE_USER_DEFINED: number; -} -export class Code extends BSONValue { - static fromExtendedJSON(doc: any): Code; - constructor(code: any, scope: any); - get _bsontype(): string; - code: any; - scope: any; - toJSON(): { - code: any; - scope: any; - } | { - code: any; - scope?: undefined; - }; - toExtendedJSON(): { - $code: any; - $scope: any; - } | { - $code: any; - $scope?: undefined; - }; - inspect(): string; -} -export class DBRef extends BSONValue { - static fromExtendedJSON(doc: any): DBRef; - constructor(collection: any, oid: any, db: any, fields: any); - get _bsontype(): string; - collection: any; - oid: any; - db: any; - fields: any; - set namespace(value: any); - get namespace(): any; - toJSON(): any; - toExtendedJSON(options: any): { - $ref: any; - $id: any; - }; - inspect(): string; -} -export class Decimal128 extends BSONValue { - static fromString(representation: any): Decimal128; - static fromExtendedJSON(doc: any): Decimal128; - constructor(bytes: any); - get _bsontype(): string; - bytes: any; - toJSON(): { - $numberDecimal: string; - }; - toExtendedJSON(): { - $numberDecimal: string; - }; - inspect(): string; -} -export class Double extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Double; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toJSON(): number; - toString(radix: any): string; - toExtendedJSON(options: any): number | { - $numberDouble: string; - }; - inspect(): string; -} -export const EJSON: any; -export class Int32 extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Int32; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toString(radix: any): string; - toJSON(): number; - toExtendedJSON(options: any): number | { - $numberInt: string; - }; - inspect(): string; -} -export class Long extends BSONValue { - static fromBits(lowBits: any, highBits: any, unsigned: any): Long; - static fromInt(value: any, unsigned: any): any; - static fromNumber(value: any, unsigned: any): any; - static fromBigInt(value: any, unsigned: any): any; - static fromString(str: any, unsigned: any, radix: any): any; - static fromBytes(bytes: any, unsigned: any, le: any): Long; - static fromBytesLE(bytes: any, unsigned: any): Long; - static fromBytesBE(bytes: any, unsigned: any): Long; - static isLong(value: any): boolean; - static fromValue(val: any, unsigned: any): any; - static fromExtendedJSON(doc: any, options: any): any; - constructor(low: number, high: any, unsigned: any); - get _bsontype(): string; - get __isLong__(): boolean; - low: number; - high: number; - unsigned: boolean; - add(addend: any): Long; - and(other: any): Long; - compare(other: any): 0 | 1 | -1; - comp(other: any): 0 | 1 | -1; - divide(divisor: any): any; - div(divisor: any): any; - equals(other: any): boolean; - eq(other: any): boolean; - getHighBits(): number; - getHighBitsUnsigned(): number; - getLowBits(): number; - getLowBitsUnsigned(): number; - getNumBitsAbs(): any; - greaterThan(other: any): boolean; - gt(other: any): boolean; - greaterThanOrEqual(other: any): boolean; - gte(other: any): boolean; - ge(other: any): boolean; - isEven(): boolean; - isNegative(): boolean; - isOdd(): boolean; - isPositive(): boolean; - isZero(): boolean; - lessThan(other: any): boolean; - lt(other: any): boolean; - lessThanOrEqual(other: any): boolean; - lte(other: any): boolean; - modulo(divisor: any): Long; - mod(divisor: any): Long; - rem(divisor: any): Long; - multiply(multiplier: any): any; - mul(multiplier: any): any; - negate(): Long; - neg(): Long; - not(): Long; - notEquals(other: any): boolean; - neq(other: any): boolean; - ne(other: any): boolean; - or(other: any): Long; - shiftLeft(numBits: any): Long; - shl(numBits: any): Long; - shiftRight(numBits: any): Long; - shr(numBits: any): Long; - shiftRightUnsigned(numBits: any): Long; - shr_u(numBits: any): Long; - shru(numBits: any): Long; - subtract(subtrahend: any): Long; - sub(subtrahend: any): Long; - toInt(): number; - toNumber(): number; - toBigInt(): bigint; - toBytes(le: any): number[]; - toBytesLE(): number[]; - toBytesBE(): number[]; - toSigned(): Long; - toString(radix: any): any; - toUnsigned(): Long; - xor(other: any): Long; - eqz(): boolean; - le(other: any): boolean; - toExtendedJSON(options: any): number | { - $numberLong: any; - }; - inspect(): string; -} -export namespace Long { - let TWO_PWR_24: any; - let MAX_UNSIGNED_VALUE: Long; - let ZERO: any; - let UZERO: any; - let ONE: any; - let UONE: any; - let NEG_ONE: any; - let MAX_VALUE: Long; - let MIN_VALUE: Long; -} -export class MaxKey extends BSONValue { - static fromExtendedJSON(): MaxKey; - get _bsontype(): string; - toExtendedJSON(): { - $maxKey: number; - }; - inspect(): string; -} -export class MinKey extends BSONValue { - static fromExtendedJSON(): MinKey; - get _bsontype(): string; - toExtendedJSON(): { - $minKey: number; - }; - inspect(): string; -} -export class ObjectId extends BSONValue { - static getInc(): number; - static generate(time: any): any; - static createPk(): ObjectId; - static createFromTime(time: any): ObjectId; - static createFromHexString(hexString: any): ObjectId; - static isValid(id: any): boolean; - static fromExtendedJSON(doc: any): ObjectId; - constructor(inputId: any); - get _bsontype(): string; - __id: any; - set id(value: any); - get id(): any; - toHexString(): any; - toString(encoding: any): any; - toJSON(): any; - equals(otherId: any): any; - getTimestamp(): Date; - toExtendedJSON(): { - $oid: any; - }; - inspect(): string; - [kId]: any; -} -export namespace ObjectId { - let index: number; -} -export class Timestamp extends Long { - static fromInt(value: any): Timestamp; - static fromNumber(value: any): Timestamp; - static fromBits(lowBits: any, highBits: any): Timestamp; - static fromString(str: any, optRadix: any): Timestamp; - static fromExtendedJSON(doc: any): Timestamp; - constructor(low: any); - toJSON(): { - $timestamp: any; - }; - toExtendedJSON(): { - $timestamp: { - t: number; - i: number; - }; - }; -} -export namespace Timestamp { - import MAX_VALUE_1 = Long.MAX_UNSIGNED_VALUE; - export { MAX_VALUE_1 as MAX_VALUE }; -} -export class UUID extends Binary { - static generate(): any; - static isValid(input: any): boolean; - static createFromHexString(hexString: any): UUID; - constructor(input: any); - __id: any; - set id(value: any); - get id(): any; - toHexString(includeDashes?: boolean): any; - equals(otherId: any): any; - toBinary(): Binary; -} -export function calculateObjectSize(object: any, options?: {}): number; -export function deserialize(buffer: any, options?: {}): {}; -export function deserializeStream(data: any, startIndex: any, numberOfDocuments: any, documents: any, docStartIndex: any, options: any): any; -export function serialize(object: any, options?: {}): any; -export function serializeWithBufferAndIndex(object: any, finalBuffer: any, options?: {}): number; -export function setInternalBufferSize(size: any): void; -declare const kId: unique symbol; -export { bson as BSON }; diff --git a/src/extras/dist/extras/struct/datastructures/index.d.ts b/src/extras/dist/extras/struct/datastructures/index.d.ts deleted file mode 100644 index 07efe2c4..00000000 --- a/src/extras/dist/extras/struct/datastructures/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './DataStructures'; -export * from './DataTablet'; -export * as DS from './DataStructures'; diff --git a/src/extras/dist/extras/struct/datastructures/types.d.ts b/src/extras/dist/extras/struct/datastructures/types.d.ts deleted file mode 100644 index ddb01f54..00000000 --- a/src/extras/dist/extras/struct/datastructures/types.d.ts +++ /dev/null @@ -1,243 +0,0 @@ -export type ArbitraryObject = { - [x: string | number]: any; -}; -export type Struct = { - _id: string; - structType?: string | number; - timestamp?: string | number; - ownerId?: string | number; - parent?: { - structType: string; - _id: string | number; - }; - [key: string]: any; -}; -export type DataTypes = 'byTime' | 'notes' | 'events' | 'sleep' | 'food' | 'rx' | 'hr' | 'ppg' | 'hrv' | 'ecg' | 'emg' | 'eeg' | 'fnirs' | string | number | undefined; -export type StructTypes = LooseStructTypes | DataTypes | 'data' | 'struct' | string | number | undefined; -export type LooseStructTypes = 'coherence' | 'imu' | 'eyetracker' | 'profile' | 'authorization' | 'group' | 'event' | 'chatroom' | 'comment' | 'notification' | 'schedule' | 'date' | string | number | undefined; -export type Data = { - type: string; - data: any; - timestamp?: string | number; -}; -export type DataStruct = { - title?: string; - author?: string; - expires: boolean | number | string; - type: string; - data: Data[]; - tag?: string | number; -} & Struct; -export type EventStruct = { - event: string; - author: string; - startTime: string; - endTime?: string; - grade?: string | number; - value?: any; - units?: string; - notes?: string; - location?: any; - attachments?: Data | string | number[]; - users?: { - [key: string]: true; - }; - tag?: string | number; -} & Struct; -export type ChatroomStruct = { - message: string; - topic: string; - author: string; - attachments: Data | string | number[]; - comments: string[]; - replies: string[]; - users: { - [key: string]: true; - }; - audioChatActive: boolean; - videoChatActive: boolean; - tag?: string | number; -} & Struct; -export type CommentStruct = { - author: string; - replyTo: string; - attachments: Data | string | number[]; - replies: string[]; - users: { - [key: string]: true; - }; - tag?: string | number; -} & Struct; -export type NotificationStruct = { - note: string; - parentUserId: string; - tag?: string | number; -} & Struct; -export type ScheduleStruct = { - title: string; - author: string; - attachments: Data | string | number[]; - dates: string[]; - tag?: string | number; -} & Struct; -export type DateStruct = { - timeSet: string | number; - notes: string; - recurs: number | string | boolean; - attachments: Data | string | number[]; - tag?: string | number; -} & Struct; -export type ProfileStruct = { - username?: string; - name?: string; - firstName?: string; - lastName?: string; - fullName?: string; - email?: string; - phone?: string; - sex?: string; - birthday?: string; - userRoles?: {}; - socials?: {}; - data?: {}; - type?: string; - hidden?: boolean; - pictureUrl: string; - accessToken?: string; - refreshToken?: string; - tag?: string | number; -} & Struct; -export type AuthorizationStruct = { - authorizedId: string; - authorizedName: string; - authorizerId: string; - authorizerName: string; - authorizations: {}; - structs: {}; - excluded: {}; - groups: {}; - status: "PENDING" | "OKAY"; - expires: string | boolean; - associatedAuthId: string | number; - tag?: string | number; -} & Struct; -export type GroupStruct = { - name: string; - details: string; - admins: {}; - peers: {}; - clients: {}; - users: {}; - tag?: string | number; -} & Struct; -type FreqBand = [number[], number[]]; -export type FrequencyBandNames = 'scp' | 'delta' | 'theta' | 'alpha1' | 'alpha2' | 'beta' | 'lowgamma' | 'highgamma'; -export type FrequencyBandsStruct = { - scp: FreqBand | []; - delta: FreqBand | []; - theta: FreqBand | []; - alpha1: FreqBand | []; - alpha2: FreqBand | []; - beta: FreqBand | []; - lowgamma: FreqBand | []; - highgamma: FreqBand | []; -}; -export type EEGStruct = { - position: { - x: number; - y: number; - z: number; - }; - count: number; - times: number[]; - raw: number[]; - filtered: number[]; - fftCount: number; - fftTimes: number[]; - ffts: [][]; - slices: FrequencyBandsStruct; - means: FrequencyBandsStruct; - startTime: number | string; - tag?: string | number; -} & Struct; -export type CoherenceStruct = { - x0: number; - y0: number; - z0: number; - x1: number; - y1: number; - z1: number; - fftCount: number; - fftTimes: number[]; - ffts: [][]; - slices: FrequencyBandsStruct; - means: FrequencyBandsStruct; - startTime: number | string; - tag?: string | number; -} & Struct; -export type FNIRSStruct = { - position: { - x: number; - y: number; - z: number; - }; - count: number; - times: number[]; - red: number[]; - ir: number[]; - ir2: number[]; - ambient: number[]; - ratio: number[]; - temp: number[]; - beat_detect: { - beats: any[]; - breaths: any[]; - rir: any[]; - rir2: any[]; - drir_dt: any[]; - localmins: any[]; - localmaxs: any[]; - val_dists: any[]; - peak_dists: any[]; - localmins2: any[]; - localmaxs2: any[]; - val_dists2: any[]; - peak_dists2: any[]; - }; - startTime: number | string; - tag?: string | number; -} & Struct; -export type IMUStruct = { - Ax: number[]; - Ay: number[]; - Az: number[]; - Gx: number[]; - Gy: number[]; - Gz: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type EyeTrackerStruct = { - count: number; - times: number[]; - x: number[]; - y: number[]; - smax: number[]; - smay: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type ECGStruct = { - count: number; - times: number[]; - raw: number[]; - filtered: number[]; - bpm: number[]; - hrv: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type PPGStruct = FNIRSStruct; -export type HRVStruct = ECGStruct; -export type EMGStruct = EEGStruct; -export {}; diff --git a/src/extras/dist/extras/struct/genTimestamps.d.ts b/src/extras/dist/extras/struct/genTimestamps.d.ts deleted file mode 100644 index 69253e3d..00000000 --- a/src/extras/dist/extras/struct/genTimestamps.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type TimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' | 'decade' | 'century' | 'millennium' | 'microsecond' | 'nanosecond'; -type Plural = `${T}s`; -export type TimeSpecifier = `now` | `last ${string} ${Plural}` | `last ${TimeUnit}`; -export declare let defaultSpecifiers: (TimeUnit | "now")[]; -export declare function genTimeSpecifiers(specifiers?: (TimeUnit | "now")[]): string[]; -export declare function genTimestampFromString(specifier: TimeSpecifier): number; -export {}; diff --git a/src/extras/dist/extras/webgl-plot/webglplot.routes.d.ts b/src/extras/dist/extras/webgl-plot/webglplot.routes.d.ts deleted file mode 100644 index 26ef2e6b..00000000 --- a/src/extras/dist/extras/webgl-plot/webglplot.routes.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { WorkerInfo } from '../../services/worker/Worker.service'; -import { WebglLinePlotInfo, WebglLinePlotProps, WebglLinePlotUtil, WebglLineProps } from "webgl-plot-utils"; -import { FilterSettings } from "../algorithms/util/BiquadFilters"; -export { WebglLinePlotUtil, WebglLineProps, WebglLinePlotProps, WebglLinePlotInfo }; -export declare const webglPlotRoutes: { - setupChart: (settings: WebglLinePlotProps) => any; - updateChartData: (plot: WebglLinePlotInfo | string, lines?: { - [key: string]: number[] | WebglLineProps | { - [key: string]: any; - values: number[]; - }; - }, draw?: boolean) => boolean; - clearChart: (plot: WebglLinePlotInfo | string) => boolean; - resetChart: (plot: WebglLinePlotInfo | string, settings: WebglLinePlotProps) => any; - getChartSettings: (plotId: any) => any; -}; -export declare function setSignalControls(controlsDiv: HTMLElement, plotId: string, streamworker: WorkerInfo, chartworker: WorkerInfo, chartSettings: Partial, filterSettings: FilterSettings): Promise; diff --git a/src/extras/dist/index.gpu.services.d.ts b/src/extras/dist/index.gpu.services.d.ts deleted file mode 100644 index ab57cca9..00000000 --- a/src/extras/dist/index.gpu.services.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './extras/gpu/GPU.service'; -export { gpualgorithms } from './extras/algorithms/index.gpu'; diff --git a/src/extras/dist/index.gpu.services.esm.js b/src/extras/dist/index.gpu.services.esm.js deleted file mode 100644 index cdca3039..00000000 --- a/src/extras/dist/index.gpu.services.esm.js +++ /dev/null @@ -1,1300 +0,0 @@ -var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value2)=>{this.data[key]=value2;this.triggerEvent(key,value2)};triggerEvent=(key,value2)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value2)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub2=>{return this.unsubscribeEvent(statesubKey,sub2)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value2=>{refObject[refKey]=value2},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub2)=>{let triggers=this.triggers[key];if(triggers){if(sub2===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub2;let changed=value2=>{onchange(value2);this.unsubscribeEvent(key,sub2)};sub2=this.subscribeEvent(key,changed);return sub2};getEvent=(key,sub2)=>{if(typeof sub2!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub2)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value2,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value2,receiver)}return Reflect.set(target,prop,value2,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub2=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub2);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub2;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub2};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub2;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub2}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub2;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub2}};__unsubscribe=(sub2,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub2)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub2)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub2=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub2);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value2=>{obj[k]=value2},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub2=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub2)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub2;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub2)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub2)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub2;if(nd instanceof GraphNode){const doSub=()=>{sub2=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)nd.__unsubscribe(sub2,key,subInput);sub2=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub2===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub2=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub2=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput);sub2=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub2=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub2};unsubscribe=(node,sub2,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub2,key,subInput)}else return this.get(node)?.__unsubscribe(sub2,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require2=(x2=>typeof __require!=="undefined"?__require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof __require!=="undefined"?__require:a)[b]}):x2)(function(x2){if(typeof __require!=="undefined")return __require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require22(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_gpu_browser_min=__commonJS({"src/gpu-browser.min.js"(exports,module){"use strict";(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}f()}})(function(){var define2,module2,exports2;return function(){function r(e,n,t){function o(i2,f){if(!n[i2]){if(!e[i2]){var c="function"==typeof __require2&&__require2;if(!f&&c)return c(i2,true);if(u)return u(i2,true);var a=new Error("Cannot find module '"+i2+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i2]={exports:{}};e[i2][0].call(p.exports,function(r2){var n2=e[i2][1][r2];return o(n2||r2)},p,p.exports,r,e,n,t)}return n[i2].exports}for(var u="function"==typeof __require2&&__require2,i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType2(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name2,prec){return new TokenType(name2,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name2,options){if(options===void 0)options={};options.keyword=name2;return keywords$1[name2]=new TokenType(name2,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position2(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation2(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start,end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser2(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse2(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports5);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports5){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports5,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports5,node.declaration.declarations)}else{this.checkExport(exports5,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports5);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value2=this.value;node=this.parseLiteral(value2.value);node.regex={pattern:value2.pattern,flags:value2.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value2){var node=this.startNode();node.value=value2;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref2){var isTagged=ref2.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref2){if(ref2===void 0)ref2={};var isTagged=ref2.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name2)>-1||scope.var.indexOf(name2)>-1;scope.lexical.push(name2);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name2]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name2)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name2)>-1}else{redeclared=scope$2.lexical.indexOf(name2)>-1||scope$2.var.indexOf(name2)>-1}scope$2.functions.push(name2)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name2)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name2)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name2)>-1){redeclared=true;break}scope$3.var.push(name2);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name2]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name2+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node2(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext2(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat){return true}if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr)){return!parent.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState2(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state2){var validFlags=state2.validFlags;var flags=state2.flags;for(var i=0;i-1){this.raise(state2.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state2){this.regexp_pattern(state2);if(!state2.switchN&&this.options.ecmaVersion>=9&&state2.groupNames.length>0){state2.switchN=true;this.regexp_pattern(state2)}};pp$8.regexp_pattern=function(state2){state2.pos=0;state2.lastIntValue=0;state2.lastStringValue="";state2.lastAssertionIsQuantifiable=false;state2.numCapturingParens=0;state2.maxBackReference=0;state2.groupNames.length=0;state2.backReferenceNames.length=0;this.regexp_disjunction(state2);if(state2.pos!==state2.source.length){if(state2.eat(41)){state2.raise("Unmatched ')'")}if(state2.eat(93)||state2.eat(125)){state2.raise("Lone quantifier brackets")}}if(state2.maxBackReference>state2.numCapturingParens){state2.raise("Invalid escape")}for(var i=0,list=state2.backReferenceNames;i=9){lookbehind=state2.eat(60)}if(state2.eat(61)||state2.eat(33)){this.regexp_disjunction(state2);if(!state2.eat(41)){state2.raise("Unterminated group")}state2.lastAssertionIsQuantifiable=!lookbehind;return true}}state2.pos=start;return false};pp$8.regexp_eatQuantifier=function(state2,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state2,noError)){state2.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state2,noError){return state2.eat(42)||state2.eat(43)||state2.eat(63)||this.regexp_eatBracedQuantifier(state2,noError)};pp$8.regexp_eatBracedQuantifier=function(state2,noError){var start=state2.pos;if(state2.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state2)){min=state2.lastIntValue;if(state2.eat(44)&&this.regexp_eatDecimalDigits(state2)){max=state2.lastIntValue}if(state2.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state2)}else if(state2.current()===63){state2.raise("Invalid group")}this.regexp_disjunction(state2);if(state2.eat(41)){state2.numCapturingParens+=1;return true}state2.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state2){return state2.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state2)||this.regexp_eatCharacterClass(state2)||this.regexp_eatUncapturingGroup(state2)||this.regexp_eatCapturingGroup(state2)||this.regexp_eatInvalidBracedQuantifier(state2)||this.regexp_eatExtendedPatternCharacter(state2)};pp$8.regexp_eatInvalidBracedQuantifier=function(state2){if(this.regexp_eatBracedQuantifier(state2,true)){state2.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state2){var ch=state2.current();if(isSyntaxCharacter(ch)){state2.lastIntValue=ch;state2.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state2){var start=state2.pos;var ch=0;while((ch=state2.current())!==-1&&!isSyntaxCharacter(ch)){state2.advance()}return state2.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state2){var ch=state2.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state2.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state2){if(state2.eat(63)){if(this.regexp_eatGroupName(state2)){if(state2.groupNames.indexOf(state2.lastStringValue)!==-1){state2.raise("Duplicate capture group name")}state2.groupNames.push(state2.lastStringValue);return}state2.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state2){state2.lastStringValue="";if(state2.eat(60)){if(this.regexp_eatRegExpIdentifierName(state2)&&state2.eat(62)){return true}state2.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state2){state2.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierStart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierPart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state2){if(this.regexp_eatBackReference(state2)||this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)||state2.switchN&&this.regexp_eatKGroupName(state2)){return true}if(state2.switchU){if(state2.current()===99){state2.raise("Invalid unicode escape")}state2.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state2){var start=state2.pos;if(this.regexp_eatDecimalEscape(state2)){var n=state2.lastIntValue;if(state2.switchU){if(n>state2.maxBackReference){state2.maxBackReference=n}return true}if(n<=state2.numCapturingParens){return true}state2.pos=start}return false};pp$8.regexp_eatKGroupName=function(state2){if(state2.eat(107)){if(this.regexp_eatGroupName(state2)){state2.backReferenceNames.push(state2.lastStringValue);return true}state2.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state2){return this.regexp_eatControlEscape(state2)||this.regexp_eatCControlLetter(state2)||this.regexp_eatZero(state2)||this.regexp_eatHexEscapeSequence(state2)||this.regexp_eatRegExpUnicodeEscapeSequence(state2)||!state2.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state2)||this.regexp_eatIdentityEscape(state2)};pp$8.regexp_eatCControlLetter=function(state2){var start=state2.pos;if(state2.eat(99)){if(this.regexp_eatControlLetter(state2)){return true}state2.pos=start}return false};pp$8.regexp_eatZero=function(state2){if(state2.current()===48&&!isDecimalDigit(state2.lookahead())){state2.lastIntValue=0;state2.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state2){var ch=state2.current();if(ch===116){state2.lastIntValue=9;state2.advance();return true}if(ch===110){state2.lastIntValue=10;state2.advance();return true}if(ch===118){state2.lastIntValue=11;state2.advance();return true}if(ch===102){state2.lastIntValue=12;state2.advance();return true}if(ch===114){state2.lastIntValue=13;state2.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state2){var ch=state2.current();if(isControlLetter(ch)){state2.lastIntValue=ch%32;state2.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(117)){if(this.regexp_eatFixedHexDigits(state2,4)){var lead=state2.lastIntValue;if(state2.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state2.pos;if(state2.eat(92)&&state2.eat(117)&&this.regexp_eatFixedHexDigits(state2,4)){var trail=state2.lastIntValue;if(trail>=56320&&trail<=57343){state2.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state2.pos=leadSurrogateEnd;state2.lastIntValue=lead}return true}if(state2.switchU&&state2.eat(123)&&this.regexp_eatHexDigits(state2)&&state2.eat(125)&&isValidUnicode(state2.lastIntValue)){return true}if(state2.switchU){state2.raise("Invalid unicode escape")}state2.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state2){if(state2.switchU){if(this.regexp_eatSyntaxCharacter(state2)){return true}if(state2.eat(47)){state2.lastIntValue=47;return true}return false}var ch=state2.current();if(ch!==99&&(!state2.switchN||ch!==107)){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state2){state2.lastIntValue=0;var ch=state2.current();if(ch>=49&&ch<=57){do{state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}while((ch=state2.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state2){var ch=state2.current();if(isCharacterClassEscape(ch)){state2.lastIntValue=-1;state2.advance();return true}if(state2.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state2.lastIntValue=-1;state2.advance();if(state2.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state2)&&state2.eat(125)){return true}state2.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state2){var start=state2.pos;if(this.regexp_eatUnicodePropertyName(state2)&&state2.eat(61)){var name2=state2.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state2)){var value2=state2.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state2,name2,value2);return true}}state2.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state2)){var nameOrValue=state2.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state2,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state2,name2,value2){if(!has(state2.unicodeProperties.nonBinary,name2)){state2.raise("Invalid property name")}if(!state2.unicodeProperties.nonBinary[name2].test(value2)){state2.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state2,nameOrValue){if(!state2.unicodeProperties.binary.test(nameOrValue)){state2.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state2){return this.regexp_eatUnicodePropertyValue(state2)};pp$8.regexp_eatCharacterClass=function(state2){if(state2.eat(91)){state2.eat(94);this.regexp_classRanges(state2);if(state2.eat(93)){return true}state2.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state2){while(this.regexp_eatClassAtom(state2)){var left=state2.lastIntValue;if(state2.eat(45)&&this.regexp_eatClassAtom(state2)){var right=state2.lastIntValue;if(state2.switchU&&(left===-1||right===-1)){state2.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state2.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state2){var start=state2.pos;if(state2.eat(92)){if(this.regexp_eatClassEscape(state2)){return true}if(state2.switchU){var ch$1=state2.current();if(ch$1===99||isOctalDigit(ch$1)){state2.raise("Invalid class escape")}state2.raise("Invalid escape")}state2.pos=start}var ch=state2.current();if(ch!==93){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state2){var start=state2.pos;if(state2.eat(98)){state2.lastIntValue=8;return true}if(state2.switchU&&state2.eat(45)){state2.lastIntValue=45;return true}if(!state2.switchU&&state2.eat(99)){if(this.regexp_eatClassControlLetter(state2)){return true}state2.pos=start}return this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)};pp$8.regexp_eatClassControlLetter=function(state2){var ch=state2.current();if(isDecimalDigit(ch)||ch===95){state2.lastIntValue=ch%32;state2.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(120)){if(this.regexp_eatFixedHexDigits(state2,2)){return true}if(state2.switchU){state2.raise("Invalid escape")}state2.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isDecimalDigit(ch=state2.current())){state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}return state2.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isHexDigit(ch=state2.current())){state2.lastIntValue=16*state2.lastIntValue+hexToInt(ch);state2.advance()}return state2.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state2){if(this.regexp_eatOctalDigit(state2)){var n1=state2.lastIntValue;if(this.regexp_eatOctalDigit(state2)){var n2=state2.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state2)){state2.lastIntValue=n1*64+n2*8+state2.lastIntValue}else{state2.lastIntValue=n1*8+n2}}else{state2.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state2){var ch=state2.current();if(isOctalDigit(ch)){state2.lastIntValue=ch-48;state2.advance();return true}state2.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state2,length){var start=state2.pos;state2.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state2=this.regexpState||(this.regexpState=new RegExpValidationState(this));state2.reset(start,pattern,flags);this.validateRegExpFlags(state2);this.validateRegExpPattern(state2);var value2=null;try{value2=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern,flags,value:value2})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos0){recording.pop()}}function insertVariable(name2,value2){variables[name2]=value2}function getEntity(value2){const name2=entityNames[value2];if(name2){return contextName+"."+name2}return value2}function setIndent(spaces){indent=" ".repeat(spaces)}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;recording.push(`${indent}const ${variableName} = ${source};`);contextVariables.push(value2);return variableName}function writePPM(width,height){const sourceVariable=`${contextName}Variable${contextVariables.length}`;const imageVariable=`imageDatum${imageCount}`;recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`);recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`);recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`);recording.push(`${indent}}`);recording.push(`${indent}if (typeof require !== "undefined") {`);recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`);recording.push(`${indent}}`);imageCount++}function addComment(value2){recording.push(`${indent}// ${value2}`)}function checkThrowError(){recording.push(`${indent}(() => { - ${indent}const error = ${contextName}.getError(); - ${indent}if (error !== ${contextName}.NONE) { - ${indent} const names = Object.getOwnPropertyNames(gl); - ${indent} for (let i = 0; i < names.length; i++) { - ${indent} const name = names[i]; - ${indent} if (${contextName}[name] === error) { - ${indent} throw new Error('${contextName} threw ' + name); - ${indent} } - ${indent} } - ${indent}} - ${indent}})();`)}function methodCallToString(method,args){return`${contextName}.${method}(${argumentsToString(args,{contextName,contextVariables,getEntity,addVariable,variables,onUnrecognizedArgumentLookup})})`}function getVariableName(value2){if(variables){for(const name2 in variables){if(variables[name2]===value2){return name2}}}return null}function getContextVariableName(value2){const i=contextVariables.indexOf(value2);if(i!==-1){return`${contextName}Variable${i}`}return null}}function glExtensionWiretap(extension,options){const proxy=new Proxy(extension,{get:listen});const extensionEntityNames={};const{contextName,contextVariables,getEntity,useTrackablePrimitives,recording,variables,indent,onUnrecognizedArgumentLookup}=options;return proxy;function listen(obj,property){if(typeof obj[property]==="function"){return function(){switch(property){case"drawBuffersWEBGL":recording.push(`${indent}${contextName}.drawBuffersWEBGL([${argumentsToString(arguments[0],{contextName,contextVariables,getEntity:getExtensionEntity,addVariable,variables,onUnrecognizedArgumentLookup})}]);`);return extension.drawBuffersWEBGL(arguments[0])}let result=extension[property].apply(extension,arguments);switch(typeof result){case"undefined":recording.push(`${indent}${methodCallToString(property,arguments)};`);return;case"number":case"boolean":if(useTrackablePrimitives&&contextVariables.indexOf(trackablePrimitive(result))===-1){recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property,arguments)};`);contextVariables.push(result=trackablePrimitive(result))}else{recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property,arguments)};`);contextVariables.push(result)}break;default:if(result===null){recording.push(`${methodCallToString(property,arguments)};`)}else{recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property,arguments)};`)}contextVariables.push(result)}return result}}extensionEntityNames[extension[property]]=property;return extension[property]}function getExtensionEntity(value2){if(extensionEntityNames.hasOwnProperty(value2)){return`${contextName}.${extensionEntityNames[value2]}`}return getEntity(value2)}function methodCallToString(method,args){return`${contextName}.${method}(${argumentsToString(args,{contextName,contextVariables,getEntity:getExtensionEntity,addVariable,variables,onUnrecognizedArgumentLookup})})`}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;contextVariables.push(value2);recording.push(`${indent}const ${variableName} = ${source};`);return variableName}}function argumentsToString(args,options){const{variables,onUnrecognizedArgumentLookup}=options;return Array.from(args).map(arg=>{const variableName=getVariableName(arg);if(variableName){return variableName}return argumentToString(arg,options)}).join(", ");function getVariableName(value2){if(variables){for(const name2 in variables){if(!variables.hasOwnProperty(name2))continue;if(variables[name2]===value2){return name2}}}if(onUnrecognizedArgumentLookup){return onUnrecognizedArgumentLookup(value2)}return null}}function argumentToString(arg,options){const{contextName,contextVariables,getEntity,addVariable,onUnrecognizedArgumentLookup}=options;if(typeof arg==="undefined"){return"undefined"}if(arg===null){return"null"}const i=contextVariables.indexOf(arg);if(i>-1){return`${contextName}Variable${i}`}switch(arg.constructor.name){case"String":const hasLines=/\n/.test(arg);const hasSingleQuotes=/'/.test(arg);const hasDoubleQuotes=/"/.test(arg);if(hasLines){return"`"+arg+"`"}else if(hasSingleQuotes&&!hasDoubleQuotes){return'"'+arg+'"'}else if(!hasSingleQuotes&&hasDoubleQuotes){return"'"+arg+"'"}else{return"'"+arg+"'"}case"Number":return getEntity(arg);case"Boolean":return getEntity(arg);case"Array":return addVariable(arg,`new ${arg.constructor.name}([${Array.from(arg).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return addVariable(arg,`new ${arg.constructor.name}(${JSON.stringify(Array.from(arg))})`);default:if(onUnrecognizedArgumentLookup){const instantiationString=onUnrecognizedArgumentLookup(arg);if(instantiationString){return instantiationString}}throw new Error(`unrecognized argument type ${arg.constructor.name}`)}}function trackablePrimitive(value2){return new value2.constructor(value2)}if(typeof module3!=="undefined"){module3.exports={glWiretap,glExtensionWiretap}}if(typeof window!=="undefined"){glWiretap.glExtensionWiretap=glExtensionWiretap;window.glWiretap=glWiretap}},{}],4:[function(require2,module3,exports3){function setupArguments(args){const newArguments=new Array(args.length);for(let i=0;i{kernel.output=setupOutput(output);if(kernel.graphical){setupGraphical(kernel)}};kernel.toJSON=()=>{throw new Error("Not usable with gpuMock")};kernel.setConstants=flag=>{kernel.constants=flag;return kernel};kernel.setGraphical=flag=>{kernel.graphical=flag;return kernel};kernel.setCanvas=flag=>{kernel.canvas=flag;return kernel};kernel.setContext=flag=>{kernel.context=flag;return kernel};kernel.destroy=()=>{};kernel.validateSettings=()=>{};if(kernel.graphical&&kernel.output){setupGraphical(kernel)}kernel.exec=function(){return new Promise((resolve,reject)=>{try{resolve(kernel.apply(kernel,arguments))}catch(e){reject(e)}})};kernel.getPixels=flip=>{const{x:x2,y}=kernel.output;return flip?flipPixels(kernel._imageData.data,x2,y):kernel._imageData.data.slice(0)};kernel.color=function(r,g,b,a){if(typeof a==="undefined"){a=1}r=Math.floor(r*255);g=Math.floor(g*255);b=Math.floor(b*255);a=Math.floor(a*255);const width=kernel.output.x;const height=kernel.output.y;const x2=kernel.thread.x;const y=height-kernel.thread.y-1;const index=x2+y*width;kernel._colorData[index*4+0]=r;kernel._colorData[index*4+1]=g;kernel._colorData[index*4+2]=b;kernel._colorData[index*4+3]=a};const mockMethod=()=>kernel;const methods=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let i=0;i0){retArr.push(", ")}retArr.push("user_");retArr.push(argumentName)}retArr.push(") {\n")}for(let i=0;i0){retArr.push(initArr.join(""),";\n")}retArr.push(`for (let ${iVariableName}=0;${iVariableName}0){retArr.push(`if (!${testArr.join("")}) break; -`)}retArr.push(bodyArr.join(""));retArr.push(` -${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whileNode,retArr){if(whileNode.type!=="WhileStatement"){throw this.astErrorOutput("Invalid while statement",whileNode)}retArr.push("for (let i = 0; i < LOOP_MAX; i++) {");retArr.push("if (");this.astGeneric(whileNode.test,retArr);retArr.push(") {\n");this.astGeneric(whileNode.body,retArr);retArr.push("} else {\n");retArr.push("break;\n");retArr.push("}\n");retArr.push("}\n");return retArr}astDoWhileStatement(doWhileNode,retArr){if(doWhileNode.type!=="DoWhileStatement"){throw this.astErrorOutput("Invalid while statement",doWhileNode)}retArr.push("for (let i = 0; i < LOOP_MAX; i++) {");this.astGeneric(doWhileNode.body,retArr);retArr.push("if (!");this.astGeneric(doWhileNode.test,retArr);retArr.push(") {\n");retArr.push("break;\n");retArr.push("}\n");retArr.push("}\n");return retArr}astAssignmentExpression(assNode,retArr){const declaration=this.getDeclaration(assNode.left);if(declaration&&!declaration.assignable){throw this.astErrorOutput(`Variable ${assNode.left.name} is not assignable here`,assNode)}this.astGeneric(assNode.left,retArr);retArr.push(assNode.operator);this.astGeneric(assNode.right,retArr);return retArr}astBlockStatement(bNode,retArr){if(this.isState("loop-body")){this.pushState("block-body");for(let i=0;i0){retArr.push(",")}const declaration=declarations[i];const info=this.getDeclaration(declaration.id);if(!info.valueType){info.valueType=this.getType(declaration.init)}this.astGeneric(declaration,retArr)}if(!this.isState("in-for-loop-init")){retArr.push(";")}return retArr}astIfStatement(ifNode,retArr){retArr.push("if (");this.astGeneric(ifNode.test,retArr);retArr.push(")");if(ifNode.consequent.type==="BlockStatement"){this.astGeneric(ifNode.consequent,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.consequent,retArr);retArr.push("\n}\n")}if(ifNode.alternate){retArr.push("else ");if(ifNode.alternate.type==="BlockStatement"||ifNode.alternate.type==="IfStatement"){this.astGeneric(ifNode.alternate,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.alternate,retArr);retArr.push("\n}\n")}}return retArr}astSwitchStatement(ast,retArr){const{discriminant,cases}=ast;retArr.push("switch (");this.astGeneric(discriminant,retArr);retArr.push(") {\n");for(let i=0;i0){retArr.push("break;\n")}continue}retArr.push("case ");this.astGeneric(cases[i].test,retArr);retArr.push(":\n");if(cases[i].consequent&&cases[i].consequent.length>0){this.astGeneric(cases[i].consequent,retArr);retArr.push("break;\n")}}retArr.push("\n}")}astThisExpression(tNode,retArr){retArr.push("_this");return retArr}astMemberExpression(mNode,retArr){const{signature,type,property,xProperty,yProperty,zProperty,name:name2,origin}=this.getMemberExpressionDetails(mNode);switch(signature){case"this.thread.value":retArr.push(`_this.thread.${name2}`);return retArr;case"this.output.value":switch(name2){case"x":retArr.push("outputX");break;case"y":retArr.push("outputY");break;case"z":retArr.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",mNode)}return retArr;case"value":throw this.astErrorOutput("Unexpected expression",mNode);case"value[]":case"value[][]":case"value[][][]":case"value.value":if(origin==="Math"){retArr.push(Math[name2]);return retArr}switch(property){case"r":retArr.push(`user_${name2}[0]`);return retArr;case"g":retArr.push(`user_${name2}[1]`);return retArr;case"b":retArr.push(`user_${name2}[2]`);return retArr;case"a":retArr.push(`user_${name2}[3]`);return retArr}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":this.astGeneric(mNode.object,retArr);retArr.push("[");this.astGeneric(mNode.property,retArr);retArr.push("]");return retArr;case"fn()[][]":this.astGeneric(mNode.object.object,retArr);retArr.push("[");this.astGeneric(mNode.object.property,retArr);retArr.push("]");retArr.push("[");this.astGeneric(mNode.property,retArr);retArr.push("]");return retArr;default:throw this.astErrorOutput("Unexpected expression",mNode)}if(!mNode.computed){switch(type){case"Number":case"Integer":case"Float":case"Boolean":retArr.push(`${origin}_${name2}`);return retArr}}const markupName=`${origin}_${name2}`;switch(type){case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":case"HTMLImageArray":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"HTMLImage":default:let size;let isInput;if(origin==="constants"){const constant=this.constants[name2];isInput=this.constantTypes[name2]==="Input";size=isInput?constant.size:null}else{isInput=this.isInput(name2);size=isInput?this.argumentSizes[this.argumentNames.indexOf(name2)]:null}retArr.push(`${markupName}`);if(zProperty&&yProperty){if(isInput){retArr.push("[(");this.astGeneric(zProperty,retArr);retArr.push(`*${this.dynamicArguments?"(outputY * outputX)":size[1]*size[0]})+(`);this.astGeneric(yProperty,retArr);retArr.push(`*${this.dynamicArguments?"outputX":size[0]})+`);this.astGeneric(xProperty,retArr);retArr.push("]")}else{retArr.push("[");this.astGeneric(zProperty,retArr);retArr.push("]");retArr.push("[");this.astGeneric(yProperty,retArr);retArr.push("]");retArr.push("[");this.astGeneric(xProperty,retArr);retArr.push("]")}}else if(yProperty){if(isInput){retArr.push("[(");this.astGeneric(yProperty,retArr);retArr.push(`*${this.dynamicArguments?"outputX":size[0]})+`);this.astGeneric(xProperty,retArr);retArr.push("]")}else{retArr.push("[");this.astGeneric(yProperty,retArr);retArr.push("]");retArr.push("[");this.astGeneric(xProperty,retArr);retArr.push("]")}}else if(typeof xProperty!=="undefined"){retArr.push("[");this.astGeneric(xProperty,retArr);retArr.push("]")}}return retArr}astCallExpression(ast,retArr){if(ast.type!=="CallExpression"){throw this.astErrorOutput("Unknown CallExpression",ast)}let functionName=this.astMemberExpressionUnroll(ast.callee);if(this.calledFunctions.indexOf(functionName)<0){this.calledFunctions.push(functionName)}const isMathFunction=this.isAstMathFunction(ast);if(this.onFunctionCall){this.onFunctionCall(this.name,functionName,ast.arguments)}retArr.push(functionName);retArr.push("(");const targetTypes=this.lookupFunctionArgumentTypes(functionName)||[];for(let i=0;i0){retArr.push(", ")}this.astGeneric(argument,retArr)}retArr.push(")");return retArr}astArrayExpression(arrNode,retArr){const returnType=this.getType(arrNode);const arrLen=arrNode.elements.length;const elements=[];for(let i=0;i{switch(propertyName){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(cpuKernel[propertyName])},findDependency:(object,name3)=>{return null}});const getPixelsFn=utils.flattenFunctionToString((useFunctionKeyword?"function ":"")+cpuKernel.getPixels.toString(),{thisLookup:propertyName=>{switch(propertyName){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(cpuKernel[propertyName])},findDependency:()=>{return null}});thisProperties.push(" _imageData,"," _colorData,",` color: ${colorFn},`);beforeReturn.push(` kernel.getPixels = ${getPixelsFn};`)}const constantTypes=[];const constantKeys=Object.keys(cpuKernel.constantTypes);for(let i=0;i{if(object==="this"){return(useFunctionKeyword?"function ":"")+cpuKernel[name3].toString()}return null},thisLookup:propertyName=>{switch(propertyName){case"canvas":return;case"context":return"context"}}});beforeReturn.push(flattenedImageTo3DArray);thisProperties.push(` _mediaTo2DArray,`);thisProperties.push(` _imageTo3DArray,`)}else if(cpuKernel.argumentTypes.indexOf("HTMLImage")!==-1||constantTypes.indexOf("HTMLImage")!==-1){const flattenedImageTo2DArray=utils.flattenFunctionToString((useFunctionKeyword?"function ":"")+cpuKernel._mediaTo2DArray.toString(),{findDependency:(object,name3)=>{return null},thisLookup:propertyName=>{switch(propertyName){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});beforeReturn.push(flattenedImageTo2DArray);thisProperties.push(` _mediaTo2DArray,`)}return`function(settings) { - ${header.join("\n")} - for (const p in _constantTypes) { - if (!_constantTypes.hasOwnProperty(p)) continue; - const type = _constantTypes[p]; - switch (type) { - case 'Number': - case 'Integer': - case 'Float': - case 'Boolean': - case 'Array(2)': - case 'Array(3)': - case 'Array(4)': - case 'Matrix(2)': - case 'Matrix(3)': - case 'Matrix(4)': - if (incomingConstants.hasOwnProperty(p)) { - console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned'); - } - continue; - } - if (!incomingConstants.hasOwnProperty(p)) { - throw new Error('constant ' + p + ' not found'); - } - _constants[p] = incomingConstants[p]; - } - const kernel = (function() { - ${cpuKernel._kernelString} - }) - .apply({ ${thisProperties.join("\n")} }); - ${beforeReturn.join("\n")} - return kernel; - }`}module3.exports={cpuKernelString}},{"../../utils":114}],8:[function(require2,module3,exports3){const{Kernel}=require2("../kernel");const{FunctionBuilder}=require2("../function-builder");const{CPUFunctionNode}=require2("./function-node");const{utils}=require2("../../utils");const{cpuKernelString}=require2("./kernel-string");class CPUKernel extends Kernel{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:true,isIntegerDivisionAccurate:true})}static get isSupported(){return true}static isContextMatch(context){return false}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(combinedKernel){return combinedKernel}static getSignature(kernel,argumentTypes){return"cpu"+(argumentTypes.length>0?":"+argumentTypes.join(","):"")}constructor(source,settings){super(source,settings);this.mergeSettings(source.settings||settings);this._imageData=null;this._colorData=null;this._kernelString=null;this._prependedString=[];this.thread={x:0,y:0,z:0};this.translatedSources=null}initCanvas(){if(typeof document!=="undefined"){return document.createElement("canvas")}else if(typeof OffscreenCanvas!=="undefined"){return new OffscreenCanvas(0,0)}}initContext(){if(!this.canvas)return null;return this.canvas.getContext("2d")}initPlugins(settings){return[]}validateSettings(args){if(!this.output||this.output.length===0){if(args.length!==1){throw new Error("Auto output only supported for kernels with only one input")}const argType=utils.getVariableType(args[0],this.strictIntegers);if(argType==="Array"){this.output=utils.getDimensions(argType)}else if(argType==="NumberTexture"||argType==="ArrayTexture(4)"){this.output=args[0].output}else{throw new Error("Auto output not supported for input type: "+argType)}}if(this.graphical){if(this.output.length!==2){throw new Error("Output must have 2 dimensions on graphical mode")}}this.checkOutput()}translateSource(){this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ";if(this.subKernels){const followingReturnStatement=[];for(let i=0;i1?`resultX_${name2}[x] = subKernelResult_${name2}; -`:`result_${name2}[x] = subKernelResult_${name2}; -`)}this.followingReturnStatement=followingReturnStatement.join("")}const functionBuilder=FunctionBuilder.fromKernel(this,CPUFunctionNode);this.translatedSources=functionBuilder.getPrototypes("kernel");if(!this.graphical&&!this.returnType){this.returnType=functionBuilder.getKernelResultType()}}build(){if(this.built)return;this.setupConstants();this.setupArguments(arguments);this.validateSettings(arguments);this.translateSource();if(this.graphical){const{canvas,output}=this;if(!canvas){throw new Error("no canvas available for using graphical output")}const width=output[0];const height=output[1]||1;canvas.width=width;canvas.height=height;this._imageData=this.context.createImageData(width,height);this._colorData=new Uint8ClampedArray(width*height*4)}const kernelString=this.getKernelString();this.kernelString=kernelString;if(this.debug){console.log("Function output:");console.log(kernelString)}try{this.run=new Function([],kernelString).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments);this.built=true}color(r,g,b,a){if(typeof a==="undefined"){a=1}r=Math.floor(r*255);g=Math.floor(g*255);b=Math.floor(b*255);a=Math.floor(a*255);const width=this.output[0];const height=this.output[1];const x2=this.thread.x;const y=height-this.thread.y-1;const index=x2+y*width;this._colorData[index*4+0]=r;this._colorData[index*4+1]=g;this._colorData[index*4+2]=b;this._colorData[index*4+3]=a}getKernelString(){if(this._kernelString!==null)return this._kernelString;let kernelThreadString=null;let{translatedSources}=this;if(translatedSources.length>1){translatedSources=translatedSources.filter(fn=>{if(/^function/.test(fn))return fn;kernelThreadString=fn;return false})}else{kernelThreadString=translatedSources.shift()}return this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()}; - ${this.injectedNative||""} - const _this = this; - ${this._resultKernelHeader()} - ${this._processConstants()} - return (${this.argumentNames.map(argumentName=>"user_"+argumentName).join(", ")}) => { - ${this._prependedString.join("")} - ${this._earlyThrows()} - ${this._processArguments()} - ${this.graphical?this._graphicalKernelBody(kernelThreadString):this._resultKernelBody(kernelThreadString)} - ${translatedSources.length>0?translatedSources.join("\n"):""} - };`}toString(){return cpuKernelString(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const result=[];for(let p in this.constants){const type=this.constantTypes[p];switch(type){case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":result.push(` const constants_${p} = this._mediaTo2DArray(this.constants.${p}); -`);break;case"HTMLImageArray":result.push(` const constants_${p} = this._imageTo3DArray(this.constants.${p}); -`);break;case"Input":result.push(` const constants_${p} = this.constants.${p}.value; -`);break;default:result.push(` const constants_${p} = this.constants.${p}; -`)}}return result.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const arrayArguments=[];for(let i=0;i`user_${argumentName} === result_${subKernel.name}`).join(" || ");checks.push(`user_${argumentName} === result${checkSubKernels?` || ${checkSubKernels}`:""}`)}return`if (${checks.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const result=[];for(let i=0;i0?media.width:media.videoWidth;const height=media.height>0?media.height:media.videoHeight;if(canvas.width=0;y--){const row=imageArray[y]=new Array(width);for(let x2=0;x2`const result_${subKernel.name} = new ${constructorString}(outputX); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - this.thread.y = 0; - this.thread.z = 0; - ${kernelString} - }`}_mutableKernel1DResults(){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const result = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new ${constructorString}(outputX); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")}`}_resultMutableKernel1DLoop(kernelString){return` const outputX = _this.output[0]; - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - this.thread.y = 0; - this.thread.z = 0; - ${kernelString} - }`}_resultImmutableKernel2DLoop(kernelString){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const result = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputY); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let y = 0; y < outputY; y++) { - this.thread.z = 0; - this.thread.y = y; - const resultX = result[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = result_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join("")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - }`}_mutableKernel2DResults(){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const result = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputY); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let y = 0; y < outputY; y++) { - const resultX = result[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = result_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join("")} - }`}_resultMutableKernel2DLoop(kernelString){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - for (let y = 0; y < outputY; y++) { - this.thread.z = 0; - this.thread.y = y; - const resultX = result[y]; - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = result_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join("")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - }`}_graphicalKernel2DLoop(kernelString){return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - for (let y = 0; y < outputY; y++) { - this.thread.z = 0; - this.thread.y = y; - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - }`}_resultImmutableKernel3DLoop(kernelString){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const outputZ = _this.output[2]; - const result = new Array(outputZ); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputZ); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let z = 0; z < outputZ; z++) { - this.thread.z = z; - const resultY = result[z] = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const resultY_${subKernel.name} = result_${subKernel.name}[z] = new Array(outputY); -`).join(" ")} - for (let y = 0; y < outputY; y++) { - this.thread.y = y; - const resultX = resultY[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = resultY_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join(" ")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - } - }`}_mutableKernel3DResults(){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const outputZ = _this.output[2]; - const result = new Array(outputZ); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputZ); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let z = 0; z < outputZ; z++) { - const resultY = result[z] = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const resultY_${subKernel.name} = result_${subKernel.name}[z] = new Array(outputY); -`).join(" ")} - for (let y = 0; y < outputY; y++) { - const resultX = resultY[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = resultY_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join(" ")} - } - }`}_resultMutableKernel3DLoop(kernelString){return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const outputZ = _this.output[2]; - for (let z = 0; z < outputZ; z++) { - this.thread.z = z; - const resultY = result[z]; - for (let y = 0; y < outputY; y++) { - this.thread.y = y; - const resultX = resultY[y]; - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - } - }`}_kernelOutput(){if(!this.subKernels){return"\n return result;"}return` - return { - result: result, - ${this.subKernels.map(subKernel=>`${subKernel.property}: result_${subKernel.name}`).join(",\n ")} - };`}_mapSubKernels(fn){return this.subKernels===null?[""]:this.subKernels.map(fn)}destroy(removeCanvasReference){if(removeCanvasReference){delete this.canvas}}static destroyContext(context){}toJSON(){const json=super.toJSON();json.functionNodes=FunctionBuilder.fromKernel(this,CPUFunctionNode).toJSON();return json}setOutput(output){super.setOutput(output);const[width,height]=this.output;if(this.graphical){this._imageData=this.context.createImageData(width,height);this._colorData=new Uint8ClampedArray(width*height*4)}}prependString(value2){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(value2)}hasPrependString(value2){return this._prependedString.indexOf(value2)>-1}}module3.exports={CPUKernel}},{"../../utils":114,"../function-builder":9,"../kernel":36,"./function-node":6,"./kernel-string":7}],9:[function(require2,module3,exports3){class FunctionBuilder{static fromKernel(kernel,FunctionNode,extraNodeOptions){const{kernelArguments,kernelConstants,argumentNames,argumentSizes,argumentBitRatios,constants,constantBitRatios,debug,loopMaxIterations,nativeFunctions,output,optimizeFloatMemory,precision,plugins,source,subKernels,functions,leadingReturnStatement,followingReturnStatement,dynamicArguments,dynamicOutput}=kernel;const argumentTypes=new Array(kernelArguments.length);const constantTypes={};for(let i=0;i{return functionBuilder.needsArgumentType(functionName,index)};const assignArgumentType=(functionName,index,type)=>{functionBuilder.assignArgumentType(functionName,index,type)};const lookupReturnType=(functionName,ast,requestingNode)=>{return functionBuilder.lookupReturnType(functionName,ast,requestingNode)};const lookupFunctionArgumentTypes=functionName=>{return functionBuilder.lookupFunctionArgumentTypes(functionName)};const lookupFunctionArgumentName=(functionName,argumentIndex)=>{return functionBuilder.lookupFunctionArgumentName(functionName,argumentIndex)};const lookupFunctionArgumentBitRatio=(functionName,argumentName)=>{return functionBuilder.lookupFunctionArgumentBitRatio(functionName,argumentName)};const triggerImplyArgumentType=(functionName,i,argumentType,requestingNode)=>{functionBuilder.assignArgumentType(functionName,i,argumentType,requestingNode)};const triggerImplyArgumentBitRatio=(functionName,argumentName,calleeFunctionName,argumentIndex)=>{functionBuilder.assignArgumentBitRatio(functionName,argumentName,calleeFunctionName,argumentIndex)};const onFunctionCall=(functionName,calleeFunctionName,args)=>{functionBuilder.trackFunctionCall(functionName,calleeFunctionName,args)};const onNestedFunction=(ast,source2)=>{const argumentNames2=[];for(let i=0;inew FunctionNode(fn.source,{returnType:fn.returnType,argumentTypes:fn.argumentTypes,output,plugins,constants,constantTypes,constantBitRatios,optimizeFloatMemory,precision,lookupReturnType,lookupFunctionArgumentTypes,lookupFunctionArgumentName,lookupFunctionArgumentBitRatio,needsArgumentType,assignArgumentType,triggerImplyArgumentType,triggerImplyArgumentBitRatio,onFunctionCall,onNestedFunction}))}let subKernelNodes=null;if(subKernels){subKernelNodes=subKernels.map(subKernel=>{const{name:name2,source:source2}=subKernel;return new FunctionNode(source2,Object.assign({},nodeOptions,{name:name2,isSubKernel:true,isRootKernel:false}))})}const functionBuilder=new FunctionBuilder({kernel,rootNode,functionNodes,nativeFunctions,subKernelNodes});return functionBuilder}constructor(settings){settings=settings||{};this.kernel=settings.kernel;this.rootNode=settings.rootNode;this.functionNodes=settings.functionNodes||[];this.subKernelNodes=settings.subKernelNodes||[];this.nativeFunctions=settings.nativeFunctions||[];this.functionMap={};this.nativeFunctionNames=[];this.lookupChain=[];this.functionNodeDependencies={};this.functionCalls={};if(this.rootNode){this.functionMap["kernel"]=this.rootNode}if(this.functionNodes){for(let i=0;i-1){const nativeFunctionIndex=retList.indexOf(functionName);if(nativeFunctionIndex===-1){retList.push(functionName)}else{const dependantNativeFunctionName=retList.splice(nativeFunctionIndex,1)[0];retList.push(dependantNativeFunctionName)}return retList}const functionNode=this.functionMap[functionName];if(functionNode){const functionIndex=retList.indexOf(functionName);if(functionIndex===-1){retList.push(functionName);functionNode.toString();for(let i=0;i-1){ret.push(this.nativeFunctions[functionIndex].source);continue}const node=this.functionMap[functionName];if(node){ret.push(node.toString())}}return ret}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(name2=>{const nativeIndex=this.nativeFunctions.indexOf(name2);if(nativeIndex>-1){return{name:name2,source:this.nativeFunctions[nativeIndex].source}}else if(this.functionMap[name2]){return this.functionMap[name2].toJSON()}else{throw new Error(`function ${name2} not found`)}})}fromJSON(jsonFunctionNodes,FunctionNode){this.functionMap={};for(let i=0;i0){const args=ast.arguments;for(let j=0;j0&&this.argumentTypes.length!==this.argumentNames.length){throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`)}if(this.output.length<1){throw new Error("this.output is not big enough")}}isIdentifierConstant(name2){if(!this.constants)return false;return this.constants.hasOwnProperty(name2)}isInput(argumentName){return this.argumentTypes[this.argumentNames.indexOf(argumentName)]==="Input"}pushState(state2){this.states.push(state2)}popState(state2){if(this.state!==state2){throw new Error(`Cannot popState ${state2} when in ${this.state}`)}this.states.pop()}isState(state2){return this.state===state2}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(ast){if(ast.type==="Identifier"){return ast.name}else if(ast.type==="ThisExpression"){return"this"}if(ast.type==="MemberExpression"){if(ast.object&&ast.property){if(ast.object.hasOwnProperty("name")&&ast.object.name!=="Math"){return this.astMemberExpressionUnroll(ast.property)}return this.astMemberExpressionUnroll(ast.object)+"."+this.astMemberExpressionUnroll(ast.property)}}if(ast.hasOwnProperty("expressions")){const firstExpression=ast.expressions[0];if(firstExpression.type==="Literal"&&firstExpression.value===0&&ast.expressions.length===2){return this.astMemberExpressionUnroll(ast.expressions[1])}}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",ast)}getJsAST(inParser){if(this.ast){return this.ast}if(typeof this.source==="object"){this.traceFunctionAST(this.source);return this.ast=this.source}inParser=inParser||acorn;if(inParser===null){throw new Error("Missing JS to AST parser")}const ast=Object.freeze(inParser.parse(`const parser_${this.name} = ${this.source};`,{locations:true}));const functionAST=ast.body[0].declarations[0].init;this.traceFunctionAST(functionAST);if(!ast){throw new Error("Failed to parse JS code")}return this.ast=functionAST}traceFunctionAST(ast){const{contexts,declarations,functions,identifiers,functionCalls}=new FunctionTracer(ast);this.contexts=contexts;this.identifiers=identifiers;this.functionCalls=functionCalls;this.functions=functions;for(let i=0;i":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const type=this.getType(ast.left);if(this.isState("skip-literal-correction"))return type;if(type==="LiteralInteger"){const rightType=this.getType(ast.right);if(rightType==="LiteralInteger"){if(ast.left.value%1===0){return"Integer"}else{return"Float"}}return rightType}return typeLookupMap[type]||type;case"UpdateExpression":return this.getType(ast.argument);case"UnaryExpression":if(ast.operator==="~"){return"Integer"}return this.getType(ast.argument);case"VariableDeclaration":{const declarations=ast.declarations;let lastType;for(let i=0;i-1}isAstMathFunction(ast){const mathFunctions=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"];return ast.type==="CallExpression"&&ast.callee&&ast.callee.type==="MemberExpression"&&ast.callee.object&&ast.callee.object.type==="Identifier"&&ast.callee.object.name==="Math"&&ast.callee.property&&ast.callee.property.type==="Identifier"&&mathFunctions.indexOf(ast.callee.property.name)>-1}isAstVariable(ast){return ast.type==="Identifier"||ast.type==="MemberExpression"}isSafe(ast){return this.isSafeDependencies(this.getDependencies(ast))}isSafeDependencies(dependencies){return dependencies&&dependencies.every?dependencies.every(dependency=>dependency.isSafe):true}getDependencies(ast,dependencies,isNotSafe){if(!dependencies){dependencies=[]}if(!ast)return null;if(Array.isArray(ast)){for(let i=0;i-Infinity&&ast.value-1){dependencies.push({name:ast.name,origin:"argument",isSafe:false})}else if(this.strictTypingChecking){throw new Error(`Cannot find identifier origin "${ast.name}"`)}break;case"FunctionDeclaration":return this.getDependencies(ast.body.body[ast.body.body.length-1],dependencies,isNotSafe);case"ReturnStatement":return this.getDependencies(ast.argument,dependencies);case"BinaryExpression":case"LogicalExpression":isNotSafe=ast.operator==="/"||ast.operator==="*";this.getDependencies(ast.left,dependencies,isNotSafe);this.getDependencies(ast.right,dependencies,isNotSafe);return dependencies;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(ast.argument,dependencies,isNotSafe);case"VariableDeclaration":return this.getDependencies(ast.declarations,dependencies,isNotSafe);case"ArrayExpression":dependencies.push({origin:"declaration",isSafe:true});return dependencies;case"CallExpression":dependencies.push({origin:"function",isSafe:true});return dependencies;case"MemberExpression":const details=this.getMemberExpressionDetails(ast);switch(details.signature){case"value[]":this.getDependencies(ast.object,dependencies,isNotSafe);break;case"value[][]":this.getDependencies(ast.object.object,dependencies,isNotSafe);break;case"value[][][]":this.getDependencies(ast.object.object.object,dependencies,isNotSafe);break;case"this.output.value":if(this.dynamicOutput){dependencies.push({name:details.name,origin:"output",isSafe:false})}break}if(details){if(details.property){this.getDependencies(details.property,dependencies,isNotSafe)}if(details.xProperty){this.getDependencies(details.xProperty,dependencies,isNotSafe)}if(details.yProperty){this.getDependencies(details.yProperty,dependencies,isNotSafe)}if(details.zProperty){this.getDependencies(details.zProperty,dependencies,isNotSafe)}return dependencies}case"SequenceExpression":return this.getDependencies(ast.expressions,dependencies,isNotSafe);default:throw this.astErrorOutput(`Unhandled type ${ast.type} in getDependencies`,ast)}return dependencies}getVariableSignature(ast,returnRawValue){if(!this.isAstVariable(ast)){throw new Error(`ast of type "${ast.type}" is not a variable signature`)}if(ast.type==="Identifier"){return"value"}const signature=[];while(true){if(!ast)break;if(ast.computed){signature.push("[]")}else if(ast.type==="ThisExpression"){signature.unshift("this")}else if(ast.property&&ast.property.name){if(ast.property.name==="x"||ast.property.name==="y"||ast.property.name==="z"){signature.unshift(returnRawValue?"."+ast.property.name:".value")}else if(ast.property.name==="constants"||ast.property.name==="thread"||ast.property.name==="output"){signature.unshift("."+ast.property.name)}else{signature.unshift(returnRawValue?"."+ast.property.name:".value")}}else if(ast.name){signature.unshift(returnRawValue?ast.name:"value")}else if(ast.callee&&ast.callee.name){signature.unshift(returnRawValue?ast.callee.name+"()":"fn()")}else if(ast.elements){signature.unshift("[]")}else{signature.unshift("unknown")}ast=ast.object}const signatureString=signature.join("");if(returnRawValue){return signatureString}const allowedExpressions=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];if(allowedExpressions.indexOf(signatureString)>-1){return signatureString}return null}build(){return this.toString().length>0}astGeneric(ast,retArr){if(ast===null){throw this.astErrorOutput("NULL ast",ast)}else{if(Array.isArray(ast)){for(let i=0;i0?splitLines[splitLines.length-1]:0;return new Error(`${error} on line ${splitLines.length}, position ${lineBefore.length}: - ${debugString}`)}astDebuggerStatement(arrNode,retArr){return retArr}astConditionalExpression(ast,retArr){if(ast.type!=="ConditionalExpression"){throw this.astErrorOutput("Not a conditional expression",ast)}retArr.push("(");this.astGeneric(ast.test,retArr);retArr.push("?");this.astGeneric(ast.consequent,retArr);retArr.push(":");this.astGeneric(ast.alternate,retArr);retArr.push(")");return retArr}astFunction(ast,retArr){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(ast,retArr){if(this.isChildFunction(ast)){return retArr}return this.astFunction(ast,retArr)}astFunctionExpression(ast,retArr){if(this.isChildFunction(ast)){return retArr}return this.astFunction(ast,retArr)}isChildFunction(ast){for(let i=0;i1){retArr.push("(",sequenceResult.join(","),")")}else{retArr.push(sequenceResult[0])}return retArr}astUnaryExpression(uNode,retArr){const unaryResult=this.checkAndUpconvertBitwiseUnary(uNode,retArr);if(unaryResult){return retArr}if(uNode.prefix){retArr.push(uNode.operator);this.astGeneric(uNode.argument,retArr)}else{this.astGeneric(uNode.argument,retArr);retArr.push(uNode.operator)}return retArr}checkAndUpconvertBitwiseUnary(uNode,retArr){}astUpdateExpression(uNode,retArr){if(uNode.prefix){retArr.push(uNode.operator);this.astGeneric(uNode.argument,retArr)}else{this.astGeneric(uNode.argument,retArr);retArr.push(uNode.operator)}return retArr}astLogicalExpression(logNode,retArr){retArr.push("(");this.astGeneric(logNode.left,retArr);retArr.push(logNode.operator);this.astGeneric(logNode.right,retArr);retArr.push(")");return retArr}astMemberExpression(ast,retArr){return retArr}astCallExpression(ast,retArr){return retArr}astArrayExpression(ast,retArr){return retArr}getMemberExpressionDetails(ast){if(ast.type!=="MemberExpression"){throw this.astErrorOutput(`Expression ${ast.type} not a MemberExpression`,ast)}let name2=null;let type=null;const variableSignature=this.getVariableSignature(ast);switch(variableSignature){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:variableSignature,type:"Integer",name:ast.property.name};case"value[]":if(typeof ast.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object),xProperty:ast.property};case"value[][]":if(typeof ast.object.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object.object),yProperty:ast.object.property,xProperty:ast.property};case"value[][][]":if(typeof ast.object.object.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object.object.object),zProperty:ast.object.object.property,yProperty:ast.object.property,xProperty:ast.property};case"value[][][][]":if(typeof ast.object.object.object.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.object.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object.object.object.object),zProperty:ast.object.object.property,yProperty:ast.object.property,xProperty:ast.property};case"value.value":if(typeof ast.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}if(this.isAstMathVariable(ast)){name2=ast.property.name;return{name:name2,origin:"Math",type:"Number",signature:variableSignature}}switch(ast.property.name){case"r":case"g":case"b":case"a":name2=ast.object.name;return{name:name2,property:ast.property.name,origin:"user",signature:variableSignature,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",ast)}case"this.constants.value":if(typeof ast.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature};case"this.constants.value[]":if(typeof ast.object.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature,xProperty:ast.property};case"this.constants.value[][]":{if(typeof ast.object.object.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature,yProperty:ast.object.property,xProperty:ast.property}}case"this.constants.value[][][]":{if(typeof ast.object.object.object.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.object.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature,zProperty:ast.object.object.property,yProperty:ast.object.property,xProperty:ast.property}}case"fn()[]":case"fn()[][]":case"[][]":return{signature:variableSignature,property:ast.property};default:throw this.astErrorOutput("Unexpected expression",ast)}}findIdentifierOrigin(astToFind){const stack=[this.ast];while(stack.length>0){const atNode=stack[0];if(atNode.type==="VariableDeclarator"&&atNode.id&&atNode.id.name&&atNode.id.name===astToFind.name){return atNode}stack.shift();if(atNode.argument){stack.push(atNode.argument)}else if(atNode.body){stack.push(atNode.body)}else if(atNode.declarations){stack.push(atNode.declarations)}else if(Array.isArray(atNode)){for(let i=0;i0){const atNode=stack.pop();if(atNode.type==="ReturnStatement"){return atNode}if(atNode.type==="FunctionDeclaration"){continue}if(atNode.argument){stack.push(atNode.argument)}else if(atNode.body){stack.push(atNode.body)}else if(atNode.declarations){stack.push(atNode.declarations)}else if(Array.isArray(atNode)){for(let i=0;i0?array[array.length-1]:null}const states={trackIdentifiers:"trackIdentifiers",memberExpression:"memberExpression",inForLoopInit:"inForLoopInit"};class FunctionTracer{constructor(ast){this.runningContexts=[];this.functionContexts=[];this.contexts=[];this.functionCalls=[];this.declarations=[];this.identifiers=[];this.functions=[];this.returnStatements=[];this.trackedIdentifiers=null;this.states=[];this.newFunctionContext();this.scan(ast)}isState(state2){return this.states[this.states.length-1]===state2}hasState(state2){return this.states.indexOf(state2)>-1}pushState(state2){this.states.push(state2)}popState(state2){if(this.isState(state2)){this.states.pop()}else{throw new Error(`Cannot pop the non-active state "${state2}"`)}}get currentFunctionContext(){return last(this.functionContexts)}get currentContext(){return last(this.runningContexts)}newFunctionContext(){const newContext={"@contextType":"function"};this.contexts.push(newContext);this.functionContexts.push(newContext)}newContext(run){const newContext=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(newContext);this.runningContexts.push(newContext);run();const{currentFunctionContext}=this;for(const p in currentFunctionContext){if(!currentFunctionContext.hasOwnProperty(p)||newContext.hasOwnProperty(p))continue;newContext[p]=currentFunctionContext[p]}this.runningContexts.pop();return newContext}useFunctionContext(run){const functionContext=last(this.functionContexts);this.runningContexts.push(functionContext);run();this.runningContexts.pop()}getIdentifiers(run){const trackedIdentifiers=this.trackedIdentifiers=[];this.pushState(states.trackIdentifiers);run();this.trackedIdentifiers=null;this.popState(states.trackIdentifiers);return trackedIdentifiers}getDeclaration(name2){const{currentContext,currentFunctionContext,runningContexts}=this;const declaration=currentContext[name2]||currentFunctionContext[name2]||null;if(!declaration&¤tContext===currentFunctionContext&&runningContexts.length>0){const previousRunningContext=runningContexts[runningContexts.length-2];if(previousRunningContext[name2]){return previousRunningContext[name2]}}return declaration}scan(ast){if(!ast)return;if(Array.isArray(ast)){for(let i=0;i{this.scan(ast.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(ast.body)});break;case"AssignmentExpression":case"LogicalExpression":this.scan(ast.left);this.scan(ast.right);break;case"BinaryExpression":this.scan(ast.left);this.scan(ast.right);break;case"UpdateExpression":if(ast.operator==="++"){const declaration=this.getDeclaration(ast.argument.name);if(declaration){declaration.suggestedType="Integer"}}this.scan(ast.argument);break;case"UnaryExpression":this.scan(ast.argument);break;case"VariableDeclaration":if(ast.kind==="var"){this.useFunctionContext(()=>{ast.declarations=utils.normalizeDeclarations(ast);this.scan(ast.declarations)})}else{ast.declarations=utils.normalizeDeclarations(ast);this.scan(ast.declarations)}break;case"VariableDeclarator":{const{currentContext}=this;const inForLoopInit=this.hasState(states.inForLoopInit);const declaration={ast,context:currentContext,name:ast.id.name,origin:"declaration",inForLoopInit,inForLoopTest:null,assignable:currentContext===this.currentFunctionContext||!inForLoopInit&&!currentContext.hasOwnProperty(ast.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};if(!currentContext[ast.id.name]){currentContext[ast.id.name]=declaration}this.declarations.push(declaration);this.scan(ast.id);this.scan(ast.init);break}case"FunctionExpression":case"FunctionDeclaration":if(this.runningContexts.length===0){this.scan(ast.body)}else{this.functions.push(ast)}break;case"IfStatement":this.scan(ast.test);this.scan(ast.consequent);if(ast.alternate)this.scan(ast.alternate);break;case"ForStatement":{let testIdentifiers;const context=this.newContext(()=>{this.pushState(states.inForLoopInit);this.scan(ast.init);this.popState(states.inForLoopInit);testIdentifiers=this.getIdentifiers(()=>{this.scan(ast.test)});this.scan(ast.update);this.newContext(()=>{this.scan(ast.body)})});if(testIdentifiers){for(const p in context){if(p==="@contextType")continue;if(testIdentifiers.indexOf(p)>-1){context[p].inForLoopTest=true}}}break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(ast.body);this.scan(ast.test)});break;case"Identifier":{if(this.isState(states.trackIdentifiers)){this.trackedIdentifiers.push(ast.name)}this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(ast.name),ast});break}case"ReturnStatement":this.returnStatements.push(ast);this.scan(ast.argument);break;case"MemberExpression":this.pushState(states.memberExpression);this.scan(ast.object);this.scan(ast.property);this.popState(states.memberExpression);break;case"ExpressionStatement":this.scan(ast.expression);break;case"SequenceExpression":this.scan(ast.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast});this.scan(ast.arguments);break;case"ArrayExpression":this.scan(ast.elements);break;case"ConditionalExpression":this.scan(ast.test);this.scan(ast.alternate);this.scan(ast.consequent);break;case"SwitchStatement":this.scan(ast.discriminant);this.scan(ast.cases);break;case"SwitchCase":this.scan(ast.test);this.scan(ast.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${ast.type}"`)}}}module3.exports={FunctionTracer}},{"../utils":114}],12:[function(require2,module3,exports3){const{glWiretap}=require2("gl-wiretap");const{utils}=require2("../../utils");function toStringWithoutUtils(fn){return fn.toString().replace("=>","").replace(/^function /,"").replace(/utils[.]/g,"/*utils.*/")}function glKernelString(Kernel,args,originKernel,setupContextString,destroyContextString){if(!originKernel.built){originKernel.build.apply(originKernel,args)}args=args?Array.from(args).map(arg=>{switch(typeof arg){case"boolean":return new Boolean(arg);case"number":return new Number(arg);default:return arg}}):null;const uploadedValues=[];const postResult=[];const context=glWiretap(originKernel.context,{useTrackablePrimitives:true,onReadPixels:targetName=>{if(kernel.subKernels){if(!subKernelsResultVariableSetup){postResult.push(` const result = { result: ${getRenderString(targetName,kernel)} };`);subKernelsResultVariableSetup=true}else{const property=kernel.subKernels[subKernelsResultIndex++].property;postResult.push(` result${isNaN(property)?"."+property:`[${property}]`} = ${getRenderString(targetName,kernel)};`)}if(subKernelsResultIndex===kernel.subKernels.length){postResult.push(" return result;")}return}if(targetName){postResult.push(` return ${getRenderString(targetName,kernel)};`)}else{postResult.push(` return null;`)}},onUnrecognizedArgumentLookup:argument=>{const argumentName=findKernelValue(argument,kernel.kernelArguments,[],context,uploadedValues);if(argumentName){return argumentName}const constantName=findKernelValue(argument,kernel.kernelConstants,constants?Object.keys(constants).map(key=>constants[key]):[],context,uploadedValues);if(constantName){return constantName}return null}});let subKernelsResultVariableSetup=false;let subKernelsResultIndex=0;const{source,canvas,output,pipeline,graphical,loopMaxIterations,constants,optimizeFloatMemory,precision,fixIntegerDivisionAccuracy,functions,nativeFunctions,subKernels,immutable,argumentTypes,constantTypes,kernelArguments,kernelConstants,tactic}=originKernel;const kernel=new Kernel(source,{canvas,context,checkContext:false,output,pipeline,graphical,loopMaxIterations,constants,optimizeFloatMemory,precision,fixIntegerDivisionAccuracy,functions,nativeFunctions,subKernels,immutable,argumentTypes,constantTypes,tactic});let result=[];context.setIndent(2);kernel.build.apply(kernel,args);result.push(context.toString());context.reset();kernel.kernelArguments.forEach((kernelArgument,i)=>{switch(kernelArgument.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":context.insertVariable(`uploadValue_${kernelArgument.name}`,kernelArgument.uploadValue);break;case"HTMLImageArray":for(let imageIndex=0;imageIndexkernelArgument.varName).join(", ")}) {`);context.setIndent(4);kernel.run.apply(kernel,args);if(kernel.renderKernels){kernel.renderKernels()}else if(kernel.renderOutput){kernel.renderOutput()}result.push(" /** start setup uploads for kernel values **/");kernel.kernelArguments.forEach(kernelArgument=>{result.push(" "+kernelArgument.getStringValueHandler().split("\n").join("\n "))});result.push(" /** end setup uploads for kernel values **/");result.push(context.toString());if(kernel.renderOutput===kernel.renderTexture){context.reset();const framebufferName=context.getContextVariableName(kernel.framebuffer);if(kernel.renderKernels){const results=kernel.renderKernels();const textureName=context.getContextVariableName(kernel.texture.texture);result.push(` return { - result: { - texture: ${textureName}, - type: '${results.result.type}', - toArray: ${getToArrayString(results.result,textureName,framebufferName)} - },`);const{subKernels:subKernels2,mappedTextures}=kernel;for(let i=0;i{constantsUpload.push(`${kernelConstant.getStringValueHandler()}`)});return`function kernel(settings) { - const { context, constants } = settings; - ${constantsUpload.join("")} - ${setupContextString?setupContextString:""} - ${result.join("\n")} - }`}function getRenderString(targetName,kernel){const readBackValue=kernel.precision==="single"?targetName:`new Float32Array(${targetName}.buffer)`;if(kernel.output[2]){return`renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]}, ${kernel.output[2]})`}if(kernel.output[1]){return`renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]})`}return`renderOutput(${readBackValue}, ${kernel.output[0]})`}function getGetPixelsString(kernel){const getPixels=kernel.getPixels.toString();const useFunctionKeyword=!/^function/.test(getPixels);return utils.flattenFunctionToString(`${useFunctionKeyword?"function ":""}${getPixels}`,{findDependency:(object,name2)=>{if(object==="utils"){return`const ${name2} = ${utils[name2].toString()};`}return null},thisLookup:property=>{if(property==="context"){return null}if(kernel.hasOwnProperty(property)){return JSON.stringify(kernel[property])}throw new Error(`unhandled thisLookup ${property}`)}})}function getToArrayString(kernelResult,textureName,framebufferName){const toArray=kernelResult.toArray.toString();const useFunctionKeyword=!/^function/.test(toArray);const flattenedFunctions=utils.flattenFunctionToString(`${useFunctionKeyword?"function ":""}${toArray}`,{findDependency:(object,name2)=>{if(object==="utils"){return`const ${name2} = ${utils[name2].toString()};`}else if(object==="this"){if(name2==="framebuffer"){return""}return`${useFunctionKeyword?"function ":""}${kernelResult[name2].toString()}`}else{throw new Error("unhandled fromObject")}},thisLookup:(property,isDeclaration)=>{if(property==="texture"){return textureName}if(property==="context"){if(isDeclaration)return null;return"gl"}if(kernelResult.hasOwnProperty(property)){return JSON.stringify(kernelResult[property])}throw new Error(`unhandled thisLookup ${property}`)}});return`() => { - function framebuffer() { return ${framebufferName}; }; - ${flattenedFunctions} - return toArray(); - }`}function findKernelValue(argument,kernelValues,values,context,uploadedValues){if(argument===null)return null;if(kernelValues===null)return null;switch(typeof argument){case"boolean":case"number":return null}if(typeof HTMLImageElement!=="undefined"&&argument instanceof HTMLImageElement){for(let i=0;i0?":"+argumentTypes.join(","):"")}setFixIntegerDivisionAccuracy(fix){this.fixIntegerDivisionAccuracy=fix;return this}setPrecision(flag){this.precision=flag;return this}setFloatTextures(flag){utils.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory");this.floatTextures=flag;return this}static nativeFunctionArguments(source){const argumentTypes=[];const argumentNames=[];const states=[];const isStartingVariableName=/^[a-zA-Z_]/;const isVariableChar=/[a-zA-Z_0-9]/;let i=0;let argumentName=null;let argumentType=null;while(i0?states[states.length-1]:null;if(state2==="FUNCTION_ARGUMENTS"&&char==="/"&&nextChar==="*"){states.push("MULTI_LINE_COMMENT");i+=2;continue}else if(state2==="MULTI_LINE_COMMENT"&&char==="*"&&nextChar==="/"){states.pop();i+=2;continue}else if(state2==="FUNCTION_ARGUMENTS"&&char==="/"&&nextChar==="/"){states.push("COMMENT");i+=2;continue}else if(state2==="COMMENT"&&char==="\n"){states.pop();i++;continue}else if(state2===null&&char==="("){states.push("FUNCTION_ARGUMENTS");i++;continue}else if(state2==="FUNCTION_ARGUMENTS"){if(char===")"){states.pop();break}if(char==="f"&&nextChar==="l"&&source[i+2]==="o"&&source[i+3]==="a"&&source[i+4]==="t"&&source[i+5]===" "){states.push("DECLARE_VARIABLE");argumentType="float";argumentName="";i+=6;continue}else if(char==="i"&&nextChar==="n"&&source[i+2]==="t"&&source[i+3]===" "){states.push("DECLARE_VARIABLE");argumentType="int";argumentName="";i+=4;continue}else if(char==="v"&&nextChar==="e"&&source[i+2]==="c"&&source[i+3]==="2"&&source[i+4]===" "){states.push("DECLARE_VARIABLE");argumentType="vec2";argumentName="";i+=5;continue}else if(char==="v"&&nextChar==="e"&&source[i+2]==="c"&&source[i+3]==="3"&&source[i+4]===" "){states.push("DECLARE_VARIABLE");argumentType="vec3";argumentName="";i+=5;continue}else if(char==="v"&&nextChar==="e"&&source[i+2]==="c"&&source[i+3]==="4"&&source[i+4]===" "){states.push("DECLARE_VARIABLE");argumentType="vec4";argumentName="";i+=5;continue}}else if(state2==="DECLARE_VARIABLE"){if(argumentName===""){if(char===" "){i++;continue}if(!isStartingVariableName.test(char)){throw new Error("variable name is not expected string")}}argumentName+=char;if(!isVariableChar.test(nextChar)){states.pop();argumentNames.push(argumentName);argumentTypes.push(typeMap[argumentType])}}i++}if(states.length>0){throw new Error("GLSL function was not parsable")}return{argumentNames,argumentTypes}}static nativeFunctionReturnType(source){return typeMap[source.match(/int|float|vec[2-4]/)[0]]}static combineKernels(combinedKernel,lastKernel){combinedKernel.apply(null,arguments);const{texSize,context,threadDim}=lastKernel.texSize;let result;if(lastKernel.precision==="single"){const w=texSize[0];const h=Math.ceil(texSize[1]/4);result=new Float32Array(w*h*4*4);context.readPixels(0,0,w,h*4,context.RGBA,context.FLOAT,result)}else{const bytes=new Uint8Array(texSize[0]*texSize[1]*4);context.readPixels(0,0,texSize[0],texSize[1],context.RGBA,context.UNSIGNED_BYTE,bytes);result=new Float32Array(bytes.buffer)}result=result.subarray(0,threadDim[0]*threadDim[1]*threadDim[2]);if(lastKernel.output.length===1){return result}else if(lastKernel.output.length===2){return utils.splitArray(result,lastKernel.output[0])}else if(lastKernel.output.length===3){const cube=utils.splitArray(result,lastKernel.output[0]*lastKernel.output[1]);return cube.map(function(x2){return utils.splitArray(x2,lastKernel.output[0])})}}constructor(source,settings){super(source,settings);this.transferValues=null;this.formatValues=null;this.TextureConstructor=null;this.renderOutput=null;this.renderRawOutput=null;this.texSize=null;this.translatedSource=null;this.compiledFragmentShader=null;this.compiledVertexShader=null;this.switchingKernels=null;this._textureSwitched=null;this._mappedTextureSwitched=null}checkTextureSize(){const{features}=this.constructor;if(this.texSize[0]>features.maxTextureSize||this.texSize[1]>features.maxTextureSize){throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${features.maxTextureSize},${features.maxTextureSize}]`)}}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(args){if(this.graphical){this.renderRawOutput=this.readPackedPixelsToUint8Array;this.transferValues=pixels=>pixels;this.TextureConstructor=GLTextureGraphical;return null}if(this.precision==="unsigned"){this.renderRawOutput=this.readPackedPixelsToUint8Array;this.transferValues=this.readPackedPixelsToFloat32Array;if(this.pipeline){this.renderOutput=this.renderTexture;if(this.subKernels!==null){this.renderKernels=this.renderKernelsToTextures}switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":if(this.output[2]>0){this.TextureConstructor=GLTextureUnsigned3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureUnsigned2D;return null}else{this.TextureConstructor=GLTextureUnsigned;return null}case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(args)}}else{if(this.subKernels!==null){this.renderKernels=this.renderKernelsToArrays}switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":this.renderOutput=this.renderValues;if(this.output[2]>0){this.TextureConstructor=GLTextureUnsigned3D;this.formatValues=utils.erect3DPackedFloat;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureUnsigned2D;this.formatValues=utils.erect2DPackedFloat;return null}else{this.TextureConstructor=GLTextureUnsigned;this.formatValues=utils.erectPackedFloat;return null}case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(args)}}}else if(this.precision==="single"){this.renderRawOutput=this.readFloatPixelsToFloat32Array;this.transferValues=this.readFloatPixelsToFloat32Array;if(this.pipeline){this.renderOutput=this.renderTexture;if(this.subKernels!==null){this.renderKernels=this.renderKernelsToTextures}switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":{if(this.optimizeFloatMemory){if(this.output[2]>0){this.TextureConstructor=GLTextureMemoryOptimized3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureMemoryOptimized2D;return null}else{this.TextureConstructor=GLTextureMemoryOptimized;return null}}else{if(this.output[2]>0){this.TextureConstructor=GLTextureFloat3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureFloat2D;return null}else{this.TextureConstructor=GLTextureFloat;return null}}}case"Array(2)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray2Float3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray2Float2D;return null}else{this.TextureConstructor=GLTextureArray2Float;return null}}case"Array(3)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray3Float3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray3Float2D;return null}else{this.TextureConstructor=GLTextureArray3Float;return null}}case"Array(4)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray4Float3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray4Float2D;return null}else{this.TextureConstructor=GLTextureArray4Float;return null}}}}this.renderOutput=this.renderValues;if(this.subKernels!==null){this.renderKernels=this.renderKernelsToArrays}if(this.optimizeFloatMemory){switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":{if(this.output[2]>0){this.TextureConstructor=GLTextureMemoryOptimized3D;this.formatValues=utils.erectMemoryOptimized3DFloat;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureMemoryOptimized2D;this.formatValues=utils.erectMemoryOptimized2DFloat;return null}else{this.TextureConstructor=GLTextureMemoryOptimized;this.formatValues=utils.erectMemoryOptimizedFloat;return null}}case"Array(2)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray2Float3D;this.formatValues=utils.erect3DArray2;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray2Float2D;this.formatValues=utils.erect2DArray2;return null}else{this.TextureConstructor=GLTextureArray2Float;this.formatValues=utils.erectArray2;return null}}case"Array(3)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray3Float3D;this.formatValues=utils.erect3DArray3;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray3Float2D;this.formatValues=utils.erect2DArray3;return null}else{this.TextureConstructor=GLTextureArray3Float;this.formatValues=utils.erectArray3;return null}}case"Array(4)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray4Float3D;this.formatValues=utils.erect3DArray4;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray4Float2D;this.formatValues=utils.erect2DArray4;return null}else{this.TextureConstructor=GLTextureArray4Float;this.formatValues=utils.erectArray4;return null}}}}else{switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":{if(this.output[2]>0){this.TextureConstructor=GLTextureFloat3D;this.formatValues=utils.erect3DFloat;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureFloat2D;this.formatValues=utils.erect2DFloat;return null}else{this.TextureConstructor=GLTextureFloat;this.formatValues=utils.erectFloat;return null}}case"Array(2)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray2Float3D;this.formatValues=utils.erect3DArray2;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray2Float2D;this.formatValues=utils.erect2DArray2;return null}else{this.TextureConstructor=GLTextureArray2Float;this.formatValues=utils.erectArray2;return null}}case"Array(3)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray3Float3D;this.formatValues=utils.erect3DArray3;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray3Float2D;this.formatValues=utils.erect2DArray3;return null}else{this.TextureConstructor=GLTextureArray3Float;this.formatValues=utils.erectArray3;return null}}case"Array(4)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray4Float3D;this.formatValues=utils.erect3DArray4;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray4Float2D;this.formatValues=utils.erect2DArray4;return null}else{this.TextureConstructor=GLTextureArray4Float;this.formatValues=utils.erectArray4;return null}}}}}else{throw new Error(`unhandled precision of "${this.precision}"`)}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error(`abstract method call`)}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error(`abstract method call`)}getMainResultSubKernelNumberTexture(){throw new Error(`abstract method call`)}getMainResultKernelArray2Texture(){throw new Error(`abstract method call`)}getMainResultSubKernelArray2Texture(){throw new Error(`abstract method call`)}getMainResultKernelArray3Texture(){throw new Error(`abstract method call`)}getMainResultSubKernelArray3Texture(){throw new Error(`abstract method call`)}getMainResultKernelArray4Texture(){throw new Error(`abstract method call`)}getMainResultSubKernelArray4Texture(){throw new Error(`abstract method call`)}getMainResultGraphical(){throw new Error(`abstract method call`)}getMainResultMemoryOptimizedFloats(){throw new Error(`abstract method call`)}getMainResultPackedPixels(){throw new Error(`abstract method call`)}getMainResultString(){if(this.graphical){return this.getMainResultGraphical()}else if(this.precision==="single"){if(this.optimizeFloatMemory){return this.getMainResultMemoryOptimizedFloats()}return this.getMainResultTexture()}else{return this.getMainResultPackedPixels()}}getMainResultNumberTexture(){return utils.linesToString(this.getMainResultKernelNumberTexture())+utils.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return utils.linesToString(this.getMainResultKernelArray2Texture())+utils.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return utils.linesToString(this.getMainResultKernelArray3Texture())+utils.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return utils.linesToString(this.getMainResultKernelArray4Texture())+utils.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){const variablePrecision=this.getVariablePrecisionString(this.texSize,this.tactic);return`precision ${variablePrecision} float; -`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,true)} int; -`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D; -`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray; -`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if(this.precision!=="unsigned")throw new Error('Requires this.precision to be "unsigned"');const{texSize,context:gl}=this;const result=new Uint8Array(texSize[0]*texSize[1]*4);gl.readPixels(0,0,texSize[0],texSize[1],gl.RGBA,gl.UNSIGNED_BYTE,result);return result}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if(this.precision!=="single")throw new Error('Requires this.precision to be "single"');const{texSize,context:gl}=this;const w=texSize[0];const h=texSize[1];const result=new Float32Array(w*h*4);gl.readPixels(0,0,w,h,gl.RGBA,gl.FLOAT,result);return result}getPixels(flip){const{context:gl,output}=this;const[width,height]=output;const pixels=new Uint8Array(width*height*4);gl.readPixels(0,0,width,height,gl.RGBA,gl.UNSIGNED_BYTE,pixels);return new Uint8ClampedArray((flip?pixels:utils.flipPixels(pixels,width,height)).buffer)}renderKernelsToArrays(){const result={result:this.renderOutput()};for(let i=0;i0){for(let i=0;i0){const{mappedTextures}=this;for(let i=0;i1){this.newTexture();return true}return false}cloneTexture(){this.texture._refs--;const{context:gl,size,texture,kernel}=this;if(kernel.debug){console.warn("cloning internal texture")}gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer());selectTexture(gl,texture);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);const target=gl.createTexture();selectTexture(gl,target);gl.texImage2D(gl.TEXTURE_2D,0,this.internalFormat,size[0],size[1],0,this.textureFormat,this.textureType,null);gl.copyTexSubImage2D(gl.TEXTURE_2D,0,0,0,0,0,size[0],size[1]);target._refs=1;this.texture=target}newTexture(){this.texture._refs--;const gl=this.context;const size=this.size;const kernel=this.kernel;if(kernel.debug){console.warn("new internal texture")}const target=gl.createTexture();selectTexture(gl,target);gl.texImage2D(gl.TEXTURE_2D,0,this.internalFormat,size[0],size[1],0,this.textureFormat,this.textureType,null);target._refs=1;this.texture=target}clear(){if(this.texture._refs){this.texture._refs--;const gl2=this.context;const target=this.texture=gl2.createTexture();selectTexture(gl2,target);const size=this.size;target._refs=1;gl2.texImage2D(gl2.TEXTURE_2D,0,this.internalFormat,size[0],size[1],0,this.textureFormat,this.textureType,null)}const{context:gl,texture}=this;gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer());gl.bindTexture(gl.TEXTURE_2D,texture);selectTexture(gl,texture);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT)}delete(){if(this._deleted)return;this._deleted=true;if(this.texture._refs){this.texture._refs--;if(this.texture._refs)return}this.context.deleteTexture(this.texture)}framebuffer(){if(!this._framebuffer){this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])}return this._framebuffer}}function selectTexture(gl,texture){gl.activeTexture(gl.TEXTURE15);gl.bindTexture(gl.TEXTURE_2D,texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST)}module3.exports={GLTexture}},{"../../../texture":113}],28:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureFloat}=require2("./float");class GLTextureMemoryOptimized2D extends GLTextureFloat{constructor(settings){super(settings);this.type="MemoryOptimizedNumberTexture"}toArray(){return utils.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}module3.exports={GLTextureMemoryOptimized2D}},{"../../../utils":114,"./float":25}],29:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureFloat}=require2("./float");class GLTextureMemoryOptimized3D extends GLTextureFloat{constructor(settings){super(settings);this.type="MemoryOptimizedNumberTexture"}toArray(){return utils.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}module3.exports={GLTextureMemoryOptimized3D}},{"../../../utils":114,"./float":25}],30:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureFloat}=require2("./float");class GLTextureMemoryOptimized extends GLTextureFloat{constructor(settings){super(settings);this.type="MemoryOptimizedNumberTexture"}toArray(){return utils.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}module3.exports={GLTextureMemoryOptimized}},{"../../../utils":114,"./float":25}],31:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureUnsigned}=require2("./unsigned");class GLTextureUnsigned2D extends GLTextureUnsigned{constructor(settings){super(settings);this.type="NumberTexture"}toArray(){return utils.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}module3.exports={GLTextureUnsigned2D}},{"../../../utils":114,"./unsigned":33}],32:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureUnsigned}=require2("./unsigned");class GLTextureUnsigned3D extends GLTextureUnsigned{constructor(settings){super(settings);this.type="NumberTexture"}toArray(){return utils.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}module3.exports={GLTextureUnsigned3D}},{"../../../utils":114,"./unsigned":33}],33:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTexture}=require2("./index");class GLTextureUnsigned extends GLTexture{get textureType(){return this.context.UNSIGNED_BYTE}constructor(settings){super(settings);this.type="NumberTexture"}renderRawOutput(){const{context:gl}=this;gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer());gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,this.texture,0);const result=new Uint8Array(this.size[0]*this.size[1]*4);gl.readPixels(0,0,this.size[0],this.size[1],gl.RGBA,gl.UNSIGNED_BYTE,result);return result}renderValues(){if(this._deleted)return null;return new Float32Array(this.renderRawOutput().buffer)}toArray(){return utils.erectPackedFloat(this.renderValues(),this.output[0])}}module3.exports={GLTextureUnsigned}},{"../../../utils":114,"./index":27}],34:[function(require2,module3,exports3){const getContext=require2("gl");const{WebGLKernel}=require2("../web-gl/kernel");const{glKernelString}=require2("../gl/kernel-string");let isSupported=null;let testCanvas=null;let testContext=null;let testExtensions=null;let features=null;class HeadlessGLKernel extends WebGLKernel{static get isSupported(){if(isSupported!==null)return isSupported;this.setupFeatureChecks();isSupported=testContext!==null;return isSupported}static setupFeatureChecks(){testCanvas=null;testExtensions=null;if(typeof getContext!=="function")return;try{testContext=getContext(2,2,{preserveDrawingBuffer:true});if(!testContext||!testContext.getExtension)return;testExtensions={STACKGL_resize_drawingbuffer:testContext.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:testContext.getExtension("STACKGL_destroy_context"),OES_texture_float:testContext.getExtension("OES_texture_float"),OES_texture_float_linear:testContext.getExtension("OES_texture_float_linear"),OES_element_index_uint:testContext.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:testContext.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:testContext.getExtension("WEBGL_color_buffer_float")};features=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(context){try{return context.getParameter(context.RENDERER)==="ANGLE"}catch(e){return false}}static getIsTextureFloat(){return Boolean(testExtensions.OES_texture_float)}static getIsDrawBuffers(){return Boolean(testExtensions.WEBGL_draw_buffers)}static getChannelCount(){return testExtensions.WEBGL_draw_buffers?testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return testContext.getParameter(testContext.MAX_TEXTURE_SIZE)}static get testCanvas(){return testCanvas}static get testContext(){return testContext}static get features(){return features}initCanvas(){return{}}initContext(){return getContext(2,2,{preserveDrawingBuffer:true})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments);if(!this.fallbackRequested){this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null;this.extensions.STACKGL_destroy_context=null;this.extensions.OES_texture_float=null;this.extensions.OES_texture_float_linear=null;this.extensions.OES_element_index_uint=null;this.extensions.WEBGL_draw_buffers=null}static destroyContext(context){const extension=context.getExtension("STACKGL_destroy_context");if(extension&&extension.destroy){extension.destroy()}}toString(){const setupContextString=`const gl = context || require('gl')(1, 1); -`;const destroyContextString=` if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); } -`;return glKernelString(this.constructor,arguments,this,setupContextString,destroyContextString)}setOutput(output){super.setOutput(output);if(this.graphical&&this.extensions.STACKGL_resize_drawingbuffer){this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}return this}}module3.exports={HeadlessGLKernel}},{"../gl/kernel-string":12,"../web-gl/kernel":70,"gl":2}],35:[function(require2,module3,exports3){class KernelValue{constructor(value2,settings){const{name:name2,kernel,context,checkContext,onRequestContextHandle,onUpdateValueMismatch,origin,strictIntegers,type,tactic}=settings;if(!name2){throw new Error("name not set")}if(!type){throw new Error("type not set")}if(!origin){throw new Error("origin not set")}if(origin!=="user"&&origin!=="constants"){throw new Error(`origin must be "user" or "constants" value is "${origin}"`)}if(!onRequestContextHandle){throw new Error("onRequestContextHandle is not set")}this.name=name2;this.origin=origin;this.tactic=tactic;this.varName=origin==="constants"?`constants.${name2}`:name2;this.kernel=kernel;this.strictIntegers=strictIntegers;this.type=value2.type||type;this.size=value2.size||null;this.index=null;this.context=context;this.checkContext=checkContext!==null&&checkContext!==void 0?checkContext:true;this.contextHandle=null;this.onRequestContextHandle=onRequestContextHandle;this.onUpdateValueMismatch=onUpdateValueMismatch;this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(value2){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}module3.exports={KernelValue}},{}],36:[function(require2,module3,exports3){const{utils}=require2("../utils");const{Input}=require2("../input");class Kernel{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(context){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(context){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(source,settings){if(typeof source!=="object"){if(typeof source!=="string"){throw new Error("source not a string")}if(!utils.isFunctionString(source)){throw new Error("source not a function string")}}this.useLegacyEncoder=false;this.fallbackRequested=false;this.onRequestFallback=null;this.argumentNames=typeof source==="string"?utils.getArgumentNamesFromString(source):null;this.argumentTypes=null;this.argumentSizes=null;this.argumentBitRatios=null;this.kernelArguments=null;this.kernelConstants=null;this.forceUploadKernelConstants=null;this.source=source;this.output=null;this.debug=false;this.graphical=false;this.loopMaxIterations=0;this.constants=null;this.constantTypes=null;this.constantBitRatios=null;this.dynamicArguments=false;this.dynamicOutput=false;this.canvas=null;this.context=null;this.checkContext=null;this.gpu=null;this.functions=null;this.nativeFunctions=null;this.injectedNative=null;this.subKernels=null;this.validate=true;this.immutable=false;this.pipeline=false;this.precision=null;this.tactic=null;this.plugins=null;this.returnType=null;this.leadingReturnStatement=null;this.followingReturnStatement=null;this.optimizeFloatMemory=null;this.strictIntegers=false;this.fixIntegerDivisionAccuracy=null;this.built=false;this.signature=null}mergeSettings(settings){for(let p in settings){if(!settings.hasOwnProperty(p)||!this.hasOwnProperty(p))continue;switch(p){case"output":if(!Array.isArray(settings.output)){this.setOutput(settings.output);continue}break;case"functions":this.functions=[];for(let i=0;iplugin.name):null,returnType:this.returnType}}}buildSignature(args){const Constructor=this.constructor;this.signature=Constructor.getSignature(this,Constructor.getArgumentTypes(this,args))}static getArgumentTypes(kernel,args){const argumentTypes=new Array(args.length);for(let i=0;isettings.argumentTypes[name2])||[]}else{argumentTypes=settings.argumentTypes||[]}return{name:utils.getFunctionNameFromString(sourceString)||null,source:sourceString,argumentTypes,returnType:settings.returnType||null}}onActivate(previousKernel){}}function splitArgumentTypes(argumentTypesObject){const argumentNames=Object.keys(argumentTypesObject);const argumentTypes=[];for(let i=0;i= 0.0) { - return pow(x, 1.0 / 3.0); - } else { - return -pow(x, 1.0 / 3.0); - } - } - - float cosh(float x) { - return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; - } - - float expm1(float x) { - return pow(${Math.E}, x) - 1.0; - } - - float fround(highp float x) { - return x; - } - - float imul(float v1, float v2) { - return float(int(v1) * int(v2)); - } - - float log10(float x) { - return log2(x) * (1.0 / log2(10.0)); - } - - float log1p(float x) { - return log(1.0 + x); - } - - float _pow(float v1, float v2) { - if (v2 == 0.0) return 1.0; - return pow(v1, v2); - } - - float tanh(float x) { - float e = exp(2.0 * x); - return (e - 1.0) / (e + 1.0); - } - - float trunc(float x) { - if (x >= 0.0) { - return floor(x); - } else { - return ceil(x); - } - } - - vec4 _round(vec4 x) { - return floor(x + 0.5); - } - - float _round(float x) { - return floor(x + 0.5); - } - - const int BIT_COUNT = 32; - int modi(int x, int y) { - return x - y * (x / y); - } - - int bitwiseOr(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseXOR(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseAnd(int a, int b) { - int result = 0; - int n = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 && b > 0)) { - break; - } - } - return result; - } - int bitwiseNot(int a) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if (modi(a, 2) == 0) { - result += n; - } - a = a / 2; - n = n * 2; - } - return result; - } - int bitwiseZeroFillLeftShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n *= 2; - } - - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - int bitwiseSignedRightShift(int num, int shifts) { - return int(floor(float(num) / pow(2.0, float(shifts)))); - } - - int bitwiseZeroFillRightShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n /= 2; - } - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - vec2 integerMod(vec2 x, float y) { - vec2 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec3 integerMod(vec3 x, float y) { - vec3 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec4 integerMod(vec4 x, vec4 y) { - vec4 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - float integerMod(float x, float y) { - float res = floor(mod(x, y)); - return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); - } - - int integerMod(int x, int y) { - return x - (y * int(x / y)); - } - - __DIVIDE_WITH_INTEGER_CHECK__; - - // Here be dragons! - // DO NOT OPTIMIZE THIS CODE - // YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE - // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME - const vec2 MAGIC_VEC = vec2(1.0, -256.0); - const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); - const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 - float decode32(vec4 texel) { - __DECODE32_ENDIANNESS__; - texel *= 255.0; - vec2 gte128; - gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; - gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; - float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); - float res = exp2(_round(exponent)); - texel.b = texel.b - 128.0 * gte128.x; - res = dot(texel, SCALE_FACTOR) * exp2(_round(exponent-23.0)) + res; - res *= gte128.y * -2.0 + 1.0; - return res; - } - - float decode16(vec4 texel, int index) { - int channel = integerMod(index, 2); - if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0; - if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0; - return 0.0; - } - - float decode8(vec4 texel, int index) { - int channel = integerMod(index, 4); - if (channel == 0) return texel.r * 255.0; - if (channel == 1) return texel.g * 255.0; - if (channel == 2) return texel.b * 255.0; - if (channel == 3) return texel.a * 255.0; - return 0.0; - } - - vec4 legacyEncode32(float f) { - float F = abs(f); - float sign = f < 0.0 ? 1.0 : 0.0; - float exponent = floor(log2(F)); - float mantissa = (exp2(-exponent) * F); - // exponent += floor(log2(mantissa)); - vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; - texel.rg = integerMod(texel.rg, 256.0); - texel.b = integerMod(texel.b, 128.0); - texel.a = exponent*0.5 + 63.5; - texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; - texel = floor(texel); - texel *= 0.003921569; // 1/255 - __ENCODE32_ENDIANNESS__; - return texel; - } - - // https://github.com/gpujs/gpu.js/wiki/Encoder-details - vec4 encode32(float value) { - if (value == 0.0) return vec4(0, 0, 0, 0); - - float exponent; - float mantissa; - vec4 result; - float sgn; - - sgn = step(0.0, -value); - value = abs(value); - - exponent = floor(log2(value)); - - mantissa = value*pow(2.0, -exponent)-1.0; - exponent = exponent+127.0; - result = vec4(0,0,0,0); - - result.a = floor(exponent/2.0); - exponent = exponent - result.a*2.0; - result.a = result.a + 128.0*sgn; - - result.b = floor(mantissa * 128.0); - mantissa = mantissa - result.b / 128.0; - result.b = result.b + exponent*128.0; - - result.g = floor(mantissa*32768.0); - mantissa = mantissa - result.g/32768.0; - - result.r = floor(mantissa*8388608.0); - return result/255.0; - } - // Dragons end here - - int index; - ivec3 threadId; - - ivec3 indexTo3D(int idx, ivec3 texDim) { - int z = int(idx / (texDim.x * texDim.y)); - idx -= z * int(texDim.x * texDim.y); - int y = int(idx / texDim.x); - int x = int(integerMod(idx, texDim.x)); - return ivec3(x, y, z); - } - - float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - return decode32(texel); - } - - float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x * 2; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y)); - return decode16(texel, index); - } - - float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x * 4; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y)); - return decode8(texel, index); - } - - float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 4); - index = index / 4; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - if (channel == 0) return texel.r; - if (channel == 1) return texel.g; - if (channel == 2) return texel.b; - if (channel == 3) return texel.a; - return 0.0; - } - - vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - return texture2D(tex, st / vec2(texSize)); - } - - float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return result[0]; - } - - vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec2(result[0], result[1]); - } - - vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int channel = integerMod(index, 2); - index = index / 2; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - if (channel == 0) return vec2(texel.r, texel.g); - if (channel == 1) return vec2(texel.b, texel.a); - return vec2(0.0, 0.0); - } - - vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec3(result[0], result[1], result[2]); - } - - vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); - int vectorIndex = fieldIndex / 4; - int vectorOffset = fieldIndex - vectorIndex * 4; - int readY = vectorIndex / texSize.x; - int readX = vectorIndex - readY * texSize.x; - vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); - - if (vectorOffset == 0) { - return tex1.xyz; - } else if (vectorOffset == 1) { - return tex1.yzw; - } else { - readX++; - if (readX >= texSize.x) { - readX = 0; - readY++; - } - vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize)); - if (vectorOffset == 2) { - return vec3(tex1.z, tex1.w, tex2.x); - } else { - return vec3(tex1.w, tex2.x, tex2.y); - } - } - } - - vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - return getImage2D(tex, texSize, texDim, z, y, x); - } - - vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 2); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - return vec4(texel.r, texel.g, texel.b, texel.a); - } - - vec4 actualColor; - void color(float r, float g, float b, float a) { - actualColor = vec4(r,g,b,a); - } - - void color(float r, float g, float b) { - color(r,g,b,1.0); - } - - void color(sampler2D image) { - actualColor = texture2D(image, vTexCoord); - } - - float modulo(float number, float divisor) { - if (number < 0.0) { - number = abs(number); - if (divisor < 0.0) { - divisor = abs(divisor); - } - return -mod(number, divisor); - } - if (divisor < 0.0) { - divisor = abs(divisor); - } - return mod(number, divisor); - } - - __INJECTED_NATIVE__; - __MAIN_CONSTANTS__; - __MAIN_ARGUMENTS__; - __KERNEL__; - - void main(void) { - index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; - __MAIN_RESULT__; - }`;module3.exports={fragmentShader}},{}],38:[function(require2,module3,exports3){const{utils}=require2("../../utils");const{FunctionNode}=require2("../function-node");class WebGLFunctionNode extends FunctionNode{constructor(source,settings){super(source,settings);if(settings&&settings.hasOwnProperty("fixIntegerDivisionAccuracy")){this.fixIntegerDivisionAccuracy=settings.fixIntegerDivisionAccuracy}}astConditionalExpression(ast,retArr){if(ast.type!=="ConditionalExpression"){throw this.astErrorOutput("Not a conditional expression",ast)}const consequentType=this.getType(ast.consequent);const alternateType=this.getType(ast.alternate);if(consequentType===null&&alternateType===null){retArr.push("if (");this.astGeneric(ast.test,retArr);retArr.push(") {");this.astGeneric(ast.consequent,retArr);retArr.push(";");retArr.push("} else {");this.astGeneric(ast.alternate,retArr);retArr.push(";");retArr.push("}");return retArr}retArr.push("(");this.astGeneric(ast.test,retArr);retArr.push("?");this.astGeneric(ast.consequent,retArr);retArr.push(":");this.astGeneric(ast.alternate,retArr);retArr.push(")");return retArr}astFunction(ast,retArr){if(this.isRootKernel){retArr.push("void")}else{if(!this.returnType){const lastReturn=this.findLastReturn();if(lastReturn){this.returnType=this.getType(ast.body);if(this.returnType==="LiteralInteger"){this.returnType="Number"}}}const{returnType}=this;if(!returnType){retArr.push("void")}else{const type=typeMap[returnType];if(!type){throw new Error(`unknown type ${returnType}`)}retArr.push(type)}}retArr.push(" ");retArr.push(this.name);retArr.push("(");if(!this.isRootKernel){for(let i=0;i0){retArr.push(", ")}let argumentType=this.argumentTypes[this.argumentNames.indexOf(argumentName)];if(!argumentType){throw this.astErrorOutput(`Unknown argument ${argumentName} type`,ast)}if(argumentType==="LiteralInteger"){this.argumentTypes[i]=argumentType="Number"}const type=typeMap[argumentType];if(!type){throw this.astErrorOutput("Unexpected expression",ast)}const name2=utils.sanitizeName(argumentName);if(type==="sampler2D"||type==="sampler2DArray"){retArr.push(`${type} user_${name2},ivec2 user_${name2}Size,ivec3 user_${name2}Dim`)}else{retArr.push(`${type} user_${name2}`)}}}retArr.push(") {\n");for(let i=0;i"||ast.operator==="<"&&ast.right.type==="Literal"){if(!Number.isInteger(ast.right.value)){this.pushState("building-float");this.castValueToFloat(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.astGeneric(ast.right,retArr);this.popState("building-float");break}}this.pushState("building-integer");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.pushState("casting-to-integer");if(ast.right.type==="Literal"){const literalResult=[];this.astGeneric(ast.right,literalResult);const literalType=this.getType(ast.right);if(literalType==="Integer"){retArr.push(literalResult.join(""))}else{throw this.astErrorOutput(`Unhandled binary expression with literal`,ast)}}else{retArr.push("int(");this.astGeneric(ast.right,retArr);retArr.push(")")}this.popState("casting-to-integer");this.popState("building-integer");break;case"Integer & LiteralInteger":this.pushState("building-integer");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castLiteralToInteger(ast.right,retArr);this.popState("building-integer");break;case"Number & Integer":this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castValueToFloat(ast.right,retArr);this.popState("building-float");break;case"Float & LiteralInteger":case"Number & LiteralInteger":this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castLiteralToFloat(ast.right,retArr);this.popState("building-float");break;case"LiteralInteger & Float":case"LiteralInteger & Number":if(this.isState("casting-to-integer")){this.pushState("building-integer");this.castLiteralToInteger(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castValueToInteger(ast.right,retArr);this.popState("building-integer")}else{this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.pushState("casting-to-float");this.astGeneric(ast.right,retArr);this.popState("casting-to-float");this.popState("building-float")}break;case"LiteralInteger & Integer":this.pushState("building-integer");this.castLiteralToInteger(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.astGeneric(ast.right,retArr);this.popState("building-integer");break;case"Boolean & Boolean":this.pushState("building-boolean");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.astGeneric(ast.right,retArr);this.popState("building-boolean");break;case"Float & Integer":this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castValueToFloat(ast.right,retArr);this.popState("building-float");break;default:throw this.astErrorOutput(`Unhandled binary expression between ${key}`,ast)}retArr.push(")");return retArr}checkAndUpconvertOperator(ast,retArr){const bitwiseResult=this.checkAndUpconvertBitwiseOperators(ast,retArr);if(bitwiseResult){return bitwiseResult}const upconvertableOperators={"%":this.fixIntegerDivisionAccuracy?"integerCorrectionModulo":"modulo","**":"pow"};const foundOperator=upconvertableOperators[ast.operator];if(!foundOperator)return null;retArr.push(foundOperator);retArr.push("(");switch(this.getType(ast.left)){case"Integer":this.castValueToFloat(ast.left,retArr);break;case"LiteralInteger":this.castLiteralToFloat(ast.left,retArr);break;default:this.astGeneric(ast.left,retArr)}retArr.push(",");switch(this.getType(ast.right)){case"Integer":this.castValueToFloat(ast.right,retArr);break;case"LiteralInteger":this.castLiteralToFloat(ast.right,retArr);break;default:this.astGeneric(ast.right,retArr)}retArr.push(")");return retArr}checkAndUpconvertBitwiseOperators(ast,retArr){const upconvertableOperators={"&":"bitwiseAnd","|":"bitwiseOr","^":"bitwiseXOR","<<":"bitwiseZeroFillLeftShift",">>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"};const foundOperator=upconvertableOperators[ast.operator];if(!foundOperator)return null;retArr.push(foundOperator);retArr.push("(");const leftType=this.getType(ast.left);switch(leftType){case"Number":case"Float":this.castValueToInteger(ast.left,retArr);break;case"LiteralInteger":this.castLiteralToInteger(ast.left,retArr);break;default:this.astGeneric(ast.left,retArr)}retArr.push(",");const rightType=this.getType(ast.right);switch(rightType){case"Number":case"Float":this.castValueToInteger(ast.right,retArr);break;case"LiteralInteger":this.castLiteralToInteger(ast.right,retArr);break;default:this.astGeneric(ast.right,retArr)}retArr.push(")");return retArr}checkAndUpconvertBitwiseUnary(ast,retArr){const upconvertableOperators={"~":"bitwiseNot"};const foundOperator=upconvertableOperators[ast.operator];if(!foundOperator)return null;retArr.push(foundOperator);retArr.push("(");switch(this.getType(ast.argument)){case"Number":case"Float":this.castValueToInteger(ast.argument,retArr);break;case"LiteralInteger":this.castLiteralToInteger(ast.argument,retArr);break;default:this.astGeneric(ast.argument,retArr)}retArr.push(")");return retArr}castLiteralToInteger(ast,retArr){this.pushState("casting-to-integer");this.astGeneric(ast,retArr);this.popState("casting-to-integer");return retArr}castLiteralToFloat(ast,retArr){this.pushState("casting-to-float");this.astGeneric(ast,retArr);this.popState("casting-to-float");return retArr}castValueToInteger(ast,retArr){this.pushState("casting-to-integer");retArr.push("int(");this.astGeneric(ast,retArr);retArr.push(")");this.popState("casting-to-integer");return retArr}castValueToFloat(ast,retArr){this.pushState("casting-to-float");retArr.push("float(");this.astGeneric(ast,retArr);retArr.push(")");this.popState("casting-to-float");return retArr}astIdentifierExpression(idtNode,retArr){if(idtNode.type!=="Identifier"){throw this.astErrorOutput("IdentifierExpression - not an Identifier",idtNode)}const type=this.getType(idtNode);const name2=utils.sanitizeName(idtNode.name);if(idtNode.name==="Infinity"){retArr.push("3.402823466e+38")}else if(type==="Boolean"){if(this.argumentNames.indexOf(name2)>-1){retArr.push(`bool(user_${name2})`)}else{retArr.push(`user_${name2}`)}}else{retArr.push(`user_${name2}`)}return retArr}astForStatement(forNode,retArr){if(forNode.type!=="ForStatement"){throw this.astErrorOutput("Invalid for statement",forNode)}const initArr=[];const testArr=[];const updateArr=[];const bodyArr=[];let isSafe=null;if(forNode.init){const{declarations}=forNode.init;if(declarations.length>1){isSafe=false}this.astGeneric(forNode.init,initArr);for(let i=0;i0){retArr.push(initArr.join(""),"\n")}retArr.push(`for (int ${iVariableName}=0;${iVariableName}0){retArr.push(`if (!${testArr.join("")}) break; -`)}retArr.push(bodyArr.join(""));retArr.push(` -${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whileNode,retArr){if(whileNode.type!=="WhileStatement"){throw this.astErrorOutput("Invalid while statement",whileNode)}const iVariableName=this.getInternalVariableName("safeI");retArr.push(`for (int ${iVariableName}=0;${iVariableName}0){declarationSets.push(declarationSet.join(","))}result.push(declarationSets.join(";"));retArr.push(result.join(""));retArr.push(";");return retArr}astIfStatement(ifNode,retArr){retArr.push("if (");this.astGeneric(ifNode.test,retArr);retArr.push(")");if(ifNode.consequent.type==="BlockStatement"){this.astGeneric(ifNode.consequent,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.consequent,retArr);retArr.push("\n}\n")}if(ifNode.alternate){retArr.push("else ");if(ifNode.alternate.type==="BlockStatement"||ifNode.alternate.type==="IfStatement"){this.astGeneric(ifNode.alternate,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.alternate,retArr);retArr.push("\n}\n")}}return retArr}astSwitchStatement(ast,retArr){if(ast.type!=="SwitchStatement"){throw this.astErrorOutput("Invalid switch statement",ast)}const{discriminant,cases}=ast;const type=this.getType(discriminant);const varName=`switchDiscriminant${this.astKey(ast,"_")}`;switch(type){case"Float":case"Number":retArr.push(`float ${varName} = `);this.astGeneric(discriminant,retArr);retArr.push(";\n");break;case"Integer":retArr.push(`int ${varName} = `);this.astGeneric(discriminant,retArr);retArr.push(";\n");break}if(cases.length===1&&!cases[0].test){this.astGeneric(cases[0].consequent,retArr);return retArr}let fallingThrough=false;let defaultResult=[];let movingDefaultToEnd=false;let pastFirstIf=false;for(let i=0;ii+1){movingDefaultToEnd=true;this.astGeneric(cases[i].consequent,defaultResult);continue}else{retArr.push(" else {\n")}}else{if(i===0||!pastFirstIf){pastFirstIf=true;retArr.push(`if (${varName} == `)}else{if(fallingThrough){retArr.push(`${varName} == `);fallingThrough=false}else{retArr.push(` else if (${varName} == `)}}if(type==="Integer"){const testType=this.getType(cases[i].test);switch(testType){case"Number":case"Float":this.castValueToInteger(cases[i].test,retArr);break;case"LiteralInteger":this.castLiteralToInteger(cases[i].test,retArr);break}}else if(type==="Float"){const testType=this.getType(cases[i].test);switch(testType){case"LiteralInteger":this.castLiteralToFloat(cases[i].test,retArr);break;case"Integer":this.castValueToFloat(cases[i].test,retArr);break}}else{throw new Error("unhanlded")}if(!cases[i].consequent||cases[i].consequent.length===0){fallingThrough=true;retArr.push(" || ");continue}retArr.push(`) { -`)}this.astGeneric(cases[i].consequent,retArr);retArr.push("\n}")}if(movingDefaultToEnd){retArr.push(" else {");retArr.push(defaultResult.join(""));retArr.push("}")}return retArr}astThisExpression(tNode,retArr){retArr.push("this");return retArr}astMemberExpression(mNode,retArr){const{property,name:name2,signature,origin,type,xProperty,yProperty,zProperty}=this.getMemberExpressionDetails(mNode);switch(signature){case"value.thread.value":case"this.thread.value":if(name2!=="x"&&name2!=="y"&&name2!=="z"){throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",mNode)}retArr.push(`threadId.${name2}`);return retArr;case"this.output.value":if(this.dynamicOutput){switch(name2){case"x":if(this.isState("casting-to-float")){retArr.push("float(uOutputDim.x)")}else{retArr.push("uOutputDim.x")}break;case"y":if(this.isState("casting-to-float")){retArr.push("float(uOutputDim.y)")}else{retArr.push("uOutputDim.y")}break;case"z":if(this.isState("casting-to-float")){retArr.push("float(uOutputDim.z)")}else{retArr.push("uOutputDim.z")}break;default:throw this.astErrorOutput("Unexpected expression",mNode)}}else{switch(name2){case"x":if(this.isState("casting-to-integer")){retArr.push(this.output[0])}else{retArr.push(this.output[0],".0")}break;case"y":if(this.isState("casting-to-integer")){retArr.push(this.output[1])}else{retArr.push(this.output[1],".0")}break;case"z":if(this.isState("casting-to-integer")){retArr.push(this.output[2])}else{retArr.push(this.output[2],".0")}break;default:throw this.astErrorOutput("Unexpected expression",mNode)}}return retArr;case"value":throw this.astErrorOutput("Unexpected expression",mNode);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if(origin==="Math"){retArr.push(Math[name2]);return retArr}const cleanName=utils.sanitizeName(name2);switch(property){case"r":retArr.push(`user_${cleanName}.r`);return retArr;case"g":retArr.push(`user_${cleanName}.g`);return retArr;case"b":retArr.push(`user_${cleanName}.b`);return retArr;case"a":retArr.push(`user_${cleanName}.a`);return retArr}break;case"this.constants.value":if(typeof xProperty==="undefined"){switch(type){case"Array(2)":case"Array(3)":case"Array(4)":retArr.push(`constants_${utils.sanitizeName(name2)}`);return retArr}}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":this.astCallExpression(mNode.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(property));retArr.push("]");return retArr;case"fn()[][]":this.astCallExpression(mNode.object.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(mNode.object.property));retArr.push("]");retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(mNode.property));retArr.push("]");return retArr;case"[][]":this.astArrayExpression(mNode.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(property));retArr.push("]");return retArr;default:throw this.astErrorOutput("Unexpected expression",mNode)}if(mNode.computed===false){switch(type){case"Number":case"Integer":case"Float":case"Boolean":retArr.push(`${origin}_${utils.sanitizeName(name2)}`);return retArr}}const markupName=`${origin}_${utils.sanitizeName(name2)}`;switch(type){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(mNode.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(xProperty));retArr.push("]");break;case"HTMLImageArray":retArr.push(`getImage3D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(1)":retArr.push(`getFloatFromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":retArr.push(`getMemoryOptimizedVec2(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(2)":retArr.push(`getVec2FromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":retArr.push(`getMemoryOptimizedVec3(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(3)":retArr.push(`getVec3FromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":retArr.push(`getMemoryOptimizedVec4(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":retArr.push(`getVec4FromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if(this.precision==="single"){retArr.push(`getMemoryOptimized32(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")")}else{const bitRatio=origin==="user"?this.lookupFunctionArgumentBitRatio(this.name,name2):this.constantBitRatios[name2];switch(bitRatio){case 1:retArr.push(`get8(${markupName}, ${markupName}Size, ${markupName}Dim, `);break;case 2:retArr.push(`get16(${markupName}, ${markupName}Size, ${markupName}Dim, `);break;case 4:case 0:retArr.push(`get32(${markupName}, ${markupName}Size, ${markupName}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${bitRatio}`)}this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")")}break;case"MemoryOptimizedNumberTexture":retArr.push(`getMemoryOptimized32(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":retArr.push(`${markupName}[${this.memberExpressionPropertyMarkup(yProperty)}]`);if(yProperty){retArr.push(`[${this.memberExpressionPropertyMarkup(xProperty)}]`)}break;default:throw new Error(`unhandled member expression "${type}"`)}return retArr}astCallExpression(ast,retArr){if(!ast.callee){throw this.astErrorOutput("Unknown CallExpression",ast)}let functionName=null;const isMathFunction=this.isAstMathFunction(ast);if(isMathFunction||ast.callee.object&&ast.callee.object.type==="ThisExpression"){functionName=ast.callee.property.name}else if(ast.callee.type==="SequenceExpression"&&ast.callee.expressions[0].type==="Literal"&&!isNaN(ast.callee.expressions[0].raw)){functionName=ast.callee.expressions[1].property.name}else{functionName=ast.callee.name}if(!functionName){throw this.astErrorOutput(`Unhandled function, couldn't find name`,ast)}switch(functionName){case"pow":functionName="_pow";break;case"round":functionName="_round";break}if(this.calledFunctions.indexOf(functionName)<0){this.calledFunctions.push(functionName)}if(functionName==="random"&&this.plugins&&this.plugins.length>0){for(let i=0;i0){retArr.push(", ")}switch(argumentType){case"Integer":this.castValueToFloat(argument,retArr);break;default:this.astGeneric(argument,retArr);break}}}else{const targetTypes=this.lookupFunctionArgumentTypes(functionName)||[];for(let i=0;i0){retArr.push(", ")}const argumentType=this.getType(argument);if(!targetType){this.triggerImplyArgumentType(functionName,i,argumentType,this);targetType=argumentType}switch(argumentType){case"Boolean":this.astGeneric(argument,retArr);continue;case"Number":case"Float":if(targetType==="Integer"){retArr.push("int(");this.astGeneric(argument,retArr);retArr.push(")");continue}else if(targetType==="Number"||targetType==="Float"){this.astGeneric(argument,retArr);continue}else if(targetType==="LiteralInteger"){this.castLiteralToFloat(argument,retArr);continue}break;case"Integer":if(targetType==="Number"||targetType==="Float"){retArr.push("float(");this.astGeneric(argument,retArr);retArr.push(")");continue}else if(targetType==="Integer"){this.astGeneric(argument,retArr);continue}break;case"LiteralInteger":if(targetType==="Integer"){this.castLiteralToInteger(argument,retArr);continue}else if(targetType==="Number"||targetType==="Float"){this.castLiteralToFloat(argument,retArr);continue}else if(targetType==="LiteralInteger"){this.astGeneric(argument,retArr);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(targetType===argumentType){if(argument.type==="Identifier"){retArr.push(`user_${utils.sanitizeName(argument.name)}`)}else if(argument.type==="ArrayExpression"||argument.type==="MemberExpression"||argument.type==="CallExpression"){this.astGeneric(argument,retArr)}else{throw this.astErrorOutput(`Unhandled argument type ${argument.type}`,ast)}continue}break;case"HTMLCanvas":case"HTMLImage":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(targetType===argumentType){if(argument.type!=="Identifier")throw this.astErrorOutput(`Unhandled argument type ${argument.type}`,ast);this.triggerImplyArgumentBitRatio(this.name,argument.name,functionName,i);const name2=utils.sanitizeName(argument.name);retArr.push(`user_${name2},user_${name2}Size,user_${name2}Dim`);continue}break}throw this.astErrorOutput(`Unhandled argument combination of ${argumentType} and ${targetType} for argument named "${argument.name}"`,ast)}}retArr.push(")");return retArr}astArrayExpression(arrNode,retArr){const returnType=this.getType(arrNode);const arrLen=arrNode.elements.length;switch(returnType){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":retArr.push(`mat${arrLen}(`);break;default:retArr.push(`vec${arrLen}(`)}for(let i=0;i0){retArr.push(", ")}const subNode=arrNode.elements[i];this.astGeneric(subNode,retArr)}retArr.push(")");return retArr}memberExpressionXYZ(x2,y,z,retArr){if(z){retArr.push(this.memberExpressionPropertyMarkup(z),", ")}else{retArr.push("0, ")}if(y){retArr.push(this.memberExpressionPropertyMarkup(y),", ")}else{retArr.push("0, ")}retArr.push(this.memberExpressionPropertyMarkup(x2));return retArr}memberExpressionPropertyMarkup(property){if(!property){throw new Error("Property not set")}const type=this.getType(property);const result=[];switch(type){case"Number":case"Float":this.castValueToInteger(property,result);break;case"LiteralInteger":this.castLiteralToInteger(property,result);break;default:this.astGeneric(property,result)}return result.join("")}}const typeMap={"Array":"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4","Array2D":"sampler2D","Array3D":"sampler2D","Boolean":"bool","Float":"float","Input":"sampler2D","Integer":"int","Number":"float","LiteralInteger":"float","NumberTexture":"sampler2D","MemoryOptimizedNumberTexture":"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D","HTMLVideo":"sampler2D","HTMLCanvas":"sampler2D","HTMLImage":"sampler2D","HTMLImageArray":"sampler2DArray"};const operatorMap={"===":"==","!==":"!="};module3.exports={WebGLFunctionNode}},{"../../utils":114,"../function-node":10}],39:[function(require2,module3,exports3){const{WebGLKernelValueBoolean}=require2("./kernel-value/boolean");const{WebGLKernelValueFloat}=require2("./kernel-value/float");const{WebGLKernelValueInteger}=require2("./kernel-value/integer");const{WebGLKernelValueHTMLImage}=require2("./kernel-value/html-image");const{WebGLKernelValueDynamicHTMLImage}=require2("./kernel-value/dynamic-html-image");const{WebGLKernelValueHTMLVideo}=require2("./kernel-value/html-video");const{WebGLKernelValueDynamicHTMLVideo}=require2("./kernel-value/dynamic-html-video");const{WebGLKernelValueSingleInput}=require2("./kernel-value/single-input");const{WebGLKernelValueDynamicSingleInput}=require2("./kernel-value/dynamic-single-input");const{WebGLKernelValueUnsignedInput}=require2("./kernel-value/unsigned-input");const{WebGLKernelValueDynamicUnsignedInput}=require2("./kernel-value/dynamic-unsigned-input");const{WebGLKernelValueMemoryOptimizedNumberTexture}=require2("./kernel-value/memory-optimized-number-texture");const{WebGLKernelValueDynamicMemoryOptimizedNumberTexture}=require2("./kernel-value/dynamic-memory-optimized-number-texture");const{WebGLKernelValueNumberTexture}=require2("./kernel-value/number-texture");const{WebGLKernelValueDynamicNumberTexture}=require2("./kernel-value/dynamic-number-texture");const{WebGLKernelValueSingleArray}=require2("./kernel-value/single-array");const{WebGLKernelValueDynamicSingleArray}=require2("./kernel-value/dynamic-single-array");const{WebGLKernelValueSingleArray1DI}=require2("./kernel-value/single-array1d-i");const{WebGLKernelValueDynamicSingleArray1DI}=require2("./kernel-value/dynamic-single-array1d-i");const{WebGLKernelValueSingleArray2DI}=require2("./kernel-value/single-array2d-i");const{WebGLKernelValueDynamicSingleArray2DI}=require2("./kernel-value/dynamic-single-array2d-i");const{WebGLKernelValueSingleArray3DI}=require2("./kernel-value/single-array3d-i");const{WebGLKernelValueDynamicSingleArray3DI}=require2("./kernel-value/dynamic-single-array3d-i");const{WebGLKernelValueSingleArray2}=require2("./kernel-value/single-array2");const{WebGLKernelValueSingleArray3}=require2("./kernel-value/single-array3");const{WebGLKernelValueSingleArray4}=require2("./kernel-value/single-array4");const{WebGLKernelValueUnsignedArray}=require2("./kernel-value/unsigned-array");const{WebGLKernelValueDynamicUnsignedArray}=require2("./kernel-value/dynamic-unsigned-array");const kernelValueMaps={unsigned:{dynamic:{"Boolean":WebGLKernelValueBoolean,"Integer":WebGLKernelValueInteger,"Float":WebGLKernelValueFloat,"Array":WebGLKernelValueDynamicUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGLKernelValueDynamicUnsignedInput,"NumberTexture":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGLKernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueDynamicHTMLImage,"HTMLImage":WebGLKernelValueDynamicHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueDynamicHTMLVideo},static:{"Boolean":WebGLKernelValueBoolean,"Float":WebGLKernelValueFloat,"Integer":WebGLKernelValueInteger,"Array":WebGLKernelValueUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGLKernelValueUnsignedInput,"NumberTexture":WebGLKernelValueNumberTexture,"ArrayTexture(1)":WebGLKernelValueNumberTexture,"ArrayTexture(2)":WebGLKernelValueNumberTexture,"ArrayTexture(3)":WebGLKernelValueNumberTexture,"ArrayTexture(4)":WebGLKernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueHTMLImage,"HTMLImage":WebGLKernelValueHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueHTMLVideo}},single:{dynamic:{"Boolean":WebGLKernelValueBoolean,"Integer":WebGLKernelValueInteger,"Float":WebGLKernelValueFloat,"Array":WebGLKernelValueDynamicSingleArray,"Array(2)":WebGLKernelValueSingleArray2,"Array(3)":WebGLKernelValueSingleArray3,"Array(4)":WebGLKernelValueSingleArray4,"Array1D(2)":WebGLKernelValueDynamicSingleArray1DI,"Array1D(3)":WebGLKernelValueDynamicSingleArray1DI,"Array1D(4)":WebGLKernelValueDynamicSingleArray1DI,"Array2D(2)":WebGLKernelValueDynamicSingleArray2DI,"Array2D(3)":WebGLKernelValueDynamicSingleArray2DI,"Array2D(4)":WebGLKernelValueDynamicSingleArray2DI,"Array3D(2)":WebGLKernelValueDynamicSingleArray3DI,"Array3D(3)":WebGLKernelValueDynamicSingleArray3DI,"Array3D(4)":WebGLKernelValueDynamicSingleArray3DI,"Input":WebGLKernelValueDynamicSingleInput,"NumberTexture":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGLKernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueDynamicHTMLImage,"HTMLImage":WebGLKernelValueDynamicHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueDynamicHTMLVideo},static:{"Boolean":WebGLKernelValueBoolean,"Float":WebGLKernelValueFloat,"Integer":WebGLKernelValueInteger,"Array":WebGLKernelValueSingleArray,"Array(2)":WebGLKernelValueSingleArray2,"Array(3)":WebGLKernelValueSingleArray3,"Array(4)":WebGLKernelValueSingleArray4,"Array1D(2)":WebGLKernelValueSingleArray1DI,"Array1D(3)":WebGLKernelValueSingleArray1DI,"Array1D(4)":WebGLKernelValueSingleArray1DI,"Array2D(2)":WebGLKernelValueSingleArray2DI,"Array2D(3)":WebGLKernelValueSingleArray2DI,"Array2D(4)":WebGLKernelValueSingleArray2DI,"Array3D(2)":WebGLKernelValueSingleArray3DI,"Array3D(3)":WebGLKernelValueSingleArray3DI,"Array3D(4)":WebGLKernelValueSingleArray3DI,"Input":WebGLKernelValueSingleInput,"NumberTexture":WebGLKernelValueNumberTexture,"ArrayTexture(1)":WebGLKernelValueNumberTexture,"ArrayTexture(2)":WebGLKernelValueNumberTexture,"ArrayTexture(3)":WebGLKernelValueNumberTexture,"ArrayTexture(4)":WebGLKernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueHTMLImage,"HTMLImage":WebGLKernelValueHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueHTMLVideo}}};function lookupKernelValueType(type,dynamic,precision,value2){if(!type){throw new Error("type missing")}if(!dynamic){throw new Error("dynamic missing")}if(!precision){throw new Error("precision missing")}if(value2.type){type=value2.type}const types=kernelValueMaps[precision][dynamic];if(types[type]===false){return null}else if(types[type]===void 0){throw new Error(`Could not find a KernelValue for ${type}`)}return types[type]}module3.exports={lookupKernelValueType,kernelValueMaps}},{"./kernel-value/boolean":41,"./kernel-value/dynamic-html-image":42,"./kernel-value/dynamic-html-video":43,"./kernel-value/dynamic-memory-optimized-number-texture":44,"./kernel-value/dynamic-number-texture":45,"./kernel-value/dynamic-single-array":46,"./kernel-value/dynamic-single-array1d-i":47,"./kernel-value/dynamic-single-array2d-i":48,"./kernel-value/dynamic-single-array3d-i":49,"./kernel-value/dynamic-single-input":50,"./kernel-value/dynamic-unsigned-array":51,"./kernel-value/dynamic-unsigned-input":52,"./kernel-value/float":53,"./kernel-value/html-image":54,"./kernel-value/html-video":55,"./kernel-value/integer":57,"./kernel-value/memory-optimized-number-texture":58,"./kernel-value/number-texture":59,"./kernel-value/single-array":60,"./kernel-value/single-array1d-i":61,"./kernel-value/single-array2":62,"./kernel-value/single-array2d-i":63,"./kernel-value/single-array3":64,"./kernel-value/single-array3d-i":65,"./kernel-value/single-array4":66,"./kernel-value/single-input":67,"./kernel-value/unsigned-array":68,"./kernel-value/unsigned-input":69}],40:[function(require2,module3,exports3){const{WebGLKernelValue}=require2("./index");const{Input}=require2("../../../input");class WebGLKernelArray extends WebGLKernelValue{checkSize(width,height){if(!this.kernel.validate)return;const{maxTextureSize}=this.kernel.constructor.features;if(width>maxTextureSize||height>maxTextureSize){if(width>height){throw new Error(`Argument texture width of ${width} larger than maximum size of ${maxTextureSize} for your GPU`)}else if(widthpluginName===plugin.name);if(usePlugin){pluginsToUse.push(plugin)}}}}return pluginsToUse}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(args){if(!this.validate){this.texSize=utils.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output);return}const{features:features2}=this.constructor;if(this.optimizeFloatMemory===true&&!features2.isTextureFloat){throw new Error("Float textures are not supported")}else if(this.precision==="single"&&!features2.isFloatRead){throw new Error("Single precision not supported")}else if(!this.graphical&&this.precision===null&&features2.isTextureFloat){this.precision=features2.isFloatRead?"single":"unsigned"}if(this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers){throw new Error("could not instantiate draw buffers extension")}if(this.fixIntegerDivisionAccuracy===null){this.fixIntegerDivisionAccuracy=!features2.isIntegerDivisionAccurate}else if(this.fixIntegerDivisionAccuracy&&features2.isIntegerDivisionAccurate){this.fixIntegerDivisionAccuracy=false}this.checkOutput();if(!this.output||this.output.length===0){if(args.length!==1){throw new Error("Auto output only supported for kernels with only one input")}const argType=utils.getVariableType(args[0],this.strictIntegers);switch(argType){case"Array":this.output=utils.getDimensions(argType);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=args[0].output;break;default:throw new Error("Auto output not supported for input type: "+argType)}}if(this.graphical){if(this.output.length!==2){throw new Error("Output must have 2 dimensions on graphical mode")}if(this.precision==="precision"){this.precision="unsigned";console.warn("Cannot use graphical mode and single precision at the same time")}this.texSize=utils.clone(this.output);return}else if(this.precision===null&&features2.isTextureFloat){this.precision="single"}this.texSize=utils.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output);this.checkTextureSize()}updateMaxTexSize(){const{texSize,canvas}=this;if(this.maxTexSize===null){let canvasIndex=canvases.indexOf(canvas);if(canvasIndex===-1){canvasIndex=canvases.length;canvases.push(canvas);maxTexSizes[canvasIndex]=[texSize[0],texSize[1]]}this.maxTexSize=maxTexSizes[canvasIndex]}if(this.maxTexSize[0]this.argumentNames.length){throw new Error("too many arguments for kernel")}const{context:gl}=this;let textureIndexes=0;const onRequestTexture=()=>{return this.createTexture()};const onRequestIndex=()=>{return this.constantTextureCount+textureIndexes++};const onUpdateValueMismatch=constructor=>{this.switchKernels({type:"argumentMismatch",needed:constructor})};const onRequestContextHandle=()=>{return gl.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++};for(let index=0;index{return this.createTexture()},onRequestIndex:()=>{return textureIndexes++},onRequestContextHandle:()=>{return gl.TEXTURE0+this.constantTextureCount++}});this.constantBitRatios[name2]=kernelValue.bitRatio;this.kernelConstants.push(kernelValue);kernelValue.setup();if(kernelValue.forceUploadEachRun){this.forceUploadKernelConstants.push(kernelValue)}}}build(){if(this.built)return;this.initExtensions();this.validateSettings(arguments);this.setupConstants(arguments);if(this.fallbackRequested)return;this.setupArguments(arguments);if(this.fallbackRequested)return;this.updateMaxTexSize();this.translateSource();const failureResult=this.pickRenderStrategy(arguments);if(failureResult){return failureResult}const{texSize,context:gl,canvas}=this;gl.enable(gl.SCISSOR_TEST);if(this.pipeline&&this.precision==="single"){gl.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]);canvas.width=this.maxTexSize[0];canvas.height=this.maxTexSize[1]}else{gl.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]);canvas.width=this.maxTexSize[0];canvas.height=this.maxTexSize[1]}const threadDim=this.threadDim=Array.from(this.output);while(threadDim.length<3){threadDim.push(1)}const compiledVertexShader=this.getVertexShader(arguments);const vertShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertShader,compiledVertexShader);gl.compileShader(vertShader);this.vertShader=vertShader;const compiledFragmentShader=this.getFragmentShader(arguments);const fragShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragShader,compiledFragmentShader);gl.compileShader(fragShader);this.fragShader=fragShader;if(this.debug){console.log("GLSL Shader Output:");console.log(compiledFragmentShader)}if(!gl.getShaderParameter(vertShader,gl.COMPILE_STATUS)){throw new Error("Error compiling vertex shader: "+gl.getShaderInfoLog(vertShader))}if(!gl.getShaderParameter(fragShader,gl.COMPILE_STATUS)){throw new Error("Error compiling fragment shader: "+gl.getShaderInfoLog(fragShader))}const program=this.program=gl.createProgram();gl.attachShader(program,vertShader);gl.attachShader(program,fragShader);gl.linkProgram(program);this.framebuffer=gl.createFramebuffer();this.framebuffer.width=texSize[0];this.framebuffer.height=texSize[1];this.rawValueFramebuffers={};const vertices=new Float32Array([-1,-1,1,-1,-1,1,1,1]);const texCoords=new Float32Array([0,0,1,0,0,1,1,1]);const texCoordOffset=vertices.byteLength;let buffer=this.buffer;if(!buffer){buffer=this.buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,vertices.byteLength+texCoords.byteLength,gl.STATIC_DRAW)}else{gl.bindBuffer(gl.ARRAY_BUFFER,buffer)}gl.bufferSubData(gl.ARRAY_BUFFER,0,vertices);gl.bufferSubData(gl.ARRAY_BUFFER,texCoordOffset,texCoords);const aPosLoc=gl.getAttribLocation(this.program,"aPos");gl.enableVertexAttribArray(aPosLoc);gl.vertexAttribPointer(aPosLoc,2,gl.FLOAT,false,0,0);const aTexCoordLoc=gl.getAttribLocation(this.program,"aTexCoord");gl.enableVertexAttribArray(aTexCoordLoc);gl.vertexAttribPointer(aTexCoordLoc,2,gl.FLOAT,false,0,texCoordOffset);gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer);let i=0;gl.useProgram(this.program);for(let p in this.constants){this.kernelConstants[i++].updateValue(this.constants[p])}this._setupOutputTexture();if(this.subKernels!==null&&this.subKernels.length>0){this._mappedTextureSwitched={};this._setupSubOutputTextures()}this.buildSignature(arguments);this.built=true}translateSource(){const functionBuilder=FunctionBuilder.fromKernel(this,WebGLFunctionNode,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=functionBuilder.getPrototypeString("kernel");this.setupReturnTypes(functionBuilder)}setupReturnTypes(functionBuilder){if(!this.graphical&&!this.returnType){this.returnType=functionBuilder.getKernelResultType()}if(this.subKernels&&this.subKernels.length>0){for(let i=0;iplugin.source&&this.source.match(plugin.functionMatch)?plugin.source:"").join("\n")}_getConstantsString(){const result=[];const{threadDim,texSize}=this;if(this.dynamicOutput){result.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize")}else{result.push(`ivec3 uOutputDim = ivec3(${threadDim[0]}, ${threadDim[1]}, ${threadDim[2]})`,`ivec2 uTexSize = ivec2(${texSize[0]}, ${texSize[1]})`)}return utils.linesToString(result)}_getTextureCoordinate(){const subKernels=this.subKernels;if(subKernels===null||subKernels.length<1){return"varying vec2 vTexCoord;\n"}else{return"out vec2 vTexCoord;\n"}}_getDecode32EndiannessString(){return this.endianness==="LE"?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return this.endianness==="LE"?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?`float divWithIntCheck(float x, float y) { - if (floor(x) == x && floor(y) == y && integerMod(x, y) == 0.0) { - return float(int(x) / int(y)); - } - return x / y; - } - - float integerCorrectionModulo(float number, float divisor) { - if (number < 0.0) { - number = abs(number); - if (divisor < 0.0) { - divisor = abs(divisor); - } - return -(number - (divisor * floor(divWithIntCheck(number, divisor)))); - } - if (divisor < 0.0) { - divisor = abs(divisor); - } - return number - (divisor * floor(divWithIntCheck(number, divisor))); - }`:""}_getMainArgumentsString(args){const results=[];const{argumentNames}=this;for(let i=0;i{if(map.hasOwnProperty(artifact)){return map[artifact]}throw`unhandled artifact ${artifact}`})}getFragmentShader(args){if(this.compiledFragmentShader!==null){return this.compiledFragmentShader}return this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(args))}getVertexShader(args){if(this.compiledVertexShader!==null){return this.compiledVertexShader}return this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(args))}toString(){const setupContextString=utils.linesToString([`const gl = context`]);return glKernelString(this.constructor,arguments,this,setupContextString)}destroy(removeCanvasReferences){if(!this.context)return;if(this.buffer){this.context.deleteBuffer(this.buffer)}if(this.framebuffer){this.context.deleteFramebuffer(this.framebuffer)}for(const width in this.rawValueFramebuffers){for(const height in this.rawValueFramebuffers[width]){this.context.deleteFramebuffer(this.rawValueFramebuffers[width][height]);delete this.rawValueFramebuffers[width][height]}delete this.rawValueFramebuffers[width]}if(this.vertShader){this.context.deleteShader(this.vertShader)}if(this.fragShader){this.context.deleteShader(this.fragShader)}if(this.program){this.context.deleteProgram(this.program)}if(this.texture){this.texture.delete();const textureCacheIndex=this.textureCache.indexOf(this.texture.texture);if(textureCacheIndex>-1){this.textureCache.splice(textureCacheIndex,1)}this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let i2=0;i2-1){this.textureCache.splice(textureCacheIndex,1)}}this.mappedTextures=null}if(this.kernelArguments){for(let i2=0;i20){const texture=this.textureCache.pop();this.context.deleteTexture(texture)}if(removeCanvasReferences){const idx=canvases.indexOf(this.canvas);if(idx>=0){canvases[idx]=null;maxTexSizes[idx]=null}}this.destroyExtensions();delete this.context;delete this.canvas;if(!this.gpu)return;const i=this.gpu.kernels.indexOf(this);if(i===-1)return;this.gpu.kernels.splice(i,1)}destroyExtensions(){this.extensions.OES_texture_float=null;this.extensions.OES_texture_float_linear=null;this.extensions.OES_element_index_uint=null;this.extensions.WEBGL_draw_buffers=null}static destroyContext(context){const extension=context.getExtension("WEBGL_lose_context");if(extension){extension.loseContext()}}toJSON(){const json=super.toJSON();json.functionNodes=FunctionBuilder.fromKernel(this,WebGLFunctionNode).toJSON();json.settings.threadDim=this.threadDim;return json}}module3.exports={WebGLKernel}},{"../../plugins/math-random-uniformly-distributed":112,"../../utils":114,"../function-builder":9,"../gl/kernel":13,"../gl/kernel-string":12,"./fragment-shader":37,"./function-node":38,"./kernel-value-maps":39,"./vertex-shader":71}],71:[function(require2,module3,exports3){const vertexShader=`__FLOAT_TACTIC_DECLARATION__; - __INT_TACTIC_DECLARATION__; - __SAMPLER_2D_TACTIC_DECLARATION__; - - attribute vec2 aPos; - attribute vec2 aTexCoord; - - varying vec2 vTexCoord; - uniform vec2 ratio; - - void main(void) { - gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); - vTexCoord = aTexCoord; - }`;module3.exports={vertexShader}},{}],72:[function(require2,module3,exports3){const fragmentShader=`#version 300 es - __HEADER__; - __FLOAT_TACTIC_DECLARATION__; - __INT_TACTIC_DECLARATION__; - __SAMPLER_2D_TACTIC_DECLARATION__; - __SAMPLER_2D_ARRAY_TACTIC_DECLARATION__; - - const int LOOP_MAX = __LOOP_MAX__; - - __PLUGINS__; - __CONSTANTS__; - - in vec2 vTexCoord; - - float atan2(float v1, float v2) { - if (v1 == 0.0 || v2 == 0.0) return 0.0; - return atan(v1 / v2); - } - - float cbrt(float x) { - if (x >= 0.0) { - return pow(x, 1.0 / 3.0); - } else { - return -pow(x, 1.0 / 3.0); - } - } - - float expm1(float x) { - return pow(${Math.E}, x) - 1.0; - } - - float fround(highp float x) { - return x; - } - - float imul(float v1, float v2) { - return float(int(v1) * int(v2)); - } - - float log10(float x) { - return log2(x) * (1.0 / log2(10.0)); - } - - float log1p(float x) { - return log(1.0 + x); - } - - float _pow(float v1, float v2) { - if (v2 == 0.0) return 1.0; - return pow(v1, v2); - } - - float _round(float x) { - return floor(x + 0.5); - } - - - const int BIT_COUNT = 32; - int modi(int x, int y) { - return x - y * (x / y); - } - - int bitwiseOr(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseXOR(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseAnd(int a, int b) { - int result = 0; - int n = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 && b > 0)) { - break; - } - } - return result; - } - int bitwiseNot(int a) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if (modi(a, 2) == 0) { - result += n; - } - a = a / 2; - n = n * 2; - } - return result; - } - int bitwiseZeroFillLeftShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n *= 2; - } - - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - int bitwiseSignedRightShift(int num, int shifts) { - return int(floor(float(num) / pow(2.0, float(shifts)))); - } - - int bitwiseZeroFillRightShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n /= 2; - } - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - vec2 integerMod(vec2 x, float y) { - vec2 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec3 integerMod(vec3 x, float y) { - vec3 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec4 integerMod(vec4 x, vec4 y) { - vec4 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - float integerMod(float x, float y) { - float res = floor(mod(x, y)); - return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); - } - - int integerMod(int x, int y) { - return x - (y * int(x/y)); - } - - __DIVIDE_WITH_INTEGER_CHECK__; - - // Here be dragons! - // DO NOT OPTIMIZE THIS CODE - // YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE - // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME - const vec2 MAGIC_VEC = vec2(1.0, -256.0); - const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); - const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 - float decode32(vec4 texel) { - __DECODE32_ENDIANNESS__; - texel *= 255.0; - vec2 gte128; - gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; - gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; - float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); - float res = exp2(round(exponent)); - texel.b = texel.b - 128.0 * gte128.x; - res = dot(texel, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res; - res *= gte128.y * -2.0 + 1.0; - return res; - } - - float decode16(vec4 texel, int index) { - int channel = integerMod(index, 2); - return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0; - } - - float decode8(vec4 texel, int index) { - int channel = integerMod(index, 4); - return texel[channel] * 255.0; - } - - vec4 legacyEncode32(float f) { - float F = abs(f); - float sign = f < 0.0 ? 1.0 : 0.0; - float exponent = floor(log2(F)); - float mantissa = (exp2(-exponent) * F); - // exponent += floor(log2(mantissa)); - vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; - texel.rg = integerMod(texel.rg, 256.0); - texel.b = integerMod(texel.b, 128.0); - texel.a = exponent*0.5 + 63.5; - texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; - texel = floor(texel); - texel *= 0.003921569; // 1/255 - __ENCODE32_ENDIANNESS__; - return texel; - } - - // https://github.com/gpujs/gpu.js/wiki/Encoder-details - vec4 encode32(float value) { - if (value == 0.0) return vec4(0, 0, 0, 0); - - float exponent; - float mantissa; - vec4 result; - float sgn; - - sgn = step(0.0, -value); - value = abs(value); - - exponent = floor(log2(value)); - - mantissa = value*pow(2.0, -exponent)-1.0; - exponent = exponent+127.0; - result = vec4(0,0,0,0); - - result.a = floor(exponent/2.0); - exponent = exponent - result.a*2.0; - result.a = result.a + 128.0*sgn; - - result.b = floor(mantissa * 128.0); - mantissa = mantissa - result.b / 128.0; - result.b = result.b + exponent*128.0; - - result.g = floor(mantissa*32768.0); - mantissa = mantissa - result.g/32768.0; - - result.r = floor(mantissa*8388608.0); - return result/255.0; - } - // Dragons end here - - int index; - ivec3 threadId; - - ivec3 indexTo3D(int idx, ivec3 texDim) { - int z = int(idx / (texDim.x * texDim.y)); - idx -= z * int(texDim.x * texDim.y); - int y = int(idx / texDim.x); - int x = int(integerMod(idx, texDim.x)); - return ivec3(x, y, z); - } - - float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize)); - return decode32(texel); - } - - float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int w = texSize.x * 2; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y)); - return decode16(texel, index); - } - - float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int w = texSize.x * 4; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y)); - return decode8(texel, index); - } - - float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int channel = integerMod(index, 4); - index = index / 4; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - index = index / 4; - vec4 texel = texture(tex, st / vec2(texSize)); - return texel[channel]; - } - - vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - return texture(tex, st / vec2(texSize)); - } - - vec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - return texture(tex, vec3(st / vec2(texSize), z)); - } - - float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return result[0]; - } - - vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec2(result[0], result[1]); - } - - vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 2); - index = index / 2; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize)); - if (channel == 0) return vec2(texel.r, texel.g); - if (channel == 1) return vec2(texel.b, texel.a); - return vec2(0.0, 0.0); - } - - vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec3(result[0], result[1], result[2]); - } - - vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); - int vectorIndex = fieldIndex / 4; - int vectorOffset = fieldIndex - vectorIndex * 4; - int readY = vectorIndex / texSize.x; - int readX = vectorIndex - readY * texSize.x; - vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); - - if (vectorOffset == 0) { - return tex1.xyz; - } else if (vectorOffset == 1) { - return tex1.yzw; - } else { - readX++; - if (readX >= texSize.x) { - readX = 0; - readY++; - } - vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize)); - if (vectorOffset == 2) { - return vec3(tex1.z, tex1.w, tex2.x); - } else { - return vec3(tex1.w, tex2.x, tex2.y); - } - } - } - - vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - return getImage2D(tex, texSize, texDim, z, y, x); - } - - vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 2); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize)); - return vec4(texel.r, texel.g, texel.b, texel.a); - } - - vec4 actualColor; - void color(float r, float g, float b, float a) { - actualColor = vec4(r,g,b,a); - } - - void color(float r, float g, float b) { - color(r,g,b,1.0); - } - - float modulo(float number, float divisor) { - if (number < 0.0) { - number = abs(number); - if (divisor < 0.0) { - divisor = abs(divisor); - } - return -mod(number, divisor); - } - if (divisor < 0.0) { - divisor = abs(divisor); - } - return mod(number, divisor); - } - - __INJECTED_NATIVE__; - __MAIN_CONSTANTS__; - __MAIN_ARGUMENTS__; - __KERNEL__; - - void main(void) { - index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; - __MAIN_RESULT__; - }`;module3.exports={fragmentShader}},{}],73:[function(require2,module3,exports3){const{utils}=require2("../../utils");const{WebGLFunctionNode}=require2("../web-gl/function-node");class WebGL2FunctionNode extends WebGLFunctionNode{astIdentifierExpression(idtNode,retArr){if(idtNode.type!=="Identifier"){throw this.astErrorOutput("IdentifierExpression - not an Identifier",idtNode)}const type=this.getType(idtNode);const name2=utils.sanitizeName(idtNode.name);if(idtNode.name==="Infinity"){retArr.push("intBitsToFloat(2139095039)")}else if(type==="Boolean"){if(this.argumentNames.indexOf(name2)>-1){retArr.push(`bool(user_${name2})`)}else{retArr.push(`user_${name2}`)}}else{retArr.push(`user_${name2}`)}return retArr}}module3.exports={WebGL2FunctionNode}},{"../../utils":114,"../web-gl/function-node":38}],74:[function(require2,module3,exports3){const{WebGL2KernelValueBoolean}=require2("./kernel-value/boolean");const{WebGL2KernelValueFloat}=require2("./kernel-value/float");const{WebGL2KernelValueInteger}=require2("./kernel-value/integer");const{WebGL2KernelValueHTMLImage}=require2("./kernel-value/html-image");const{WebGL2KernelValueDynamicHTMLImage}=require2("./kernel-value/dynamic-html-image");const{WebGL2KernelValueHTMLImageArray}=require2("./kernel-value/html-image-array");const{WebGL2KernelValueDynamicHTMLImageArray}=require2("./kernel-value/dynamic-html-image-array");const{WebGL2KernelValueHTMLVideo}=require2("./kernel-value/html-video");const{WebGL2KernelValueDynamicHTMLVideo}=require2("./kernel-value/dynamic-html-video");const{WebGL2KernelValueSingleInput}=require2("./kernel-value/single-input");const{WebGL2KernelValueDynamicSingleInput}=require2("./kernel-value/dynamic-single-input");const{WebGL2KernelValueUnsignedInput}=require2("./kernel-value/unsigned-input");const{WebGL2KernelValueDynamicUnsignedInput}=require2("./kernel-value/dynamic-unsigned-input");const{WebGL2KernelValueMemoryOptimizedNumberTexture}=require2("./kernel-value/memory-optimized-number-texture");const{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture}=require2("./kernel-value/dynamic-memory-optimized-number-texture");const{WebGL2KernelValueNumberTexture}=require2("./kernel-value/number-texture");const{WebGL2KernelValueDynamicNumberTexture}=require2("./kernel-value/dynamic-number-texture");const{WebGL2KernelValueSingleArray}=require2("./kernel-value/single-array");const{WebGL2KernelValueDynamicSingleArray}=require2("./kernel-value/dynamic-single-array");const{WebGL2KernelValueSingleArray1DI}=require2("./kernel-value/single-array1d-i");const{WebGL2KernelValueDynamicSingleArray1DI}=require2("./kernel-value/dynamic-single-array1d-i");const{WebGL2KernelValueSingleArray2DI}=require2("./kernel-value/single-array2d-i");const{WebGL2KernelValueDynamicSingleArray2DI}=require2("./kernel-value/dynamic-single-array2d-i");const{WebGL2KernelValueSingleArray3DI}=require2("./kernel-value/single-array3d-i");const{WebGL2KernelValueDynamicSingleArray3DI}=require2("./kernel-value/dynamic-single-array3d-i");const{WebGL2KernelValueSingleArray2}=require2("./kernel-value/single-array2");const{WebGL2KernelValueSingleArray3}=require2("./kernel-value/single-array3");const{WebGL2KernelValueSingleArray4}=require2("./kernel-value/single-array4");const{WebGL2KernelValueUnsignedArray}=require2("./kernel-value/unsigned-array");const{WebGL2KernelValueDynamicUnsignedArray}=require2("./kernel-value/dynamic-unsigned-array");const kernelValueMaps={unsigned:{dynamic:{"Boolean":WebGL2KernelValueBoolean,"Integer":WebGL2KernelValueInteger,"Float":WebGL2KernelValueFloat,"Array":WebGL2KernelValueDynamicUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGL2KernelValueDynamicUnsignedInput,"NumberTexture":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGL2KernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueDynamicHTMLImage,"HTMLImage":WebGL2KernelValueDynamicHTMLImage,"HTMLImageArray":WebGL2KernelValueDynamicHTMLImageArray,"HTMLVideo":WebGL2KernelValueDynamicHTMLVideo},static:{"Boolean":WebGL2KernelValueBoolean,"Float":WebGL2KernelValueFloat,"Integer":WebGL2KernelValueInteger,"Array":WebGL2KernelValueUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGL2KernelValueUnsignedInput,"NumberTexture":WebGL2KernelValueNumberTexture,"ArrayTexture(1)":WebGL2KernelValueNumberTexture,"ArrayTexture(2)":WebGL2KernelValueNumberTexture,"ArrayTexture(3)":WebGL2KernelValueNumberTexture,"ArrayTexture(4)":WebGL2KernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueHTMLImage,"HTMLImage":WebGL2KernelValueHTMLImage,"HTMLImageArray":WebGL2KernelValueHTMLImageArray,"HTMLVideo":WebGL2KernelValueHTMLVideo}},single:{dynamic:{"Boolean":WebGL2KernelValueBoolean,"Integer":WebGL2KernelValueInteger,"Float":WebGL2KernelValueFloat,"Array":WebGL2KernelValueDynamicSingleArray,"Array(2)":WebGL2KernelValueSingleArray2,"Array(3)":WebGL2KernelValueSingleArray3,"Array(4)":WebGL2KernelValueSingleArray4,"Array1D(2)":WebGL2KernelValueDynamicSingleArray1DI,"Array1D(3)":WebGL2KernelValueDynamicSingleArray1DI,"Array1D(4)":WebGL2KernelValueDynamicSingleArray1DI,"Array2D(2)":WebGL2KernelValueDynamicSingleArray2DI,"Array2D(3)":WebGL2KernelValueDynamicSingleArray2DI,"Array2D(4)":WebGL2KernelValueDynamicSingleArray2DI,"Array3D(2)":WebGL2KernelValueDynamicSingleArray3DI,"Array3D(3)":WebGL2KernelValueDynamicSingleArray3DI,"Array3D(4)":WebGL2KernelValueDynamicSingleArray3DI,"Input":WebGL2KernelValueDynamicSingleInput,"NumberTexture":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGL2KernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueDynamicHTMLImage,"HTMLImage":WebGL2KernelValueDynamicHTMLImage,"HTMLImageArray":WebGL2KernelValueDynamicHTMLImageArray,"HTMLVideo":WebGL2KernelValueDynamicHTMLVideo},static:{"Boolean":WebGL2KernelValueBoolean,"Float":WebGL2KernelValueFloat,"Integer":WebGL2KernelValueInteger,"Array":WebGL2KernelValueSingleArray,"Array(2)":WebGL2KernelValueSingleArray2,"Array(3)":WebGL2KernelValueSingleArray3,"Array(4)":WebGL2KernelValueSingleArray4,"Array1D(2)":WebGL2KernelValueSingleArray1DI,"Array1D(3)":WebGL2KernelValueSingleArray1DI,"Array1D(4)":WebGL2KernelValueSingleArray1DI,"Array2D(2)":WebGL2KernelValueSingleArray2DI,"Array2D(3)":WebGL2KernelValueSingleArray2DI,"Array2D(4)":WebGL2KernelValueSingleArray2DI,"Array3D(2)":WebGL2KernelValueSingleArray3DI,"Array3D(3)":WebGL2KernelValueSingleArray3DI,"Array3D(4)":WebGL2KernelValueSingleArray3DI,"Input":WebGL2KernelValueSingleInput,"NumberTexture":WebGL2KernelValueNumberTexture,"ArrayTexture(1)":WebGL2KernelValueNumberTexture,"ArrayTexture(2)":WebGL2KernelValueNumberTexture,"ArrayTexture(3)":WebGL2KernelValueNumberTexture,"ArrayTexture(4)":WebGL2KernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueHTMLImage,"HTMLImage":WebGL2KernelValueHTMLImage,"HTMLImageArray":WebGL2KernelValueHTMLImageArray,"HTMLVideo":WebGL2KernelValueHTMLVideo}}};function lookupKernelValueType(type,dynamic,precision,value2){if(!type){throw new Error("type missing")}if(!dynamic){throw new Error("dynamic missing")}if(!precision){throw new Error("precision missing")}if(value2.type){type=value2.type}const types=kernelValueMaps[precision][dynamic];if(types[type]===false){return null}else if(types[type]===void 0){throw new Error(`Could not find a KernelValue for ${type}`)}return types[type]}module3.exports={kernelValueMaps,lookupKernelValueType}},{"./kernel-value/boolean":75,"./kernel-value/dynamic-html-image":77,"./kernel-value/dynamic-html-image-array":76,"./kernel-value/dynamic-html-video":78,"./kernel-value/dynamic-memory-optimized-number-texture":79,"./kernel-value/dynamic-number-texture":80,"./kernel-value/dynamic-single-array":81,"./kernel-value/dynamic-single-array1d-i":82,"./kernel-value/dynamic-single-array2d-i":83,"./kernel-value/dynamic-single-array3d-i":84,"./kernel-value/dynamic-single-input":85,"./kernel-value/dynamic-unsigned-array":86,"./kernel-value/dynamic-unsigned-input":87,"./kernel-value/float":88,"./kernel-value/html-image":90,"./kernel-value/html-image-array":89,"./kernel-value/html-video":91,"./kernel-value/integer":92,"./kernel-value/memory-optimized-number-texture":93,"./kernel-value/number-texture":94,"./kernel-value/single-array":95,"./kernel-value/single-array1d-i":96,"./kernel-value/single-array2":97,"./kernel-value/single-array2d-i":98,"./kernel-value/single-array3":99,"./kernel-value/single-array3d-i":100,"./kernel-value/single-array4":101,"./kernel-value/single-input":102,"./kernel-value/unsigned-array":103,"./kernel-value/unsigned-input":104}],75:[function(require2,module3,exports3){const{WebGLKernelValueBoolean}=require2("../../web-gl/kernel-value/boolean");class WebGL2KernelValueBoolean extends WebGLKernelValueBoolean{}module3.exports={WebGL2KernelValueBoolean}},{"../../web-gl/kernel-value/boolean":41}],76:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueHTMLImageArray}=require2("./html-image-array");class WebGL2KernelValueDynamicHTMLImageArray extends WebGL2KernelValueHTMLImageArray{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2DArray ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(images){const{width,height}=images[0];this.checkSize(width,height);this.dimensions=[width,height,images.length];this.textureSize=[width,height];this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(images)}}module3.exports={WebGL2KernelValueDynamicHTMLImageArray}},{"../../../utils":114,"./html-image-array":89}],77:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicHTMLImage}=require2("../../web-gl/kernel-value/dynamic-html-image");class WebGL2KernelValueDynamicHTMLImage extends WebGLKernelValueDynamicHTMLImage{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicHTMLImage}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-html-image":42}],78:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueDynamicHTMLImage}=require2("./dynamic-html-image");class WebGL2KernelValueDynamicHTMLVideo extends WebGL2KernelValueDynamicHTMLImage{}module3.exports={WebGL2KernelValueDynamicHTMLVideo}},{"../../../utils":114,"./dynamic-html-image":77}],79:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicMemoryOptimizedNumberTexture}=require2("../../web-gl/kernel-value/dynamic-memory-optimized-number-texture");class WebGL2KernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueDynamicMemoryOptimizedNumberTexture{getSource(){return utils.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-memory-optimized-number-texture":44}],80:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicNumberTexture}=require2("../../web-gl/kernel-value/dynamic-number-texture");class WebGL2KernelValueDynamicNumberTexture extends WebGLKernelValueDynamicNumberTexture{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicNumberTexture}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-number-texture":45}],81:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray}=require2("../../web-gl2/kernel-value/single-array");class WebGL2KernelValueDynamicSingleArray extends WebGL2KernelValueSingleArray{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.dimensions=utils.getDimensions(value2,true);this.textureSize=utils.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio);this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio;this.checkSize(this.textureSize[0],this.textureSize[1]);this.uploadValue=new Float32Array(this.uploadArrayLength);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array":95}],82:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray1DI}=require2("../../web-gl2/kernel-value/single-array1d-i");class WebGL2KernelValueDynamicSingleArray1DI extends WebGL2KernelValueSingleArray1DI{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.setShape(value2);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray1DI}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array1d-i":96}],83:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray2DI}=require2("../../web-gl2/kernel-value/single-array2d-i");class WebGL2KernelValueDynamicSingleArray2DI extends WebGL2KernelValueSingleArray2DI{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.setShape(value2);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray2DI}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array2d-i":98}],84:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray3DI}=require2("../../web-gl2/kernel-value/single-array3d-i");class WebGL2KernelValueDynamicSingleArray3DI extends WebGL2KernelValueSingleArray3DI{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.setShape(value2);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray3DI}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array3d-i":100}],85:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleInput}=require2("../../web-gl2/kernel-value/single-input");class WebGL2KernelValueDynamicSingleInput extends WebGL2KernelValueSingleInput{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){let[w,h,d]=value2.size;this.dimensions=new Int32Array([w||1,h||1,d||1]);this.textureSize=utils.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio);this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio;this.checkSize(this.textureSize[0],this.textureSize[1]);this.uploadValue=new Float32Array(this.uploadArrayLength);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleInput}},{"../../../utils":114,"../../web-gl2/kernel-value/single-input":102}],86:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicUnsignedArray}=require2("../../web-gl/kernel-value/dynamic-unsigned-array");class WebGL2KernelValueDynamicUnsignedArray extends WebGLKernelValueDynamicUnsignedArray{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicUnsignedArray}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-unsigned-array":51}],87:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicUnsignedInput}=require2("../../web-gl/kernel-value/dynamic-unsigned-input");class WebGL2KernelValueDynamicUnsignedInput extends WebGLKernelValueDynamicUnsignedInput{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicUnsignedInput}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-unsigned-input":52}],88:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueFloat}=require2("../../web-gl/kernel-value/float");class WebGL2KernelValueFloat extends WebGLKernelValueFloat{}module3.exports={WebGL2KernelValueFloat}},{"../../../utils":114,"../../web-gl/kernel-value/float":53}],89:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelArray}=require2("../../web-gl/kernel-value/array");class WebGL2KernelValueHTMLImageArray extends WebGLKernelArray{constructor(value2,settings){super(value2,settings);this.checkSize(value2[0].width,value2[0].height);this.dimensions=[value2[0].width,value2[0].height,value2.length];this.textureSize=[value2[0].width,value2[0].height]}defineTexture(){const{context:gl}=this;gl.activeTexture(this.contextHandle);gl.bindTexture(gl.TEXTURE_2D_ARRAY,this.texture);gl.texParameteri(gl.TEXTURE_2D_ARRAY,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D_ARRAY,gl.TEXTURE_MIN_FILTER,gl.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}; -`}getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2DArray ${this.id}`,`${variablePrecision} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${variablePrecision} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(images){const{context:gl}=this;gl.activeTexture(this.contextHandle);gl.bindTexture(gl.TEXTURE_2D_ARRAY,this.texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);gl.texImage3D(gl.TEXTURE_2D_ARRAY,0,gl.RGBA,images[0].width,images[0].height,images.length,0,gl.RGBA,gl.UNSIGNED_BYTE,null);for(let i=0;iKernel2.isSupported)}static get isKernelMapSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.kernelMap)}static get isOffscreenCanvasSupported(){return typeof Worker!=="undefined"&&typeof OffscreenCanvas!=="undefined"||typeof importScripts!=="undefined"}static get isWebGLSupported(){return WebGLKernel.isSupported}static get isWebGL2Supported(){return WebGL2Kernel.isSupported}static get isHeadlessGLSupported(){return HeadlessGLKernel.isSupported}static get isCanvasSupported(){return typeof HTMLCanvasElement!=="undefined"}static get isGPUHTMLImageArraySupported(){return WebGL2Kernel.isSupported}static get isSinglePrecisionSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.isFloatRead&&Kernel2.features.isTextureFloat)}constructor(settings){settings=settings||{};this.canvas=settings.canvas||null;this.context=settings.context||null;this.mode=settings.mode;this.Kernel=null;this.kernels=[];this.functions=[];this.nativeFunctions=[];this.injectedNative=null;if(this.mode==="dev")return;this.chooseKernel();if(settings.functions){for(let i=0;isettings.argumentTypes[argumentName])}function onRequestFallback(args){console.warn("Falling back to CPU");const fallbackKernel=new CPUKernel(source,{argumentTypes:kernelRun.argumentTypes,constantTypes:kernelRun.constantTypes,graphical:kernelRun.graphical,loopMaxIterations:kernelRun.loopMaxIterations,constants:kernelRun.constants,dynamicOutput:kernelRun.dynamicOutput,dynamicArgument:kernelRun.dynamicArguments,output:kernelRun.output,precision:kernelRun.precision,pipeline:kernelRun.pipeline,immutable:kernelRun.immutable,optimizeFloatMemory:kernelRun.optimizeFloatMemory,fixIntegerDivisionAccuracy:kernelRun.fixIntegerDivisionAccuracy,functions:kernelRun.functions,nativeFunctions:kernelRun.nativeFunctions,injectedNative:kernelRun.injectedNative,subKernels:kernelRun.subKernels,strictIntegers:kernelRun.strictIntegers,debug:kernelRun.debug});fallbackKernel.build.apply(fallbackKernel,args);const result=fallbackKernel.run.apply(fallbackKernel,args);kernelRun.replaceKernel(fallbackKernel);return result}function onRequestSwitchKernel(reasons,args,_kernel){if(_kernel.debug){console.warn("Switching kernels")}let newOutput=null;if(_kernel.signature&&!switchableKernels[_kernel.signature]){switchableKernels[_kernel.signature]=_kernel}if(_kernel.dynamicOutput){for(let i=reasons.length-1;i>=0;i--){const reason=reasons[i];if(reason.type==="outputPrecisionMismatch"){newOutput=reason.needed}}}const Constructor=_kernel.constructor;const argumentTypes=Constructor.getArgumentTypes(_kernel,args);const signature=Constructor.getSignature(_kernel,argumentTypes);const existingKernel=switchableKernels[signature];if(existingKernel){existingKernel.onActivate(_kernel);return existingKernel}const newKernel=switchableKernels[signature]=new Constructor(source,{argumentTypes,constantTypes:_kernel.constantTypes,graphical:_kernel.graphical,loopMaxIterations:_kernel.loopMaxIterations,constants:_kernel.constants,dynamicOutput:_kernel.dynamicOutput,dynamicArgument:_kernel.dynamicArguments,context:_kernel.context,canvas:_kernel.canvas,output:newOutput||_kernel.output,precision:_kernel.precision,pipeline:_kernel.pipeline,immutable:_kernel.immutable,optimizeFloatMemory:_kernel.optimizeFloatMemory,fixIntegerDivisionAccuracy:_kernel.fixIntegerDivisionAccuracy,functions:_kernel.functions,nativeFunctions:_kernel.nativeFunctions,injectedNative:_kernel.injectedNative,subKernels:_kernel.subKernels,strictIntegers:_kernel.strictIntegers,debug:_kernel.debug,gpu:_kernel.gpu,validate,returnType:_kernel.returnType,tactic:_kernel.tactic,onRequestFallback,onRequestSwitchKernel,texture:_kernel.texture,mappedTextures:_kernel.mappedTextures,drawBuffersMap:_kernel.drawBuffersMap});newKernel.build.apply(newKernel,args);kernelRun.replaceKernel(newKernel);kernels.push(newKernel);return newKernel}const mergedSettings=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate,onRequestFallback,onRequestSwitchKernel},settingsCopy);const kernel=new this.Kernel(source,mergedSettings);const kernelRun=kernelRunShortcut(kernel);if(!this.canvas){this.canvas=kernel.canvas}if(!this.context){this.context=kernel.context}kernels.push(kernel);return kernelRun}createKernelMap(){let fn;let settings;const argument2Type=typeof arguments[arguments.length-2];if(argument2Type==="function"||argument2Type==="string"){fn=arguments[arguments.length-2];settings=arguments[arguments.length-1]}else{fn=arguments[arguments.length-1]}if(this.mode!=="dev"){if(!this.Kernel.isSupported||!this.Kernel.features.kernelMap){if(this.mode&&kernelTypes.indexOf(this.mode)<0){throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}}}const settingsCopy=upgradeDeprecatedCreateKernelSettings(settings);if(settings&&typeof settings.argumentTypes==="object"){settingsCopy.argumentTypes=Object.keys(settings.argumentTypes).map(argumentName=>settings.argumentTypes[argumentName])}if(Array.isArray(arguments[0])){settingsCopy.subKernels=[];const functions=arguments[0];for(let i=0;i0){throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.')}this.nativeFunctions.push(Object.assign({name:name2,source},settings));return this}injectNative(source){this.injectedNative=source;return this}destroy(){return new Promise((resolve,reject)=>{if(!this.kernels){resolve()}setTimeout(()=>{try{for(let i=0;i{try{accept(run.apply(this,arguments))}catch(e){reject(e)}})};shortcut.replaceKernel=function(replacementKernel){kernel=replacementKernel;bindKernelToShortcut(kernel,shortcut)};bindKernelToShortcut(kernel,shortcut);return shortcut}function bindKernelToShortcut(kernel,shortcut){if(shortcut.kernel){shortcut.kernel=kernel;return}const properties=utils.allPropertiesOf(kernel);for(let i=0;ishortcut.kernel[property]);shortcut.__defineSetter__(property,value2=>{shortcut.kernel[property]=value2})}}shortcut.kernel=kernel}module3.exports={kernelRunShortcut}},{"./utils":114}],112:[function(require2,module3,exports3){const source=`// https://www.shadertoy.com/view/4t2SDh - //note: uniformly distributed, normalized rand, [0,1] - highp float randomSeedShift = 1.0; - highp float slide = 1.0; - uniform highp float randomSeed1; - uniform highp float randomSeed2; - - highp float nrand(highp vec2 n) { - highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453); - randomSeedShift = result; - if (randomSeedShift > 0.5) { - slide += 0.00009; - } else { - slide += 0.0009; - } - return result; - }`;const name2="math-random-uniformly-distributed";const functionMatch=`Math.random()`;const functionReplace=`nrand(vTexCoord)`;const functionReturnType="Number";const onBeforeRun=kernel=>{kernel.setUniform1f("randomSeed1",Math.random());kernel.setUniform1f("randomSeed2",Math.random())};const plugin={name:name2,onBeforeRun,functionMatch,functionReplace,functionReturnType,source};module3.exports=plugin},{}],113:[function(require2,module3,exports3){class Texture{constructor(settings){const{texture,size,dimensions,output,context,type="NumberTexture",kernel,internalFormat,textureFormat}=settings;if(!output)throw new Error('settings property "output" required.');if(!context)throw new Error('settings property "context" required.');if(!texture)throw new Error('settings property "texture" required.');if(!kernel)throw new Error('settings property "kernel" required.');this.texture=texture;if(texture._refs){texture._refs++}else{texture._refs=1}this.size=size;this.dimensions=dimensions;this.output=output;this.context=context;this.kernel=kernel;this.type=type;this._deleted=false;this.internalFormat=internalFormat;this.textureFormat=textureFormat}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}module3.exports={Texture}},{}],114:[function(require2,module3,exports3){const acorn=require2("acorn");const{Input}=require2("./input");const{Texture}=require2("./texture");const FUNCTION_NAME=/function ([^(]*)/;const STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;const ARGUMENT_NAMES=/([^\s,]+)/g;const utils={systemEndianness(){return _systemEndianness},getSystemEndianness(){const b=new ArrayBuffer(4);const a=new Uint32Array(b);const c=new Uint8Array(b);a[0]=3735928559;if(c[0]===239)return"LE";if(c[0]===222)return"BE";throw new Error("unknown endianness")},isFunction(funcObj){return typeof funcObj==="function"},isFunctionString(fn){if(typeof fn==="string"){return fn.slice(0,"function".length).toLowerCase()==="function"}return false},getFunctionNameFromString(funcStr){const result=FUNCTION_NAME.exec(funcStr);if(!result||result.length===0)return null;return result[1].trim()},getFunctionBodyFromString(funcStr){return funcStr.substring(funcStr.indexOf("{")+1,funcStr.lastIndexOf("}"))},getArgumentNamesFromString(fn){const fnStr=fn.replace(STRIP_COMMENTS,"");let result=fnStr.slice(fnStr.indexOf("(")+1,fnStr.indexOf(")")).match(ARGUMENT_NAMES);if(result===null){result=[]}return result},clone(obj){if(obj===null||typeof obj!=="object"||obj.hasOwnProperty("isActiveClone"))return obj;const temp=obj.constructor();for(let key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){obj.isActiveClone=null;temp[key]=utils.clone(obj[key]);delete obj.isActiveClone}}return temp},isArray(array){return!isNaN(array.length)},getVariableType(value2,strictIntegers){if(utils.isArray(value2)){if(value2.length>0&&value2[0].nodeName==="IMG"){return"HTMLImageArray"}return"Array"}switch(value2.constructor){case Boolean:return"Boolean";case Number:if(strictIntegers&&Number.isInteger(value2)){return"Integer"}return"Float";case Texture:return value2.type;case Input:return"Input"}switch(value2.nodeName){case"IMG":return"HTMLImage";case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}if(value2.hasOwnProperty("type")){return value2.type}return"Unknown"},getKernelTextureSize(settings,dimensions){let[w,h,d]=dimensions;let texelCount=(w||1)*(h||1)*(d||1);if(settings.optimizeFloatMemory&&settings.precision==="single"){w=texelCount=Math.ceil(texelCount/4)}if(h>1&&w*h===texelCount){return new Int32Array([w,h])}return utils.closestSquareDimensions(texelCount)},closestSquareDimensions(length){const sqrt=Math.sqrt(length);let high=Math.ceil(sqrt);let low=Math.floor(sqrt);while(high*low0){return lines.join(";\n")+";\n"}else{return"\n"}},warnDeprecated(type,oldName,newName){if(newName){console.warn(`You are using a deprecated ${type} "${oldName}". It has been replaced with "${newName}". Fixing, but please upgrade as it will soon be removed.`)}else{console.warn(`You are using a deprecated ${type} "${oldName}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)}},flipPixels:(pixels,width,height)=>{const halfHeight=height/2|0;const bytesPerRow=width*4;const temp=new Uint8ClampedArray(width*4);const result=pixels.slice(0);for(let y=0;y{return array.subarray(0,width)},erect2DPackedFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{return array.subarray(0,width)},erectMemoryOptimized2DFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{const xResults=new Float32Array(width);let i=0;for(let x2=0;x2{const yResults=new Array(height);let i=0;for(let y=0;y{const zResults=new Array(depth);let i=0;for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const yResults=new Array(height);const XResultsMax=width*4;for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(array);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const{findDependency,thisLookup,doNotDefine}=settings;let flattened=settings.flattened;if(!flattened){flattened=settings.flattened={}}const ast=acorn.parse(source);const functionDependencies=[];let indent=0;function flatten2(ast2){if(Array.isArray(ast2)){const results=[];for(let i=0;ir!==null);if(declarations.length<1){return""}else{return`${ast2.kind} ${declarations.join(",")}`}case"VariableDeclarator":if(ast2.init.object&&ast2.init.object.type==="ThisExpression"){const lookup=thisLookup(ast2.init.property.name,true);if(lookup){return`${ast2.id.name} = ${flatten2(ast2.init)}`}else{return null}}else{return`${ast2.id.name} = ${flatten2(ast2.init)}`}case"CallExpression":{if(ast2.callee.property.name==="subarray"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.name==="gl"||ast2.callee.object.name==="context"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.type==="ThisExpression"){functionDependencies.push(findDependency("this",ast2.callee.property.name));return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else if(ast2.callee.object.name){const foundSource=findDependency(ast2.callee.object.name,ast2.callee.property.name);if(foundSource===null){return`${ast2.callee.object.name}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{functionDependencies.push(foundSource);return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}}else if(ast2.callee.object.type==="MemberExpression"){return`${flatten2(ast2.callee.object)}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{throw new Error("unknown ast.callee")}}case"ReturnStatement":return`return ${flatten2(ast2.argument)}`;case"BinaryExpression":return`(${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)})`;case"UnaryExpression":if(ast2.prefix){return`${ast2.operator} ${flatten2(ast2.argument)}`}else{return`${flatten2(ast2.argument)} ${ast2.operator}`}case"ExpressionStatement":return`${flatten2(ast2.expression)}`;case"SequenceExpression":return`(${flatten2(ast2.expressions)})`;case"ArrowFunctionExpression":return`(${ast2.params.map(flatten2).join(", ")}) => ${flatten2(ast2.body)}`;case"Literal":return ast2.raw;case"Identifier":return ast2.name;case"MemberExpression":if(ast2.object.type==="ThisExpression"){return thisLookup(ast2.property.name)}if(ast2.computed){return`${flatten2(ast2.object)}[${flatten2(ast2.property)}]`}return flatten2(ast2.object)+"."+flatten2(ast2.property);case"ThisExpression":return"this";case"NewExpression":return`new ${flatten2(ast2.callee)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`;case"ForStatement":return`for (${flatten2(ast2.init)};${flatten2(ast2.test)};${flatten2(ast2.update)}) ${flatten2(ast2.body)}`;case"AssignmentExpression":return`${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)}`;case"UpdateExpression":return`${flatten2(ast2.argument)}${ast2.operator}`;case"IfStatement":return`if (${flatten2(ast2.test)}) ${flatten2(ast2.consequent)}`;case"ThrowStatement":return`throw ${flatten2(ast2.argument)}`;case"ObjectPattern":return ast2.properties.map(flatten2).join(", ");case"ArrayPattern":return ast2.elements.map(flatten2).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${flatten2(ast2.test)}?${flatten2(ast2.consequent)}:${flatten2(ast2.alternate)}`;case"Property":if(ast2.kind==="init"){return flatten2(ast2.key)}}throw new Error(`unhandled ast.type of ${ast2.type}`)}const result=flatten2(ast);if(functionDependencies.length>0){const flattenedFunctionDependencies=[];for(let i=0;i{if(ast.type!=="VariableDeclaration")throw new Error('Ast is not of type "VariableDeclaration"');const normalizedDeclarations=[];for(let declarationIndex=0;declarationIndex{const rKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.r*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const gKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.g*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const bKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.b*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const aKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.a*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const result=[rKernel(image),gKernel(image),bKernel(image),aKernel(image)];result.rKernel=rKernel;result.gKernel=gKernel;result.bKernel=bKernel;result.aKernel=aKernel;result.gpu=gpu;return result},splitRGBAToCanvases:(gpu,rgba,width,height)=>{const visualKernelR=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(pixel.r/255,0,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelR(rgba);const visualKernelG=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,pixel.g/255,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelG(rgba);const visualKernelB=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,0,pixel.b/255,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelB(rgba);const visualKernelA=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(255,255,255,pixel.a/255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelA(rgba);return[visualKernelR.canvas,visualKernelG.canvas,visualKernelB.canvas,visualKernelA.canvas]},getMinifySafeName:fn=>{try{const ast=acorn.parse(`const value = ${fn.toString()}`);const{init}=ast.body[0].declarations[0];return init.body.name||init.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(name2){if(dollarSign.test(name2)){name2=name2.replace(dollarSign,"S_S")}if(doubleUnderscore.test(name2)){name2=name2.replace(doubleUnderscore,"U_U")}else if(singleUnderscore.test(name2)){name2=name2.replace(singleUnderscore,"u_u")}return name2}};const dollarSign=/\$/;const doubleUnderscore=/__/;const singleUnderscore=/_/;const _systemEndianness=utils.getSystemEndianness();module3.exports={utils}},{"./input":110,"./texture":113,"acorn":1}]},{},[107])(107)})}});var import_gpu_browser_min=__toESM(require_gpu_browser_min());function add(a,b){return a+b}function sub(a,b){return a-b}function mul(a,b){return a*b}function div(a,b){return a/b}function cadd(a_real,a_imag,b_real,b_imag){return[a_real+b_real,a_imag+b_imag]}function csub(a_real,a_imag,b_real,b_imag){return[a_real-b_real,a_imag-b_imag]}function cmul(a_real,a_imag,b_real,b_imag){return[a_real*b_real-a_imag*b_imag,a_real*b_imag+a_imag*b_real]}function cexp(a_real,a_imag){const er=Math.exp(a_real);return[er*Math.cos(a_imag),er*Math.sin(a_imag)]}function mag(a,b){return Math.sqrt(a*a+b*b)}function conj(imag){return 0-imag}function lof(n){const sqrt_n=Math.sqrt(n);var factor=3;while(factor<=sqrt_n){if(n%factor===0)return factor;factor+=2}}function mean(arr,len){var mean2=0;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signal[j]*Math.cos(sharedi);imag=imag-signal[j]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function FFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=imag-signals[j+(len-1)*n]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function iDFT(fft,len,freq){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+fft[j]*Math.cos(sharedi);imag=fft[j]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function iFFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=signals[j+(len-1)*n]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function correlogramsKern(arrays,len){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=mean(arrays[k],len);var arr2mean=mean(arrays[k+1],len);var arr1Est=est(arrays[k],arr1mean,len);var arr2Est2=est(arrays[k+1],arr2mean,len);var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function correlogramsPCKern(arrays,len,means,estimators){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=means[k];var arr2mean=means[k+1];var arr1Est=estimators[k];var arr2Est2=estimators[k+1];var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function dftKern(signal,len,scalar){var result=DFT(signal,len,this.thread.x);return mag(result[0],result[1])*scalar}function idftKern(amplitudes,len,scalar){var result=iDFT(amplitudes,len,this.thread.x);return mag(result[0],result[1])*scalar}function fftKern(signal,len,scalar,sampleRate){var result=FFT(signal,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function ifftKern(amplitudes,len,scalar,sampleRate){var result=iFFT(amplitudes,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function listdft2DKern(signals,scalar){var len=this.output.x;var result=DFT(signals[this.thread.y],len,this.thread.x);return mag(result[0],result[1])*scalar}function listdft1DKern(signals,len,scalar){var result=[0,0];if(this.thread.x<=len){result=DFT(signals,len,this.thread.x)}else{var n=Math.floor(this.thread.x/len);result=DFTlist(signals,len,this.thread.x-n*len,n)}return mag(result[0],result[1])*scalar}function listfft1DKern(signals,len,scalar,sps){var result=[0,0];if(this.thread.x<=len){result=FFT(signals,len,this.thread.x,sps)}else{var n=Math.floor(this.thread.x/len);result=FFTlist(signals,len,this.thread.x-n*len,n,sps)}return mag(result[0],result[1])*scalar}function dft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=DFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function fft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=FFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function idft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iDFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function ifft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iFFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function listdft1D_windowedKern(signals,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];if(this.thread.x=width){i++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+i+kernelRadius;const weights=kernel[kernelOffset];const pixel=img[this.thread.y+i][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}i++}this.color(r,g,b)}function multiImgConv2DKern(img,width,height,kernels,kernelLengths,nKernels){let r=0,g=0,b=0;for(var i=0;i=width){k++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+k+kernelRadius;const weights=kernels[i][kernelOffset];const pixel=img[this.thread.y+k][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}k++}}this.color(r,g,b)}function transpose2DKern(mat2){return mat2[this.thread.y][this.thread.x]}var createGpuKernels={correlogramsKern,correlogramsPCKern,dftKern,idftKern,fftKern,ifftKern,dft_windowedKern,idft_windowedKern,fft_windowedKern,ifft_windowedKern,listdft2DKern,listdft1DKern,listfft1DKern,listfft1D_windowedKern,listdft1D_windowedKern,listidft1D_windowedKern,listifft1D_windowedKern,bulkArrayMulKern,multiImgConv2DKern,ImgConv2DKern,transpose2DKern};var addGpuFunctions=[add,sub,mul,div,cadd,csub,cmul,cexp,mag,conj,lof,mean,est,mse,rms,xcor,softmax,DFT,DFTlist,iDFT,iDFTlist,FFT,iFFT,iFFTlist];function makeKrnl(gpu,f,opts={setDynamicOutput:true,setDynamicArguments:true,setPipeline:true,setImmutable:true,setGraphical:false}){const k=gpu.createKernel(f);if(opts.setDynamicOutput)k.setDynamicOutput(true);if(opts.output)k.setOutput(opts.output);if(opts.setDynamicArguments)k.setDynamicArguments(true);if(opts.setPipeline)k.setPipeline(true);if(opts.setImmutable)k.setImmutable(true);if(opts.setGraphical)k.setGraphical(true);return k}function makeCanvasKrnl(gpu,f,opts={output:[300,300],setDynamicArguments:true,setDynamicOutput:true,setPipeline:false,setImmutable:true,setGraphical:true},divId){const k=makeKrnl(gpu,f,opts);const canvas=k.canvas;if(typeof divId==="string")document.getElementById(toAppend).appendChild(canvas);else if(divId)toAppend.appendChild(canvas);else document.body.appendChild(canvas);return k}var gpuUtils=class{constructor(gpu=new GPUjs){this.gpu=gpu;this.kernels=new Map;this.kernel;this.PI=3.141592653589793;this.SQRT1_2=.7071067811865476;this.addFunctions();this.imgkernels={edgeDetection:[-1,-1,-1,-1,8,-1,-1,-1,-1],boxBlur:[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],sobelLeft:[1,0,-1,2,0,-2,1,0,-1],sobelRight:[-1,0,1,-2,0,2,-1,0,1],sobelTop:[1,2,1,0,0,0,-1,-2,-1],sobelBottom:[-1,2,1,0,0,0,1,2,1],identity:[0,0,0,0,1,0,0,0,0],gaussian3x3:[1,2,1,2,4,2,1,2,1],guassian7x7:[0,0,0,5,0,0,0,0,5,18,32,18,5,0,0,18,64,100,64,18,0,5,32,100,100,100,32,5,0,18,64,100,64,18,0,0,5,18,32,18,5,0,0,0,0,5,0,0,0],emboss:[-2,-1,0,-1,1,1,0,1,2],sharpen:[0,-1,0,-1,5,-1,0,-1,0]}}addFunction(func=function f(){}){this.gpu.addFunction(func)}addKernel(name2="",krnl=function foo(){},opts){let found=this.kernels.get(name2);if(!found){this.kernels.set(name2,makeKrnl(this.gpu,krnl,opts));return true}else{console.error("Kernel already exists");return false}}addCanvasKernel(name2,f,opts,divId){let found=this.kernels.get(name2);if(!found){let krnl=makeCanvasKrnl(this.gpu,f,opts,divId);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}combineKernels(name2,fs=[],ckrnl=function foo(){}){let found=this.kernels.get(name2);if(!found){fs.forEach((f,i)=>{if(typeof f==="string"){let found2=this.kernels.get(f);if(found2)fs[i]=found2;else return false}else if(typeof f==="function"){if(this.kernels.get(f.name)){}else{this.addKernel(f.name,f)}}});let krnl=this.gpu.combineKernels(...fs,ckrnl);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}callKernel(name2="",args=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}result=krnl(...args);return result}callCanvasKernel(name2="",args=[],outputDims=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}else{if(outputDims.length===2)krnl.setOutput(outputDims);result=krnl(...args);return result}}hasKernel(name2=""){let found=this.kernels.get(name2);if(!found){return false}else return true}addFunctions(){addGpuFunctions.forEach(f=>this.gpu.addFunction(f));this.correlograms=makeKrnl(this.gpu,createGpuKernels.correlogramsKern);this.correlogramsPC=makeKrnl(this.gpu,createGpuKernels.correlogramsPCKern);this.dft=makeKrnl(this.gpu,createGpuKernels.dftKern);this.idft=makeKrnl(this.gpu,createGpuKernels.idftKern);this.dft_windowed=makeKrnl(this.gpu,createGpuKernels.dft_windowedKern);this.idft_windowed=makeKrnl(this.gpu,createGpuKernels.idft_windowedKern);this.fft=makeKrnl(this.gpu,createGpuKernels.fftKern);this.ifft=makeKrnl(this.gpu,createGpuKernels.ifftKern);this.fft_windowed=makeKrnl(this.gpu,createGpuKernels.fft_windowedKern);this.ifft_windowed=makeKrnl(this.gpu,createGpuKernels.ifft_windowedKern);this.listdft2D=makeKrnl(this.gpu,createGpuKernels.listdft2DKern);this.listdft1D=makeKrnl(this.gpu,createGpuKernels.listdft1DKern);this.listdft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listdft1D_windowedKern);this.listfft1D=makeKrnl(this.gpu,createGpuKernels.listfft1DKern);this.listfft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listfft1D_windowedKern);this.listidft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listidft1D_windowedKern);this.listifft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listifft1D_windowedKern);this.bulkArrayMul=makeKrnl(this.gpu,createGpuKernels.bulkArrayMulKern);let kernels=[{name:"correlograms",krnl:this.correlograms},{name:"correlogramsPC",krnl:this.correlogramsPC},{name:"dft",krnl:this.dft},{name:"idft",krnl:this.idft},{name:"dft_windowed",krnl:this.idft_windowed},{name:"fft",krnl:this.fft},{name:"ifft",krnl:this.ifft},{name:"fft_windowed",krnl:this.fft_windowed},{name:"ifft_windowed",krnl:this.ifft_windowed},{name:"listdft2D",krnl:this.listdft2D},{name:"listdft1D",krnl:this.listdft1D},{name:"listdft1D_windowed",krnl:this.listdft1D_windowed},{name:"listfft1D",krnl:this.listfft1D},{name:"listfft1D_windowed",krnl:this.listfft1D_windowed},{name:"listidft1D_windowed",krnl:this.listidft1D_windowed},{name:"listifft1D_windowed",krnl:this.listifft1D_windowed},{name:"bulkArrayMul",krnl:this.bulkArrayMul}];kernels.forEach(k=>{this.kernels.set(k.name,k)});const signalBandpass=(signal,sampleRate,freqStart,freqEnd,scalar)=>{var dft2=this.fft_windowed(signal,sampleRate,freqStart,freqEnd,scalar,0);var filtered_signal=this.ifft_windowed(dft2,sampleRate,freqStart,freqEnd,scalar);return filtered_signal};const signalBandpassMulti=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var dfts=this.listdft1D_windowed(signals,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var filtered_signals=this.listifft1D_windowed(dfts,sampleRate,freqStart,freqEnd,scalar);return filtered_signals};this.gpuCoherence=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var xcors=this.correlograms(signals);var dfts=this.listfft1D_windowed(xcors,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var products=this.bulkArrayMul(dfts,sampleRate,5,1);return products}}gpuXCors(arrays,precompute=false,texOut=false){var outputTex;if(precompute===true){var means=[];var ests=[];arrays.forEach((arr,i2)=>{means.push(arr.reduce((prev,curr)=>curr+=prev)/arr.length);ests.push(Math.sqrt(means[i2].reduce((sum,item)=>sum+=Math.pow(item-mean1,2))))});var meansbuf=[];var estsbuf=[];var buffer=[];for(var i=0;i{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D.setOutput([signalBufferProcessed.length]);this.listdft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D(signalBufferProcessed,nSamplesPerChannel,scalar);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D_windowed.setOutput([signalBufferProcessed.length]);this.listdft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}gpuFFT(signalBuffer,nSeconds,scalar=1,sampleRate,texOut=false){var nSamples=signalBuffer.length;var sampleRate=nSamples/nSeconds;this.fft.setOutput([signalBuffer.length]);this.fft.setLoopMaxIterations(nSamples);var outputTex=this.fft(signalBuffer,nSamples,scalar,sampleRate);var output=null;if(texOut===false){var freqDist=this.makeFrequencyDistribution(nSamples,sampleRate);var signalBufferProcessed=outputTex.toArray();outputTex.delete();return[freqDist,this.orderMagnitudes(signalBufferProcessed)]}else{var tex=outputTex;outputTex.delete();return tex}}MultiChannelFFT(signalBuffer,nSeconds,scalar=1,texOut=false){var signalBufferProcessed=[];signalBuffer.forEach(row=>{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D.setOutput([signalBufferProcessed.length]);this.listfft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D(signalBufferProcessed,nSamplesPerChannel,scalar,sampleRate);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D_windowed.setOutput([signalBufferProcessed.length]);this.listfft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}orderMagnitudes(unorderedMags){return[...unorderedMags.slice(Math.ceil(unorderedMags.length*.5),unorderedMags.length),...unorderedMags.slice(0,Math.ceil(unorderedMags.length*.5))]}makeFrequencyDistribution(FFTlength,sampleRate){var N=FFTlength;var df=sampleRate/N;var freqDist=[];for(var i=-N/2;i1){magList.forEach((row,k)=>{summedMags.push([]);var _max=1/Math.max(...row);for(var i2=0;i2{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean2=void 0)=>{let avg=mean2;if(!mean2)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean2=this.mean(arr);let std=this.std(arr,mean2);let z=new Array(arr.length);for(let i=0;ia+(b-mean2)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean2=this.mean(arr);let std=this.std(arr,mean2);return populationMean?std/populationMean:std/mean2};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y)=>acc+Math.pow(y-meanY,2),0);const ssResidual=observed.reduce((acc,y,i)=>acc+Math.pow(y-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x2)=>sum+x2,0);const sumY=yCoords.reduce((sum,y)=>sum+y,0);const sumXY=xCoords.reduce((sum,x2,i)=>sum+x2*yCoords[i],0);const sumX2=xCoords.reduce((sum,x2)=>sum+x2*x2,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{return vec.map((v,i)=>v-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v,i)=>v/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v,i)=>v+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v,i)=>v-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v,i)=>v/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x2,y,z)=>{var r=Math.sqrt(x2*x2+y*y+z*z);var theta=Math.atan2(y,x2);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y=x2;return y},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x2=Math.cos(t);return x2},yFunc=t=>{let y=Math.sin(t);return y},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u,v)=>u,yFunc=(u,v)=>v,zFunc=(u,v)=>u+v,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u=rangeU[0];u{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value2,index)=>{const row=Array(values.length).fill(0);row[index]=value2;return row})};static householderMatrix=v=>{const size=v.length;const vvT=v.map(rowVal=>v.map(colVal=>rowVal*colVal));const vTv=this.normalize(v)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A,B)=>{return A.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean2=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value2=>(value2-min)/(max-min))};static garroteThreshold=(data,value2)=>{return data.map(x2=>{if(Math.abs(x2)<=value2){return 0}else{return x2-value2*value2/x2}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean12=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v,i)=>(v-mean12)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x2,x2),this.cov1d(x2,y),this.cov1d(x2,z)],[this.cov1d(y,x2),this.cov1d(y,y),this.cov1d(y,z)],[this.cov1d(z,x2),this.cov1d(z,y),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean2=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean2*mean2-det);let eig1=mean2+sqrt;let eig2=mean2-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean2=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v=>v-mean2)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N=signalA.length;const M=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean12=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(delaybuf[delay+i]-mean12));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x2=arr.filter((element,index)=>{return index%factor===0});return x2};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y=>y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x2)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A,numIter=100)=>{let b=Array(A.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A[0].length>A.length){A=this.transpose(A)}const m=A.length;const n=A[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x2):this.normalize(x2);const u=this.vecsub(x2,e);const normU=this.normalize(u);const v=u.map(val=>val/normU);const Qk=this.householderMatrix(v);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean2=this.mean(smoothed);let std=this.std(smoothed,mean2);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean2)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean2)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}}}return value2}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value2==="function"?value2.toString():value2,path.join("."))}}}return typeof value2==="function"?value2.toString():value2}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx++}}}}}function checkValues(key,value2){let val;if(value2!=null){if(typeof value2==="object"){let c=value2.constructor.name;if(key&&c==="Object"){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}if(c==="Array"){if(value2.length>20){val=value2.slice(value2.length-20)}else val=value2}else if(c.includes("Set")){val=Array.from(value2)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value2){if(value2[prop]==null){obj[prop]=value2[prop]}else if(Array.isArray(value2[prop])){if(value2[prop].length>20)obj[prop]=value2[prop].slice(value2[prop].length-20);else obj[prop]=value2[prop]}else if(value2[prop].constructor.name==="Object"){obj[prop]={};for(const p in value2[prop]){if(Array.isArray(value2[prop][p])){if(value2[prop][p].length>20)obj[prop][p]=value2[prop][p].slice(value2[prop][p].length-20);else obj[prop][p]=value2[prop][p]}else{if(value2[prop][p]!=null){let con=value2[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value2[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value2[prop][p]}}else{obj[prop][p]=value2[prop][p]}}}}else{let con=value2[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value2[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value2[prop]}}}val=obj}else{val=value2}}else{val=value2}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var GPUService=class extends Service{gpu=new gpuUtils;constructor(options){super(options);this.load(this)}addFunc=fn=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addFunction(fn)};addKernel=(name2,fn,options)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addKernel(name2,fn,options)};combineKernels=(name2,fs,ckrnl)=>{for(let i=0;i{this.gpu.callKernel(name2,args)};dft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.gpuDFT(signalBuffer,nSeconds,scalar)};multidft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT(signalBuffer,nSeconds,scalar)};multidftbandpass=(buffered,nSeconds,freqStart,freqEnd,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT_Bandpass(buffered,nSeconds,freqStart,freqEnd,scalar)};coherence=(buffered,nSeconds,freqStart,freqEnd)=>{const correlograms=Math2.correlograms(buffered);const buffer=[...buffered,...correlograms];var dfts;var scalar=1;dfts=this.gpu.MultiChannelDFT_Bandpass(buffer,nSeconds,freqStart,freqEnd,scalar);const cordfts=dfts[1].splice(buffered.length,buffer.length-buffered.length);const coherenceResults=[];const nChannels=buffered.length;var k=0;var l=0;cordfts.forEach((row,i)=>{if(l+k===nChannels){var temp=cordfts.splice(i,1);k++;cordfts.splice(k,0,...temp);l=0}l++});var autoFFTproducts=[];k=0;l=1;cordfts.forEach((dft2,i)=>{var newdft=new Array(dft2.length).fill(0);if(i{newdft[j]=amp});autoFFTproducts.push(newdft)}else{dft2.forEach((amp,j)=>{let denom=autoFFTproducts[k][j]*autoFFTproducts[k+l][j];if(denom!==0)newdft[j]=amp*amp/denom;else newdft[j]=0;if(newdft[j]>1){newdft[j]=1}});l++;if(l+k===nChannels){k++;l=1}coherenceResults.push(newdft)}});return[dfts[0],dfts[1],coherenceResults]}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var dft={sps:250,nSec:1,freqStart:0,freqEnd:125,watch:["0","1","2","3"],blocking:false,__operator:function(arraybuffer){let results=globalThis.gpu.multidftbandpass(arraybuffer,this.nSec,this.freqStart,this.freqEnd,1);let dft2={};this.watch.forEach((tag,i)=>{dft2[tag]=results[1][i]});return{frequencies:results[0],dft:dft2}}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var coherence={sps:250,nSec:1,freqStart:0,freqEnd:125,tags:["0","1","2","3"],coherenceTags:[],__onconnected:function(node){node.tags.forEach((tag,i)=>{if(i!==node.tags.length-1){for(let j=i+1;j{dft2[tag]=results[1][i]});let coherence2={};this.coherenceTags.forEach((tag,i)=>{coherence2[tag]=results[2][i]});return{timestamp:ts,frequencies:results[0],dft:dft2,coherence:coherence2}}};var gpualgorithms={dft,coherence};export{GPUService,gpualgorithms}; -/*! Bundled license information: - -gpujsutils/dist/index.esm.js: - (** - * gpu.js - * http://gpu.rocks/ - * - * GPU Accelerated JavaScript - * - * @version 2.11.0 - * @date Tue Jan 05 2021 15:55:59 GMT-0500 (Eastern Standard Time) - * - * @license MIT - * The MIT License - * - * Copyright (c) 2021 gpu.js Team - *) -*/ diff --git a/src/extras/dist/index.gpu.services.js b/src/extras/dist/index.gpu.services.js deleted file mode 100644 index 90bf9273..00000000 --- a/src/extras/dist/index.gpu.services.js +++ /dev/null @@ -1,1300 +0,0 @@ -(()=>{var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value2)=>{this.data[key]=value2;this.triggerEvent(key,value2)};triggerEvent=(key,value2)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value2)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub2=>{return this.unsubscribeEvent(statesubKey,sub2)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value2=>{refObject[refKey]=value2},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub2)=>{let triggers=this.triggers[key];if(triggers){if(sub2===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub2;let changed=value2=>{onchange(value2);this.unsubscribeEvent(key,sub2)};sub2=this.subscribeEvent(key,changed);return sub2};getEvent=(key,sub2)=>{if(typeof sub2!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub2)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value2,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value2,receiver)}return Reflect.set(target,prop,value2,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub2=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub2);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub2;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub2};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub2;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub2}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub2;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub2}};__unsubscribe=(sub2,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub2)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub2)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub2=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub2);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value2=>{obj[k]=value2},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub2=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub2)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub2;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub2)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub2)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub2;if(nd instanceof GraphNode){const doSub=()=>{sub2=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)nd.__unsubscribe(sub2,key,subInput);sub2=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub2===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub2=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub2=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput);sub2=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub2=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub2};unsubscribe=(node,sub2,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub2,key,subInput)}else return this.get(node)?.__unsubscribe(sub2,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require2=(x2=>typeof __require!=="undefined"?__require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof __require!=="undefined"?__require:a)[b]}):x2)(function(x2){if(typeof __require!=="undefined")return __require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require22(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_gpu_browser_min=__commonJS({"src/gpu-browser.min.js"(exports,module){"use strict";(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}f()}})(function(){var define2,module2,exports2;return function(){function r(e,n,t){function o(i2,f){if(!n[i2]){if(!e[i2]){var c="function"==typeof __require2&&__require2;if(!f&&c)return c(i2,true);if(u)return u(i2,true);var a=new Error("Cannot find module '"+i2+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i2]={exports:{}};e[i2][0].call(p.exports,function(r2){var n2=e[i2][1][r2];return o(n2||r2)},p,p.exports,r,e,n,t)}return n[i2].exports}for(var u="function"==typeof __require2&&__require2,i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType2(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name2,prec){return new TokenType(name2,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name2,options){if(options===void 0)options={};options.keyword=name2;return keywords$1[name2]=new TokenType(name2,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position2(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation2(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start,end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser2(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse2(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports5);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports5){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports5,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports5,node.declaration.declarations)}else{this.checkExport(exports5,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports5);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value2=this.value;node=this.parseLiteral(value2.value);node.regex={pattern:value2.pattern,flags:value2.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value2){var node=this.startNode();node.value=value2;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref2){var isTagged=ref2.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref2){if(ref2===void 0)ref2={};var isTagged=ref2.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name2)>-1||scope.var.indexOf(name2)>-1;scope.lexical.push(name2);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name2]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name2)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name2)>-1}else{redeclared=scope$2.lexical.indexOf(name2)>-1||scope$2.var.indexOf(name2)>-1}scope$2.functions.push(name2)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name2)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name2)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name2)>-1){redeclared=true;break}scope$3.var.push(name2);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name2]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name2+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node2(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext2(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat){return true}if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr)){return!parent.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState2(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state2){var validFlags=state2.validFlags;var flags=state2.flags;for(var i=0;i-1){this.raise(state2.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state2){this.regexp_pattern(state2);if(!state2.switchN&&this.options.ecmaVersion>=9&&state2.groupNames.length>0){state2.switchN=true;this.regexp_pattern(state2)}};pp$8.regexp_pattern=function(state2){state2.pos=0;state2.lastIntValue=0;state2.lastStringValue="";state2.lastAssertionIsQuantifiable=false;state2.numCapturingParens=0;state2.maxBackReference=0;state2.groupNames.length=0;state2.backReferenceNames.length=0;this.regexp_disjunction(state2);if(state2.pos!==state2.source.length){if(state2.eat(41)){state2.raise("Unmatched ')'")}if(state2.eat(93)||state2.eat(125)){state2.raise("Lone quantifier brackets")}}if(state2.maxBackReference>state2.numCapturingParens){state2.raise("Invalid escape")}for(var i=0,list=state2.backReferenceNames;i=9){lookbehind=state2.eat(60)}if(state2.eat(61)||state2.eat(33)){this.regexp_disjunction(state2);if(!state2.eat(41)){state2.raise("Unterminated group")}state2.lastAssertionIsQuantifiable=!lookbehind;return true}}state2.pos=start;return false};pp$8.regexp_eatQuantifier=function(state2,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state2,noError)){state2.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state2,noError){return state2.eat(42)||state2.eat(43)||state2.eat(63)||this.regexp_eatBracedQuantifier(state2,noError)};pp$8.regexp_eatBracedQuantifier=function(state2,noError){var start=state2.pos;if(state2.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state2)){min=state2.lastIntValue;if(state2.eat(44)&&this.regexp_eatDecimalDigits(state2)){max=state2.lastIntValue}if(state2.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state2)}else if(state2.current()===63){state2.raise("Invalid group")}this.regexp_disjunction(state2);if(state2.eat(41)){state2.numCapturingParens+=1;return true}state2.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state2){return state2.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state2)||this.regexp_eatCharacterClass(state2)||this.regexp_eatUncapturingGroup(state2)||this.regexp_eatCapturingGroup(state2)||this.regexp_eatInvalidBracedQuantifier(state2)||this.regexp_eatExtendedPatternCharacter(state2)};pp$8.regexp_eatInvalidBracedQuantifier=function(state2){if(this.regexp_eatBracedQuantifier(state2,true)){state2.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state2){var ch=state2.current();if(isSyntaxCharacter(ch)){state2.lastIntValue=ch;state2.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state2){var start=state2.pos;var ch=0;while((ch=state2.current())!==-1&&!isSyntaxCharacter(ch)){state2.advance()}return state2.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state2){var ch=state2.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state2.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state2){if(state2.eat(63)){if(this.regexp_eatGroupName(state2)){if(state2.groupNames.indexOf(state2.lastStringValue)!==-1){state2.raise("Duplicate capture group name")}state2.groupNames.push(state2.lastStringValue);return}state2.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state2){state2.lastStringValue="";if(state2.eat(60)){if(this.regexp_eatRegExpIdentifierName(state2)&&state2.eat(62)){return true}state2.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state2){state2.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierStart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierPart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state2){if(this.regexp_eatBackReference(state2)||this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)||state2.switchN&&this.regexp_eatKGroupName(state2)){return true}if(state2.switchU){if(state2.current()===99){state2.raise("Invalid unicode escape")}state2.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state2){var start=state2.pos;if(this.regexp_eatDecimalEscape(state2)){var n=state2.lastIntValue;if(state2.switchU){if(n>state2.maxBackReference){state2.maxBackReference=n}return true}if(n<=state2.numCapturingParens){return true}state2.pos=start}return false};pp$8.regexp_eatKGroupName=function(state2){if(state2.eat(107)){if(this.regexp_eatGroupName(state2)){state2.backReferenceNames.push(state2.lastStringValue);return true}state2.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state2){return this.regexp_eatControlEscape(state2)||this.regexp_eatCControlLetter(state2)||this.regexp_eatZero(state2)||this.regexp_eatHexEscapeSequence(state2)||this.regexp_eatRegExpUnicodeEscapeSequence(state2)||!state2.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state2)||this.regexp_eatIdentityEscape(state2)};pp$8.regexp_eatCControlLetter=function(state2){var start=state2.pos;if(state2.eat(99)){if(this.regexp_eatControlLetter(state2)){return true}state2.pos=start}return false};pp$8.regexp_eatZero=function(state2){if(state2.current()===48&&!isDecimalDigit(state2.lookahead())){state2.lastIntValue=0;state2.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state2){var ch=state2.current();if(ch===116){state2.lastIntValue=9;state2.advance();return true}if(ch===110){state2.lastIntValue=10;state2.advance();return true}if(ch===118){state2.lastIntValue=11;state2.advance();return true}if(ch===102){state2.lastIntValue=12;state2.advance();return true}if(ch===114){state2.lastIntValue=13;state2.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state2){var ch=state2.current();if(isControlLetter(ch)){state2.lastIntValue=ch%32;state2.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(117)){if(this.regexp_eatFixedHexDigits(state2,4)){var lead=state2.lastIntValue;if(state2.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state2.pos;if(state2.eat(92)&&state2.eat(117)&&this.regexp_eatFixedHexDigits(state2,4)){var trail=state2.lastIntValue;if(trail>=56320&&trail<=57343){state2.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state2.pos=leadSurrogateEnd;state2.lastIntValue=lead}return true}if(state2.switchU&&state2.eat(123)&&this.regexp_eatHexDigits(state2)&&state2.eat(125)&&isValidUnicode(state2.lastIntValue)){return true}if(state2.switchU){state2.raise("Invalid unicode escape")}state2.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state2){if(state2.switchU){if(this.regexp_eatSyntaxCharacter(state2)){return true}if(state2.eat(47)){state2.lastIntValue=47;return true}return false}var ch=state2.current();if(ch!==99&&(!state2.switchN||ch!==107)){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state2){state2.lastIntValue=0;var ch=state2.current();if(ch>=49&&ch<=57){do{state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}while((ch=state2.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state2){var ch=state2.current();if(isCharacterClassEscape(ch)){state2.lastIntValue=-1;state2.advance();return true}if(state2.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state2.lastIntValue=-1;state2.advance();if(state2.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state2)&&state2.eat(125)){return true}state2.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state2){var start=state2.pos;if(this.regexp_eatUnicodePropertyName(state2)&&state2.eat(61)){var name2=state2.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state2)){var value2=state2.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state2,name2,value2);return true}}state2.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state2)){var nameOrValue=state2.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state2,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state2,name2,value2){if(!has(state2.unicodeProperties.nonBinary,name2)){state2.raise("Invalid property name")}if(!state2.unicodeProperties.nonBinary[name2].test(value2)){state2.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state2,nameOrValue){if(!state2.unicodeProperties.binary.test(nameOrValue)){state2.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state2){return this.regexp_eatUnicodePropertyValue(state2)};pp$8.regexp_eatCharacterClass=function(state2){if(state2.eat(91)){state2.eat(94);this.regexp_classRanges(state2);if(state2.eat(93)){return true}state2.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state2){while(this.regexp_eatClassAtom(state2)){var left=state2.lastIntValue;if(state2.eat(45)&&this.regexp_eatClassAtom(state2)){var right=state2.lastIntValue;if(state2.switchU&&(left===-1||right===-1)){state2.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state2.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state2){var start=state2.pos;if(state2.eat(92)){if(this.regexp_eatClassEscape(state2)){return true}if(state2.switchU){var ch$1=state2.current();if(ch$1===99||isOctalDigit(ch$1)){state2.raise("Invalid class escape")}state2.raise("Invalid escape")}state2.pos=start}var ch=state2.current();if(ch!==93){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state2){var start=state2.pos;if(state2.eat(98)){state2.lastIntValue=8;return true}if(state2.switchU&&state2.eat(45)){state2.lastIntValue=45;return true}if(!state2.switchU&&state2.eat(99)){if(this.regexp_eatClassControlLetter(state2)){return true}state2.pos=start}return this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)};pp$8.regexp_eatClassControlLetter=function(state2){var ch=state2.current();if(isDecimalDigit(ch)||ch===95){state2.lastIntValue=ch%32;state2.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(120)){if(this.regexp_eatFixedHexDigits(state2,2)){return true}if(state2.switchU){state2.raise("Invalid escape")}state2.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isDecimalDigit(ch=state2.current())){state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}return state2.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isHexDigit(ch=state2.current())){state2.lastIntValue=16*state2.lastIntValue+hexToInt(ch);state2.advance()}return state2.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state2){if(this.regexp_eatOctalDigit(state2)){var n1=state2.lastIntValue;if(this.regexp_eatOctalDigit(state2)){var n2=state2.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state2)){state2.lastIntValue=n1*64+n2*8+state2.lastIntValue}else{state2.lastIntValue=n1*8+n2}}else{state2.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state2){var ch=state2.current();if(isOctalDigit(ch)){state2.lastIntValue=ch-48;state2.advance();return true}state2.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state2,length){var start=state2.pos;state2.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state2=this.regexpState||(this.regexpState=new RegExpValidationState(this));state2.reset(start,pattern,flags);this.validateRegExpFlags(state2);this.validateRegExpPattern(state2);var value2=null;try{value2=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern,flags,value:value2})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos0){recording.pop()}}function insertVariable(name2,value2){variables[name2]=value2}function getEntity(value2){const name2=entityNames[value2];if(name2){return contextName+"."+name2}return value2}function setIndent(spaces){indent=" ".repeat(spaces)}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;recording.push(`${indent}const ${variableName} = ${source};`);contextVariables.push(value2);return variableName}function writePPM(width,height){const sourceVariable=`${contextName}Variable${contextVariables.length}`;const imageVariable=`imageDatum${imageCount}`;recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`);recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`);recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`);recording.push(`${indent}}`);recording.push(`${indent}if (typeof require !== "undefined") {`);recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`);recording.push(`${indent}}`);imageCount++}function addComment(value2){recording.push(`${indent}// ${value2}`)}function checkThrowError(){recording.push(`${indent}(() => { - ${indent}const error = ${contextName}.getError(); - ${indent}if (error !== ${contextName}.NONE) { - ${indent} const names = Object.getOwnPropertyNames(gl); - ${indent} for (let i = 0; i < names.length; i++) { - ${indent} const name = names[i]; - ${indent} if (${contextName}[name] === error) { - ${indent} throw new Error('${contextName} threw ' + name); - ${indent} } - ${indent} } - ${indent}} - ${indent}})();`)}function methodCallToString(method,args){return`${contextName}.${method}(${argumentsToString(args,{contextName,contextVariables,getEntity,addVariable,variables,onUnrecognizedArgumentLookup})})`}function getVariableName(value2){if(variables){for(const name2 in variables){if(variables[name2]===value2){return name2}}}return null}function getContextVariableName(value2){const i=contextVariables.indexOf(value2);if(i!==-1){return`${contextName}Variable${i}`}return null}}function glExtensionWiretap(extension,options){const proxy=new Proxy(extension,{get:listen});const extensionEntityNames={};const{contextName,contextVariables,getEntity,useTrackablePrimitives,recording,variables,indent,onUnrecognizedArgumentLookup}=options;return proxy;function listen(obj,property){if(typeof obj[property]==="function"){return function(){switch(property){case"drawBuffersWEBGL":recording.push(`${indent}${contextName}.drawBuffersWEBGL([${argumentsToString(arguments[0],{contextName,contextVariables,getEntity:getExtensionEntity,addVariable,variables,onUnrecognizedArgumentLookup})}]);`);return extension.drawBuffersWEBGL(arguments[0])}let result=extension[property].apply(extension,arguments);switch(typeof result){case"undefined":recording.push(`${indent}${methodCallToString(property,arguments)};`);return;case"number":case"boolean":if(useTrackablePrimitives&&contextVariables.indexOf(trackablePrimitive(result))===-1){recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property,arguments)};`);contextVariables.push(result=trackablePrimitive(result))}else{recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property,arguments)};`);contextVariables.push(result)}break;default:if(result===null){recording.push(`${methodCallToString(property,arguments)};`)}else{recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property,arguments)};`)}contextVariables.push(result)}return result}}extensionEntityNames[extension[property]]=property;return extension[property]}function getExtensionEntity(value2){if(extensionEntityNames.hasOwnProperty(value2)){return`${contextName}.${extensionEntityNames[value2]}`}return getEntity(value2)}function methodCallToString(method,args){return`${contextName}.${method}(${argumentsToString(args,{contextName,contextVariables,getEntity:getExtensionEntity,addVariable,variables,onUnrecognizedArgumentLookup})})`}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;contextVariables.push(value2);recording.push(`${indent}const ${variableName} = ${source};`);return variableName}}function argumentsToString(args,options){const{variables,onUnrecognizedArgumentLookup}=options;return Array.from(args).map(arg=>{const variableName=getVariableName(arg);if(variableName){return variableName}return argumentToString(arg,options)}).join(", ");function getVariableName(value2){if(variables){for(const name2 in variables){if(!variables.hasOwnProperty(name2))continue;if(variables[name2]===value2){return name2}}}if(onUnrecognizedArgumentLookup){return onUnrecognizedArgumentLookup(value2)}return null}}function argumentToString(arg,options){const{contextName,contextVariables,getEntity,addVariable,onUnrecognizedArgumentLookup}=options;if(typeof arg==="undefined"){return"undefined"}if(arg===null){return"null"}const i=contextVariables.indexOf(arg);if(i>-1){return`${contextName}Variable${i}`}switch(arg.constructor.name){case"String":const hasLines=/\n/.test(arg);const hasSingleQuotes=/'/.test(arg);const hasDoubleQuotes=/"/.test(arg);if(hasLines){return"`"+arg+"`"}else if(hasSingleQuotes&&!hasDoubleQuotes){return'"'+arg+'"'}else if(!hasSingleQuotes&&hasDoubleQuotes){return"'"+arg+"'"}else{return"'"+arg+"'"}case"Number":return getEntity(arg);case"Boolean":return getEntity(arg);case"Array":return addVariable(arg,`new ${arg.constructor.name}([${Array.from(arg).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return addVariable(arg,`new ${arg.constructor.name}(${JSON.stringify(Array.from(arg))})`);default:if(onUnrecognizedArgumentLookup){const instantiationString=onUnrecognizedArgumentLookup(arg);if(instantiationString){return instantiationString}}throw new Error(`unrecognized argument type ${arg.constructor.name}`)}}function trackablePrimitive(value2){return new value2.constructor(value2)}if(typeof module3!=="undefined"){module3.exports={glWiretap,glExtensionWiretap}}if(typeof window!=="undefined"){glWiretap.glExtensionWiretap=glExtensionWiretap;window.glWiretap=glWiretap}},{}],4:[function(require2,module3,exports3){function setupArguments(args){const newArguments=new Array(args.length);for(let i=0;i{kernel.output=setupOutput(output);if(kernel.graphical){setupGraphical(kernel)}};kernel.toJSON=()=>{throw new Error("Not usable with gpuMock")};kernel.setConstants=flag=>{kernel.constants=flag;return kernel};kernel.setGraphical=flag=>{kernel.graphical=flag;return kernel};kernel.setCanvas=flag=>{kernel.canvas=flag;return kernel};kernel.setContext=flag=>{kernel.context=flag;return kernel};kernel.destroy=()=>{};kernel.validateSettings=()=>{};if(kernel.graphical&&kernel.output){setupGraphical(kernel)}kernel.exec=function(){return new Promise((resolve,reject)=>{try{resolve(kernel.apply(kernel,arguments))}catch(e){reject(e)}})};kernel.getPixels=flip=>{const{x:x2,y}=kernel.output;return flip?flipPixels(kernel._imageData.data,x2,y):kernel._imageData.data.slice(0)};kernel.color=function(r,g,b,a){if(typeof a==="undefined"){a=1}r=Math.floor(r*255);g=Math.floor(g*255);b=Math.floor(b*255);a=Math.floor(a*255);const width=kernel.output.x;const height=kernel.output.y;const x2=kernel.thread.x;const y=height-kernel.thread.y-1;const index=x2+y*width;kernel._colorData[index*4+0]=r;kernel._colorData[index*4+1]=g;kernel._colorData[index*4+2]=b;kernel._colorData[index*4+3]=a};const mockMethod=()=>kernel;const methods=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let i=0;i0){retArr.push(", ")}retArr.push("user_");retArr.push(argumentName)}retArr.push(") {\n")}for(let i=0;i0){retArr.push(initArr.join(""),";\n")}retArr.push(`for (let ${iVariableName}=0;${iVariableName}0){retArr.push(`if (!${testArr.join("")}) break; -`)}retArr.push(bodyArr.join(""));retArr.push(` -${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whileNode,retArr){if(whileNode.type!=="WhileStatement"){throw this.astErrorOutput("Invalid while statement",whileNode)}retArr.push("for (let i = 0; i < LOOP_MAX; i++) {");retArr.push("if (");this.astGeneric(whileNode.test,retArr);retArr.push(") {\n");this.astGeneric(whileNode.body,retArr);retArr.push("} else {\n");retArr.push("break;\n");retArr.push("}\n");retArr.push("}\n");return retArr}astDoWhileStatement(doWhileNode,retArr){if(doWhileNode.type!=="DoWhileStatement"){throw this.astErrorOutput("Invalid while statement",doWhileNode)}retArr.push("for (let i = 0; i < LOOP_MAX; i++) {");this.astGeneric(doWhileNode.body,retArr);retArr.push("if (!");this.astGeneric(doWhileNode.test,retArr);retArr.push(") {\n");retArr.push("break;\n");retArr.push("}\n");retArr.push("}\n");return retArr}astAssignmentExpression(assNode,retArr){const declaration=this.getDeclaration(assNode.left);if(declaration&&!declaration.assignable){throw this.astErrorOutput(`Variable ${assNode.left.name} is not assignable here`,assNode)}this.astGeneric(assNode.left,retArr);retArr.push(assNode.operator);this.astGeneric(assNode.right,retArr);return retArr}astBlockStatement(bNode,retArr){if(this.isState("loop-body")){this.pushState("block-body");for(let i=0;i0){retArr.push(",")}const declaration=declarations[i];const info=this.getDeclaration(declaration.id);if(!info.valueType){info.valueType=this.getType(declaration.init)}this.astGeneric(declaration,retArr)}if(!this.isState("in-for-loop-init")){retArr.push(";")}return retArr}astIfStatement(ifNode,retArr){retArr.push("if (");this.astGeneric(ifNode.test,retArr);retArr.push(")");if(ifNode.consequent.type==="BlockStatement"){this.astGeneric(ifNode.consequent,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.consequent,retArr);retArr.push("\n}\n")}if(ifNode.alternate){retArr.push("else ");if(ifNode.alternate.type==="BlockStatement"||ifNode.alternate.type==="IfStatement"){this.astGeneric(ifNode.alternate,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.alternate,retArr);retArr.push("\n}\n")}}return retArr}astSwitchStatement(ast,retArr){const{discriminant,cases}=ast;retArr.push("switch (");this.astGeneric(discriminant,retArr);retArr.push(") {\n");for(let i=0;i0){retArr.push("break;\n")}continue}retArr.push("case ");this.astGeneric(cases[i].test,retArr);retArr.push(":\n");if(cases[i].consequent&&cases[i].consequent.length>0){this.astGeneric(cases[i].consequent,retArr);retArr.push("break;\n")}}retArr.push("\n}")}astThisExpression(tNode,retArr){retArr.push("_this");return retArr}astMemberExpression(mNode,retArr){const{signature,type,property,xProperty,yProperty,zProperty,name:name2,origin}=this.getMemberExpressionDetails(mNode);switch(signature){case"this.thread.value":retArr.push(`_this.thread.${name2}`);return retArr;case"this.output.value":switch(name2){case"x":retArr.push("outputX");break;case"y":retArr.push("outputY");break;case"z":retArr.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",mNode)}return retArr;case"value":throw this.astErrorOutput("Unexpected expression",mNode);case"value[]":case"value[][]":case"value[][][]":case"value.value":if(origin==="Math"){retArr.push(Math[name2]);return retArr}switch(property){case"r":retArr.push(`user_${name2}[0]`);return retArr;case"g":retArr.push(`user_${name2}[1]`);return retArr;case"b":retArr.push(`user_${name2}[2]`);return retArr;case"a":retArr.push(`user_${name2}[3]`);return retArr}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":this.astGeneric(mNode.object,retArr);retArr.push("[");this.astGeneric(mNode.property,retArr);retArr.push("]");return retArr;case"fn()[][]":this.astGeneric(mNode.object.object,retArr);retArr.push("[");this.astGeneric(mNode.object.property,retArr);retArr.push("]");retArr.push("[");this.astGeneric(mNode.property,retArr);retArr.push("]");return retArr;default:throw this.astErrorOutput("Unexpected expression",mNode)}if(!mNode.computed){switch(type){case"Number":case"Integer":case"Float":case"Boolean":retArr.push(`${origin}_${name2}`);return retArr}}const markupName=`${origin}_${name2}`;switch(type){case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":case"HTMLImageArray":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"HTMLImage":default:let size;let isInput;if(origin==="constants"){const constant=this.constants[name2];isInput=this.constantTypes[name2]==="Input";size=isInput?constant.size:null}else{isInput=this.isInput(name2);size=isInput?this.argumentSizes[this.argumentNames.indexOf(name2)]:null}retArr.push(`${markupName}`);if(zProperty&&yProperty){if(isInput){retArr.push("[(");this.astGeneric(zProperty,retArr);retArr.push(`*${this.dynamicArguments?"(outputY * outputX)":size[1]*size[0]})+(`);this.astGeneric(yProperty,retArr);retArr.push(`*${this.dynamicArguments?"outputX":size[0]})+`);this.astGeneric(xProperty,retArr);retArr.push("]")}else{retArr.push("[");this.astGeneric(zProperty,retArr);retArr.push("]");retArr.push("[");this.astGeneric(yProperty,retArr);retArr.push("]");retArr.push("[");this.astGeneric(xProperty,retArr);retArr.push("]")}}else if(yProperty){if(isInput){retArr.push("[(");this.astGeneric(yProperty,retArr);retArr.push(`*${this.dynamicArguments?"outputX":size[0]})+`);this.astGeneric(xProperty,retArr);retArr.push("]")}else{retArr.push("[");this.astGeneric(yProperty,retArr);retArr.push("]");retArr.push("[");this.astGeneric(xProperty,retArr);retArr.push("]")}}else if(typeof xProperty!=="undefined"){retArr.push("[");this.astGeneric(xProperty,retArr);retArr.push("]")}}return retArr}astCallExpression(ast,retArr){if(ast.type!=="CallExpression"){throw this.astErrorOutput("Unknown CallExpression",ast)}let functionName=this.astMemberExpressionUnroll(ast.callee);if(this.calledFunctions.indexOf(functionName)<0){this.calledFunctions.push(functionName)}const isMathFunction=this.isAstMathFunction(ast);if(this.onFunctionCall){this.onFunctionCall(this.name,functionName,ast.arguments)}retArr.push(functionName);retArr.push("(");const targetTypes=this.lookupFunctionArgumentTypes(functionName)||[];for(let i=0;i0){retArr.push(", ")}this.astGeneric(argument,retArr)}retArr.push(")");return retArr}astArrayExpression(arrNode,retArr){const returnType=this.getType(arrNode);const arrLen=arrNode.elements.length;const elements=[];for(let i=0;i{switch(propertyName){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(cpuKernel[propertyName])},findDependency:(object,name3)=>{return null}});const getPixelsFn=utils.flattenFunctionToString((useFunctionKeyword?"function ":"")+cpuKernel.getPixels.toString(),{thisLookup:propertyName=>{switch(propertyName){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(cpuKernel[propertyName])},findDependency:()=>{return null}});thisProperties.push(" _imageData,"," _colorData,",` color: ${colorFn},`);beforeReturn.push(` kernel.getPixels = ${getPixelsFn};`)}const constantTypes=[];const constantKeys=Object.keys(cpuKernel.constantTypes);for(let i=0;i{if(object==="this"){return(useFunctionKeyword?"function ":"")+cpuKernel[name3].toString()}return null},thisLookup:propertyName=>{switch(propertyName){case"canvas":return;case"context":return"context"}}});beforeReturn.push(flattenedImageTo3DArray);thisProperties.push(` _mediaTo2DArray,`);thisProperties.push(` _imageTo3DArray,`)}else if(cpuKernel.argumentTypes.indexOf("HTMLImage")!==-1||constantTypes.indexOf("HTMLImage")!==-1){const flattenedImageTo2DArray=utils.flattenFunctionToString((useFunctionKeyword?"function ":"")+cpuKernel._mediaTo2DArray.toString(),{findDependency:(object,name3)=>{return null},thisLookup:propertyName=>{switch(propertyName){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});beforeReturn.push(flattenedImageTo2DArray);thisProperties.push(` _mediaTo2DArray,`)}return`function(settings) { - ${header.join("\n")} - for (const p in _constantTypes) { - if (!_constantTypes.hasOwnProperty(p)) continue; - const type = _constantTypes[p]; - switch (type) { - case 'Number': - case 'Integer': - case 'Float': - case 'Boolean': - case 'Array(2)': - case 'Array(3)': - case 'Array(4)': - case 'Matrix(2)': - case 'Matrix(3)': - case 'Matrix(4)': - if (incomingConstants.hasOwnProperty(p)) { - console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned'); - } - continue; - } - if (!incomingConstants.hasOwnProperty(p)) { - throw new Error('constant ' + p + ' not found'); - } - _constants[p] = incomingConstants[p]; - } - const kernel = (function() { - ${cpuKernel._kernelString} - }) - .apply({ ${thisProperties.join("\n")} }); - ${beforeReturn.join("\n")} - return kernel; - }`}module3.exports={cpuKernelString}},{"../../utils":114}],8:[function(require2,module3,exports3){const{Kernel}=require2("../kernel");const{FunctionBuilder}=require2("../function-builder");const{CPUFunctionNode}=require2("./function-node");const{utils}=require2("../../utils");const{cpuKernelString}=require2("./kernel-string");class CPUKernel extends Kernel{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:true,isIntegerDivisionAccurate:true})}static get isSupported(){return true}static isContextMatch(context){return false}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(combinedKernel){return combinedKernel}static getSignature(kernel,argumentTypes){return"cpu"+(argumentTypes.length>0?":"+argumentTypes.join(","):"")}constructor(source,settings){super(source,settings);this.mergeSettings(source.settings||settings);this._imageData=null;this._colorData=null;this._kernelString=null;this._prependedString=[];this.thread={x:0,y:0,z:0};this.translatedSources=null}initCanvas(){if(typeof document!=="undefined"){return document.createElement("canvas")}else if(typeof OffscreenCanvas!=="undefined"){return new OffscreenCanvas(0,0)}}initContext(){if(!this.canvas)return null;return this.canvas.getContext("2d")}initPlugins(settings){return[]}validateSettings(args){if(!this.output||this.output.length===0){if(args.length!==1){throw new Error("Auto output only supported for kernels with only one input")}const argType=utils.getVariableType(args[0],this.strictIntegers);if(argType==="Array"){this.output=utils.getDimensions(argType)}else if(argType==="NumberTexture"||argType==="ArrayTexture(4)"){this.output=args[0].output}else{throw new Error("Auto output not supported for input type: "+argType)}}if(this.graphical){if(this.output.length!==2){throw new Error("Output must have 2 dimensions on graphical mode")}}this.checkOutput()}translateSource(){this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ";if(this.subKernels){const followingReturnStatement=[];for(let i=0;i1?`resultX_${name2}[x] = subKernelResult_${name2}; -`:`result_${name2}[x] = subKernelResult_${name2}; -`)}this.followingReturnStatement=followingReturnStatement.join("")}const functionBuilder=FunctionBuilder.fromKernel(this,CPUFunctionNode);this.translatedSources=functionBuilder.getPrototypes("kernel");if(!this.graphical&&!this.returnType){this.returnType=functionBuilder.getKernelResultType()}}build(){if(this.built)return;this.setupConstants();this.setupArguments(arguments);this.validateSettings(arguments);this.translateSource();if(this.graphical){const{canvas,output}=this;if(!canvas){throw new Error("no canvas available for using graphical output")}const width=output[0];const height=output[1]||1;canvas.width=width;canvas.height=height;this._imageData=this.context.createImageData(width,height);this._colorData=new Uint8ClampedArray(width*height*4)}const kernelString=this.getKernelString();this.kernelString=kernelString;if(this.debug){console.log("Function output:");console.log(kernelString)}try{this.run=new Function([],kernelString).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments);this.built=true}color(r,g,b,a){if(typeof a==="undefined"){a=1}r=Math.floor(r*255);g=Math.floor(g*255);b=Math.floor(b*255);a=Math.floor(a*255);const width=this.output[0];const height=this.output[1];const x2=this.thread.x;const y=height-this.thread.y-1;const index=x2+y*width;this._colorData[index*4+0]=r;this._colorData[index*4+1]=g;this._colorData[index*4+2]=b;this._colorData[index*4+3]=a}getKernelString(){if(this._kernelString!==null)return this._kernelString;let kernelThreadString=null;let{translatedSources}=this;if(translatedSources.length>1){translatedSources=translatedSources.filter(fn=>{if(/^function/.test(fn))return fn;kernelThreadString=fn;return false})}else{kernelThreadString=translatedSources.shift()}return this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()}; - ${this.injectedNative||""} - const _this = this; - ${this._resultKernelHeader()} - ${this._processConstants()} - return (${this.argumentNames.map(argumentName=>"user_"+argumentName).join(", ")}) => { - ${this._prependedString.join("")} - ${this._earlyThrows()} - ${this._processArguments()} - ${this.graphical?this._graphicalKernelBody(kernelThreadString):this._resultKernelBody(kernelThreadString)} - ${translatedSources.length>0?translatedSources.join("\n"):""} - };`}toString(){return cpuKernelString(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const result=[];for(let p in this.constants){const type=this.constantTypes[p];switch(type){case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":result.push(` const constants_${p} = this._mediaTo2DArray(this.constants.${p}); -`);break;case"HTMLImageArray":result.push(` const constants_${p} = this._imageTo3DArray(this.constants.${p}); -`);break;case"Input":result.push(` const constants_${p} = this.constants.${p}.value; -`);break;default:result.push(` const constants_${p} = this.constants.${p}; -`)}}return result.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const arrayArguments=[];for(let i=0;i`user_${argumentName} === result_${subKernel.name}`).join(" || ");checks.push(`user_${argumentName} === result${checkSubKernels?` || ${checkSubKernels}`:""}`)}return`if (${checks.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const result=[];for(let i=0;i0?media.width:media.videoWidth;const height=media.height>0?media.height:media.videoHeight;if(canvas.width=0;y--){const row=imageArray[y]=new Array(width);for(let x2=0;x2`const result_${subKernel.name} = new ${constructorString}(outputX); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - this.thread.y = 0; - this.thread.z = 0; - ${kernelString} - }`}_mutableKernel1DResults(){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const result = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new ${constructorString}(outputX); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")}`}_resultMutableKernel1DLoop(kernelString){return` const outputX = _this.output[0]; - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - this.thread.y = 0; - this.thread.z = 0; - ${kernelString} - }`}_resultImmutableKernel2DLoop(kernelString){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const result = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputY); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let y = 0; y < outputY; y++) { - this.thread.z = 0; - this.thread.y = y; - const resultX = result[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = result_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join("")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - }`}_mutableKernel2DResults(){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const result = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputY); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let y = 0; y < outputY; y++) { - const resultX = result[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = result_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join("")} - }`}_resultMutableKernel2DLoop(kernelString){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - for (let y = 0; y < outputY; y++) { - this.thread.z = 0; - this.thread.y = y; - const resultX = result[y]; - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = result_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join("")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - }`}_graphicalKernel2DLoop(kernelString){return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - for (let y = 0; y < outputY; y++) { - this.thread.z = 0; - this.thread.y = y; - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - }`}_resultImmutableKernel3DLoop(kernelString){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const outputZ = _this.output[2]; - const result = new Array(outputZ); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputZ); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let z = 0; z < outputZ; z++) { - this.thread.z = z; - const resultY = result[z] = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const resultY_${subKernel.name} = result_${subKernel.name}[z] = new Array(outputY); -`).join(" ")} - for (let y = 0; y < outputY; y++) { - this.thread.y = y; - const resultX = resultY[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = resultY_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join(" ")} - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - } - }`}_mutableKernel3DResults(){const constructorString=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const outputZ = _this.output[2]; - const result = new Array(outputZ); - ${this._mapSubKernels(subKernel=>`const result_${subKernel.name} = new Array(outputZ); -`).join(" ")} - ${this._mapSubKernels(subKernel=>`let subKernelResult_${subKernel.name}; -`).join(" ")} - for (let z = 0; z < outputZ; z++) { - const resultY = result[z] = new Array(outputY); - ${this._mapSubKernels(subKernel=>`const resultY_${subKernel.name} = result_${subKernel.name}[z] = new Array(outputY); -`).join(" ")} - for (let y = 0; y < outputY; y++) { - const resultX = resultY[y] = new ${constructorString}(outputX); - ${this._mapSubKernels(subKernel=>`const resultX_${subKernel.name} = resultY_${subKernel.name}[y] = new ${constructorString}(outputX); -`).join(" ")} - } - }`}_resultMutableKernel3DLoop(kernelString){return` const outputX = _this.output[0]; - const outputY = _this.output[1]; - const outputZ = _this.output[2]; - for (let z = 0; z < outputZ; z++) { - this.thread.z = z; - const resultY = result[z]; - for (let y = 0; y < outputY; y++) { - this.thread.y = y; - const resultX = resultY[y]; - for (let x = 0; x < outputX; x++) { - this.thread.x = x; - ${kernelString} - } - } - }`}_kernelOutput(){if(!this.subKernels){return"\n return result;"}return` - return { - result: result, - ${this.subKernels.map(subKernel=>`${subKernel.property}: result_${subKernel.name}`).join(",\n ")} - };`}_mapSubKernels(fn){return this.subKernels===null?[""]:this.subKernels.map(fn)}destroy(removeCanvasReference){if(removeCanvasReference){delete this.canvas}}static destroyContext(context){}toJSON(){const json=super.toJSON();json.functionNodes=FunctionBuilder.fromKernel(this,CPUFunctionNode).toJSON();return json}setOutput(output){super.setOutput(output);const[width,height]=this.output;if(this.graphical){this._imageData=this.context.createImageData(width,height);this._colorData=new Uint8ClampedArray(width*height*4)}}prependString(value2){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(value2)}hasPrependString(value2){return this._prependedString.indexOf(value2)>-1}}module3.exports={CPUKernel}},{"../../utils":114,"../function-builder":9,"../kernel":36,"./function-node":6,"./kernel-string":7}],9:[function(require2,module3,exports3){class FunctionBuilder{static fromKernel(kernel,FunctionNode,extraNodeOptions){const{kernelArguments,kernelConstants,argumentNames,argumentSizes,argumentBitRatios,constants,constantBitRatios,debug,loopMaxIterations,nativeFunctions,output,optimizeFloatMemory,precision,plugins,source,subKernels,functions,leadingReturnStatement,followingReturnStatement,dynamicArguments,dynamicOutput}=kernel;const argumentTypes=new Array(kernelArguments.length);const constantTypes={};for(let i=0;i{return functionBuilder.needsArgumentType(functionName,index)};const assignArgumentType=(functionName,index,type)=>{functionBuilder.assignArgumentType(functionName,index,type)};const lookupReturnType=(functionName,ast,requestingNode)=>{return functionBuilder.lookupReturnType(functionName,ast,requestingNode)};const lookupFunctionArgumentTypes=functionName=>{return functionBuilder.lookupFunctionArgumentTypes(functionName)};const lookupFunctionArgumentName=(functionName,argumentIndex)=>{return functionBuilder.lookupFunctionArgumentName(functionName,argumentIndex)};const lookupFunctionArgumentBitRatio=(functionName,argumentName)=>{return functionBuilder.lookupFunctionArgumentBitRatio(functionName,argumentName)};const triggerImplyArgumentType=(functionName,i,argumentType,requestingNode)=>{functionBuilder.assignArgumentType(functionName,i,argumentType,requestingNode)};const triggerImplyArgumentBitRatio=(functionName,argumentName,calleeFunctionName,argumentIndex)=>{functionBuilder.assignArgumentBitRatio(functionName,argumentName,calleeFunctionName,argumentIndex)};const onFunctionCall=(functionName,calleeFunctionName,args)=>{functionBuilder.trackFunctionCall(functionName,calleeFunctionName,args)};const onNestedFunction=(ast,source2)=>{const argumentNames2=[];for(let i=0;inew FunctionNode(fn.source,{returnType:fn.returnType,argumentTypes:fn.argumentTypes,output,plugins,constants,constantTypes,constantBitRatios,optimizeFloatMemory,precision,lookupReturnType,lookupFunctionArgumentTypes,lookupFunctionArgumentName,lookupFunctionArgumentBitRatio,needsArgumentType,assignArgumentType,triggerImplyArgumentType,triggerImplyArgumentBitRatio,onFunctionCall,onNestedFunction}))}let subKernelNodes=null;if(subKernels){subKernelNodes=subKernels.map(subKernel=>{const{name:name2,source:source2}=subKernel;return new FunctionNode(source2,Object.assign({},nodeOptions,{name:name2,isSubKernel:true,isRootKernel:false}))})}const functionBuilder=new FunctionBuilder({kernel,rootNode,functionNodes,nativeFunctions,subKernelNodes});return functionBuilder}constructor(settings){settings=settings||{};this.kernel=settings.kernel;this.rootNode=settings.rootNode;this.functionNodes=settings.functionNodes||[];this.subKernelNodes=settings.subKernelNodes||[];this.nativeFunctions=settings.nativeFunctions||[];this.functionMap={};this.nativeFunctionNames=[];this.lookupChain=[];this.functionNodeDependencies={};this.functionCalls={};if(this.rootNode){this.functionMap["kernel"]=this.rootNode}if(this.functionNodes){for(let i=0;i-1){const nativeFunctionIndex=retList.indexOf(functionName);if(nativeFunctionIndex===-1){retList.push(functionName)}else{const dependantNativeFunctionName=retList.splice(nativeFunctionIndex,1)[0];retList.push(dependantNativeFunctionName)}return retList}const functionNode=this.functionMap[functionName];if(functionNode){const functionIndex=retList.indexOf(functionName);if(functionIndex===-1){retList.push(functionName);functionNode.toString();for(let i=0;i-1){ret.push(this.nativeFunctions[functionIndex].source);continue}const node=this.functionMap[functionName];if(node){ret.push(node.toString())}}return ret}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(name2=>{const nativeIndex=this.nativeFunctions.indexOf(name2);if(nativeIndex>-1){return{name:name2,source:this.nativeFunctions[nativeIndex].source}}else if(this.functionMap[name2]){return this.functionMap[name2].toJSON()}else{throw new Error(`function ${name2} not found`)}})}fromJSON(jsonFunctionNodes,FunctionNode){this.functionMap={};for(let i=0;i0){const args=ast.arguments;for(let j=0;j0&&this.argumentTypes.length!==this.argumentNames.length){throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`)}if(this.output.length<1){throw new Error("this.output is not big enough")}}isIdentifierConstant(name2){if(!this.constants)return false;return this.constants.hasOwnProperty(name2)}isInput(argumentName){return this.argumentTypes[this.argumentNames.indexOf(argumentName)]==="Input"}pushState(state2){this.states.push(state2)}popState(state2){if(this.state!==state2){throw new Error(`Cannot popState ${state2} when in ${this.state}`)}this.states.pop()}isState(state2){return this.state===state2}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(ast){if(ast.type==="Identifier"){return ast.name}else if(ast.type==="ThisExpression"){return"this"}if(ast.type==="MemberExpression"){if(ast.object&&ast.property){if(ast.object.hasOwnProperty("name")&&ast.object.name!=="Math"){return this.astMemberExpressionUnroll(ast.property)}return this.astMemberExpressionUnroll(ast.object)+"."+this.astMemberExpressionUnroll(ast.property)}}if(ast.hasOwnProperty("expressions")){const firstExpression=ast.expressions[0];if(firstExpression.type==="Literal"&&firstExpression.value===0&&ast.expressions.length===2){return this.astMemberExpressionUnroll(ast.expressions[1])}}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",ast)}getJsAST(inParser){if(this.ast){return this.ast}if(typeof this.source==="object"){this.traceFunctionAST(this.source);return this.ast=this.source}inParser=inParser||acorn;if(inParser===null){throw new Error("Missing JS to AST parser")}const ast=Object.freeze(inParser.parse(`const parser_${this.name} = ${this.source};`,{locations:true}));const functionAST=ast.body[0].declarations[0].init;this.traceFunctionAST(functionAST);if(!ast){throw new Error("Failed to parse JS code")}return this.ast=functionAST}traceFunctionAST(ast){const{contexts,declarations,functions,identifiers,functionCalls}=new FunctionTracer(ast);this.contexts=contexts;this.identifiers=identifiers;this.functionCalls=functionCalls;this.functions=functions;for(let i=0;i":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const type=this.getType(ast.left);if(this.isState("skip-literal-correction"))return type;if(type==="LiteralInteger"){const rightType=this.getType(ast.right);if(rightType==="LiteralInteger"){if(ast.left.value%1===0){return"Integer"}else{return"Float"}}return rightType}return typeLookupMap[type]||type;case"UpdateExpression":return this.getType(ast.argument);case"UnaryExpression":if(ast.operator==="~"){return"Integer"}return this.getType(ast.argument);case"VariableDeclaration":{const declarations=ast.declarations;let lastType;for(let i=0;i-1}isAstMathFunction(ast){const mathFunctions=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"];return ast.type==="CallExpression"&&ast.callee&&ast.callee.type==="MemberExpression"&&ast.callee.object&&ast.callee.object.type==="Identifier"&&ast.callee.object.name==="Math"&&ast.callee.property&&ast.callee.property.type==="Identifier"&&mathFunctions.indexOf(ast.callee.property.name)>-1}isAstVariable(ast){return ast.type==="Identifier"||ast.type==="MemberExpression"}isSafe(ast){return this.isSafeDependencies(this.getDependencies(ast))}isSafeDependencies(dependencies){return dependencies&&dependencies.every?dependencies.every(dependency=>dependency.isSafe):true}getDependencies(ast,dependencies,isNotSafe){if(!dependencies){dependencies=[]}if(!ast)return null;if(Array.isArray(ast)){for(let i=0;i-Infinity&&ast.value-1){dependencies.push({name:ast.name,origin:"argument",isSafe:false})}else if(this.strictTypingChecking){throw new Error(`Cannot find identifier origin "${ast.name}"`)}break;case"FunctionDeclaration":return this.getDependencies(ast.body.body[ast.body.body.length-1],dependencies,isNotSafe);case"ReturnStatement":return this.getDependencies(ast.argument,dependencies);case"BinaryExpression":case"LogicalExpression":isNotSafe=ast.operator==="/"||ast.operator==="*";this.getDependencies(ast.left,dependencies,isNotSafe);this.getDependencies(ast.right,dependencies,isNotSafe);return dependencies;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(ast.argument,dependencies,isNotSafe);case"VariableDeclaration":return this.getDependencies(ast.declarations,dependencies,isNotSafe);case"ArrayExpression":dependencies.push({origin:"declaration",isSafe:true});return dependencies;case"CallExpression":dependencies.push({origin:"function",isSafe:true});return dependencies;case"MemberExpression":const details=this.getMemberExpressionDetails(ast);switch(details.signature){case"value[]":this.getDependencies(ast.object,dependencies,isNotSafe);break;case"value[][]":this.getDependencies(ast.object.object,dependencies,isNotSafe);break;case"value[][][]":this.getDependencies(ast.object.object.object,dependencies,isNotSafe);break;case"this.output.value":if(this.dynamicOutput){dependencies.push({name:details.name,origin:"output",isSafe:false})}break}if(details){if(details.property){this.getDependencies(details.property,dependencies,isNotSafe)}if(details.xProperty){this.getDependencies(details.xProperty,dependencies,isNotSafe)}if(details.yProperty){this.getDependencies(details.yProperty,dependencies,isNotSafe)}if(details.zProperty){this.getDependencies(details.zProperty,dependencies,isNotSafe)}return dependencies}case"SequenceExpression":return this.getDependencies(ast.expressions,dependencies,isNotSafe);default:throw this.astErrorOutput(`Unhandled type ${ast.type} in getDependencies`,ast)}return dependencies}getVariableSignature(ast,returnRawValue){if(!this.isAstVariable(ast)){throw new Error(`ast of type "${ast.type}" is not a variable signature`)}if(ast.type==="Identifier"){return"value"}const signature=[];while(true){if(!ast)break;if(ast.computed){signature.push("[]")}else if(ast.type==="ThisExpression"){signature.unshift("this")}else if(ast.property&&ast.property.name){if(ast.property.name==="x"||ast.property.name==="y"||ast.property.name==="z"){signature.unshift(returnRawValue?"."+ast.property.name:".value")}else if(ast.property.name==="constants"||ast.property.name==="thread"||ast.property.name==="output"){signature.unshift("."+ast.property.name)}else{signature.unshift(returnRawValue?"."+ast.property.name:".value")}}else if(ast.name){signature.unshift(returnRawValue?ast.name:"value")}else if(ast.callee&&ast.callee.name){signature.unshift(returnRawValue?ast.callee.name+"()":"fn()")}else if(ast.elements){signature.unshift("[]")}else{signature.unshift("unknown")}ast=ast.object}const signatureString=signature.join("");if(returnRawValue){return signatureString}const allowedExpressions=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];if(allowedExpressions.indexOf(signatureString)>-1){return signatureString}return null}build(){return this.toString().length>0}astGeneric(ast,retArr){if(ast===null){throw this.astErrorOutput("NULL ast",ast)}else{if(Array.isArray(ast)){for(let i=0;i0?splitLines[splitLines.length-1]:0;return new Error(`${error} on line ${splitLines.length}, position ${lineBefore.length}: - ${debugString}`)}astDebuggerStatement(arrNode,retArr){return retArr}astConditionalExpression(ast,retArr){if(ast.type!=="ConditionalExpression"){throw this.astErrorOutput("Not a conditional expression",ast)}retArr.push("(");this.astGeneric(ast.test,retArr);retArr.push("?");this.astGeneric(ast.consequent,retArr);retArr.push(":");this.astGeneric(ast.alternate,retArr);retArr.push(")");return retArr}astFunction(ast,retArr){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(ast,retArr){if(this.isChildFunction(ast)){return retArr}return this.astFunction(ast,retArr)}astFunctionExpression(ast,retArr){if(this.isChildFunction(ast)){return retArr}return this.astFunction(ast,retArr)}isChildFunction(ast){for(let i=0;i1){retArr.push("(",sequenceResult.join(","),")")}else{retArr.push(sequenceResult[0])}return retArr}astUnaryExpression(uNode,retArr){const unaryResult=this.checkAndUpconvertBitwiseUnary(uNode,retArr);if(unaryResult){return retArr}if(uNode.prefix){retArr.push(uNode.operator);this.astGeneric(uNode.argument,retArr)}else{this.astGeneric(uNode.argument,retArr);retArr.push(uNode.operator)}return retArr}checkAndUpconvertBitwiseUnary(uNode,retArr){}astUpdateExpression(uNode,retArr){if(uNode.prefix){retArr.push(uNode.operator);this.astGeneric(uNode.argument,retArr)}else{this.astGeneric(uNode.argument,retArr);retArr.push(uNode.operator)}return retArr}astLogicalExpression(logNode,retArr){retArr.push("(");this.astGeneric(logNode.left,retArr);retArr.push(logNode.operator);this.astGeneric(logNode.right,retArr);retArr.push(")");return retArr}astMemberExpression(ast,retArr){return retArr}astCallExpression(ast,retArr){return retArr}astArrayExpression(ast,retArr){return retArr}getMemberExpressionDetails(ast){if(ast.type!=="MemberExpression"){throw this.astErrorOutput(`Expression ${ast.type} not a MemberExpression`,ast)}let name2=null;let type=null;const variableSignature=this.getVariableSignature(ast);switch(variableSignature){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:variableSignature,type:"Integer",name:ast.property.name};case"value[]":if(typeof ast.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object),xProperty:ast.property};case"value[][]":if(typeof ast.object.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object.object),yProperty:ast.object.property,xProperty:ast.property};case"value[][][]":if(typeof ast.object.object.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object.object.object),zProperty:ast.object.object.property,yProperty:ast.object.property,xProperty:ast.property};case"value[][][][]":if(typeof ast.object.object.object.object.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.object.object.name;return{name:name2,origin:"user",signature:variableSignature,type:this.getVariableType(ast.object.object.object.object),zProperty:ast.object.object.property,yProperty:ast.object.property,xProperty:ast.property};case"value.value":if(typeof ast.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}if(this.isAstMathVariable(ast)){name2=ast.property.name;return{name:name2,origin:"Math",type:"Number",signature:variableSignature}}switch(ast.property.name){case"r":case"g":case"b":case"a":name2=ast.object.name;return{name:name2,property:ast.property.name,origin:"user",signature:variableSignature,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",ast)}case"this.constants.value":if(typeof ast.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature};case"this.constants.value[]":if(typeof ast.object.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature,xProperty:ast.property};case"this.constants.value[][]":{if(typeof ast.object.object.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature,yProperty:ast.object.property,xProperty:ast.property}}case"this.constants.value[][][]":{if(typeof ast.object.object.object.property.name!=="string"){throw this.astErrorOutput("Unexpected expression",ast)}name2=ast.object.object.object.property.name;type=this.getConstantType(name2);if(!type){throw this.astErrorOutput("Constant has no type",ast)}return{name:name2,type,origin:"constants",signature:variableSignature,zProperty:ast.object.object.property,yProperty:ast.object.property,xProperty:ast.property}}case"fn()[]":case"fn()[][]":case"[][]":return{signature:variableSignature,property:ast.property};default:throw this.astErrorOutput("Unexpected expression",ast)}}findIdentifierOrigin(astToFind){const stack=[this.ast];while(stack.length>0){const atNode=stack[0];if(atNode.type==="VariableDeclarator"&&atNode.id&&atNode.id.name&&atNode.id.name===astToFind.name){return atNode}stack.shift();if(atNode.argument){stack.push(atNode.argument)}else if(atNode.body){stack.push(atNode.body)}else if(atNode.declarations){stack.push(atNode.declarations)}else if(Array.isArray(atNode)){for(let i=0;i0){const atNode=stack.pop();if(atNode.type==="ReturnStatement"){return atNode}if(atNode.type==="FunctionDeclaration"){continue}if(atNode.argument){stack.push(atNode.argument)}else if(atNode.body){stack.push(atNode.body)}else if(atNode.declarations){stack.push(atNode.declarations)}else if(Array.isArray(atNode)){for(let i=0;i0?array[array.length-1]:null}const states={trackIdentifiers:"trackIdentifiers",memberExpression:"memberExpression",inForLoopInit:"inForLoopInit"};class FunctionTracer{constructor(ast){this.runningContexts=[];this.functionContexts=[];this.contexts=[];this.functionCalls=[];this.declarations=[];this.identifiers=[];this.functions=[];this.returnStatements=[];this.trackedIdentifiers=null;this.states=[];this.newFunctionContext();this.scan(ast)}isState(state2){return this.states[this.states.length-1]===state2}hasState(state2){return this.states.indexOf(state2)>-1}pushState(state2){this.states.push(state2)}popState(state2){if(this.isState(state2)){this.states.pop()}else{throw new Error(`Cannot pop the non-active state "${state2}"`)}}get currentFunctionContext(){return last(this.functionContexts)}get currentContext(){return last(this.runningContexts)}newFunctionContext(){const newContext={"@contextType":"function"};this.contexts.push(newContext);this.functionContexts.push(newContext)}newContext(run){const newContext=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(newContext);this.runningContexts.push(newContext);run();const{currentFunctionContext}=this;for(const p in currentFunctionContext){if(!currentFunctionContext.hasOwnProperty(p)||newContext.hasOwnProperty(p))continue;newContext[p]=currentFunctionContext[p]}this.runningContexts.pop();return newContext}useFunctionContext(run){const functionContext=last(this.functionContexts);this.runningContexts.push(functionContext);run();this.runningContexts.pop()}getIdentifiers(run){const trackedIdentifiers=this.trackedIdentifiers=[];this.pushState(states.trackIdentifiers);run();this.trackedIdentifiers=null;this.popState(states.trackIdentifiers);return trackedIdentifiers}getDeclaration(name2){const{currentContext,currentFunctionContext,runningContexts}=this;const declaration=currentContext[name2]||currentFunctionContext[name2]||null;if(!declaration&¤tContext===currentFunctionContext&&runningContexts.length>0){const previousRunningContext=runningContexts[runningContexts.length-2];if(previousRunningContext[name2]){return previousRunningContext[name2]}}return declaration}scan(ast){if(!ast)return;if(Array.isArray(ast)){for(let i=0;i{this.scan(ast.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(ast.body)});break;case"AssignmentExpression":case"LogicalExpression":this.scan(ast.left);this.scan(ast.right);break;case"BinaryExpression":this.scan(ast.left);this.scan(ast.right);break;case"UpdateExpression":if(ast.operator==="++"){const declaration=this.getDeclaration(ast.argument.name);if(declaration){declaration.suggestedType="Integer"}}this.scan(ast.argument);break;case"UnaryExpression":this.scan(ast.argument);break;case"VariableDeclaration":if(ast.kind==="var"){this.useFunctionContext(()=>{ast.declarations=utils.normalizeDeclarations(ast);this.scan(ast.declarations)})}else{ast.declarations=utils.normalizeDeclarations(ast);this.scan(ast.declarations)}break;case"VariableDeclarator":{const{currentContext}=this;const inForLoopInit=this.hasState(states.inForLoopInit);const declaration={ast,context:currentContext,name:ast.id.name,origin:"declaration",inForLoopInit,inForLoopTest:null,assignable:currentContext===this.currentFunctionContext||!inForLoopInit&&!currentContext.hasOwnProperty(ast.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};if(!currentContext[ast.id.name]){currentContext[ast.id.name]=declaration}this.declarations.push(declaration);this.scan(ast.id);this.scan(ast.init);break}case"FunctionExpression":case"FunctionDeclaration":if(this.runningContexts.length===0){this.scan(ast.body)}else{this.functions.push(ast)}break;case"IfStatement":this.scan(ast.test);this.scan(ast.consequent);if(ast.alternate)this.scan(ast.alternate);break;case"ForStatement":{let testIdentifiers;const context=this.newContext(()=>{this.pushState(states.inForLoopInit);this.scan(ast.init);this.popState(states.inForLoopInit);testIdentifiers=this.getIdentifiers(()=>{this.scan(ast.test)});this.scan(ast.update);this.newContext(()=>{this.scan(ast.body)})});if(testIdentifiers){for(const p in context){if(p==="@contextType")continue;if(testIdentifiers.indexOf(p)>-1){context[p].inForLoopTest=true}}}break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(ast.body);this.scan(ast.test)});break;case"Identifier":{if(this.isState(states.trackIdentifiers)){this.trackedIdentifiers.push(ast.name)}this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(ast.name),ast});break}case"ReturnStatement":this.returnStatements.push(ast);this.scan(ast.argument);break;case"MemberExpression":this.pushState(states.memberExpression);this.scan(ast.object);this.scan(ast.property);this.popState(states.memberExpression);break;case"ExpressionStatement":this.scan(ast.expression);break;case"SequenceExpression":this.scan(ast.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast});this.scan(ast.arguments);break;case"ArrayExpression":this.scan(ast.elements);break;case"ConditionalExpression":this.scan(ast.test);this.scan(ast.alternate);this.scan(ast.consequent);break;case"SwitchStatement":this.scan(ast.discriminant);this.scan(ast.cases);break;case"SwitchCase":this.scan(ast.test);this.scan(ast.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${ast.type}"`)}}}module3.exports={FunctionTracer}},{"../utils":114}],12:[function(require2,module3,exports3){const{glWiretap}=require2("gl-wiretap");const{utils}=require2("../../utils");function toStringWithoutUtils(fn){return fn.toString().replace("=>","").replace(/^function /,"").replace(/utils[.]/g,"/*utils.*/")}function glKernelString(Kernel,args,originKernel,setupContextString,destroyContextString){if(!originKernel.built){originKernel.build.apply(originKernel,args)}args=args?Array.from(args).map(arg=>{switch(typeof arg){case"boolean":return new Boolean(arg);case"number":return new Number(arg);default:return arg}}):null;const uploadedValues=[];const postResult=[];const context=glWiretap(originKernel.context,{useTrackablePrimitives:true,onReadPixels:targetName=>{if(kernel.subKernels){if(!subKernelsResultVariableSetup){postResult.push(` const result = { result: ${getRenderString(targetName,kernel)} };`);subKernelsResultVariableSetup=true}else{const property=kernel.subKernels[subKernelsResultIndex++].property;postResult.push(` result${isNaN(property)?"."+property:`[${property}]`} = ${getRenderString(targetName,kernel)};`)}if(subKernelsResultIndex===kernel.subKernels.length){postResult.push(" return result;")}return}if(targetName){postResult.push(` return ${getRenderString(targetName,kernel)};`)}else{postResult.push(` return null;`)}},onUnrecognizedArgumentLookup:argument=>{const argumentName=findKernelValue(argument,kernel.kernelArguments,[],context,uploadedValues);if(argumentName){return argumentName}const constantName=findKernelValue(argument,kernel.kernelConstants,constants?Object.keys(constants).map(key=>constants[key]):[],context,uploadedValues);if(constantName){return constantName}return null}});let subKernelsResultVariableSetup=false;let subKernelsResultIndex=0;const{source,canvas,output,pipeline,graphical,loopMaxIterations,constants,optimizeFloatMemory,precision,fixIntegerDivisionAccuracy,functions,nativeFunctions,subKernels,immutable,argumentTypes,constantTypes,kernelArguments,kernelConstants,tactic}=originKernel;const kernel=new Kernel(source,{canvas,context,checkContext:false,output,pipeline,graphical,loopMaxIterations,constants,optimizeFloatMemory,precision,fixIntegerDivisionAccuracy,functions,nativeFunctions,subKernels,immutable,argumentTypes,constantTypes,tactic});let result=[];context.setIndent(2);kernel.build.apply(kernel,args);result.push(context.toString());context.reset();kernel.kernelArguments.forEach((kernelArgument,i)=>{switch(kernelArgument.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":context.insertVariable(`uploadValue_${kernelArgument.name}`,kernelArgument.uploadValue);break;case"HTMLImageArray":for(let imageIndex=0;imageIndexkernelArgument.varName).join(", ")}) {`);context.setIndent(4);kernel.run.apply(kernel,args);if(kernel.renderKernels){kernel.renderKernels()}else if(kernel.renderOutput){kernel.renderOutput()}result.push(" /** start setup uploads for kernel values **/");kernel.kernelArguments.forEach(kernelArgument=>{result.push(" "+kernelArgument.getStringValueHandler().split("\n").join("\n "))});result.push(" /** end setup uploads for kernel values **/");result.push(context.toString());if(kernel.renderOutput===kernel.renderTexture){context.reset();const framebufferName=context.getContextVariableName(kernel.framebuffer);if(kernel.renderKernels){const results=kernel.renderKernels();const textureName=context.getContextVariableName(kernel.texture.texture);result.push(` return { - result: { - texture: ${textureName}, - type: '${results.result.type}', - toArray: ${getToArrayString(results.result,textureName,framebufferName)} - },`);const{subKernels:subKernels2,mappedTextures}=kernel;for(let i=0;i{constantsUpload.push(`${kernelConstant.getStringValueHandler()}`)});return`function kernel(settings) { - const { context, constants } = settings; - ${constantsUpload.join("")} - ${setupContextString?setupContextString:""} - ${result.join("\n")} - }`}function getRenderString(targetName,kernel){const readBackValue=kernel.precision==="single"?targetName:`new Float32Array(${targetName}.buffer)`;if(kernel.output[2]){return`renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]}, ${kernel.output[2]})`}if(kernel.output[1]){return`renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]})`}return`renderOutput(${readBackValue}, ${kernel.output[0]})`}function getGetPixelsString(kernel){const getPixels=kernel.getPixels.toString();const useFunctionKeyword=!/^function/.test(getPixels);return utils.flattenFunctionToString(`${useFunctionKeyword?"function ":""}${getPixels}`,{findDependency:(object,name2)=>{if(object==="utils"){return`const ${name2} = ${utils[name2].toString()};`}return null},thisLookup:property=>{if(property==="context"){return null}if(kernel.hasOwnProperty(property)){return JSON.stringify(kernel[property])}throw new Error(`unhandled thisLookup ${property}`)}})}function getToArrayString(kernelResult,textureName,framebufferName){const toArray=kernelResult.toArray.toString();const useFunctionKeyword=!/^function/.test(toArray);const flattenedFunctions=utils.flattenFunctionToString(`${useFunctionKeyword?"function ":""}${toArray}`,{findDependency:(object,name2)=>{if(object==="utils"){return`const ${name2} = ${utils[name2].toString()};`}else if(object==="this"){if(name2==="framebuffer"){return""}return`${useFunctionKeyword?"function ":""}${kernelResult[name2].toString()}`}else{throw new Error("unhandled fromObject")}},thisLookup:(property,isDeclaration)=>{if(property==="texture"){return textureName}if(property==="context"){if(isDeclaration)return null;return"gl"}if(kernelResult.hasOwnProperty(property)){return JSON.stringify(kernelResult[property])}throw new Error(`unhandled thisLookup ${property}`)}});return`() => { - function framebuffer() { return ${framebufferName}; }; - ${flattenedFunctions} - return toArray(); - }`}function findKernelValue(argument,kernelValues,values,context,uploadedValues){if(argument===null)return null;if(kernelValues===null)return null;switch(typeof argument){case"boolean":case"number":return null}if(typeof HTMLImageElement!=="undefined"&&argument instanceof HTMLImageElement){for(let i=0;i0?":"+argumentTypes.join(","):"")}setFixIntegerDivisionAccuracy(fix){this.fixIntegerDivisionAccuracy=fix;return this}setPrecision(flag){this.precision=flag;return this}setFloatTextures(flag){utils.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory");this.floatTextures=flag;return this}static nativeFunctionArguments(source){const argumentTypes=[];const argumentNames=[];const states=[];const isStartingVariableName=/^[a-zA-Z_]/;const isVariableChar=/[a-zA-Z_0-9]/;let i=0;let argumentName=null;let argumentType=null;while(i0?states[states.length-1]:null;if(state2==="FUNCTION_ARGUMENTS"&&char==="/"&&nextChar==="*"){states.push("MULTI_LINE_COMMENT");i+=2;continue}else if(state2==="MULTI_LINE_COMMENT"&&char==="*"&&nextChar==="/"){states.pop();i+=2;continue}else if(state2==="FUNCTION_ARGUMENTS"&&char==="/"&&nextChar==="/"){states.push("COMMENT");i+=2;continue}else if(state2==="COMMENT"&&char==="\n"){states.pop();i++;continue}else if(state2===null&&char==="("){states.push("FUNCTION_ARGUMENTS");i++;continue}else if(state2==="FUNCTION_ARGUMENTS"){if(char===")"){states.pop();break}if(char==="f"&&nextChar==="l"&&source[i+2]==="o"&&source[i+3]==="a"&&source[i+4]==="t"&&source[i+5]===" "){states.push("DECLARE_VARIABLE");argumentType="float";argumentName="";i+=6;continue}else if(char==="i"&&nextChar==="n"&&source[i+2]==="t"&&source[i+3]===" "){states.push("DECLARE_VARIABLE");argumentType="int";argumentName="";i+=4;continue}else if(char==="v"&&nextChar==="e"&&source[i+2]==="c"&&source[i+3]==="2"&&source[i+4]===" "){states.push("DECLARE_VARIABLE");argumentType="vec2";argumentName="";i+=5;continue}else if(char==="v"&&nextChar==="e"&&source[i+2]==="c"&&source[i+3]==="3"&&source[i+4]===" "){states.push("DECLARE_VARIABLE");argumentType="vec3";argumentName="";i+=5;continue}else if(char==="v"&&nextChar==="e"&&source[i+2]==="c"&&source[i+3]==="4"&&source[i+4]===" "){states.push("DECLARE_VARIABLE");argumentType="vec4";argumentName="";i+=5;continue}}else if(state2==="DECLARE_VARIABLE"){if(argumentName===""){if(char===" "){i++;continue}if(!isStartingVariableName.test(char)){throw new Error("variable name is not expected string")}}argumentName+=char;if(!isVariableChar.test(nextChar)){states.pop();argumentNames.push(argumentName);argumentTypes.push(typeMap[argumentType])}}i++}if(states.length>0){throw new Error("GLSL function was not parsable")}return{argumentNames,argumentTypes}}static nativeFunctionReturnType(source){return typeMap[source.match(/int|float|vec[2-4]/)[0]]}static combineKernels(combinedKernel,lastKernel){combinedKernel.apply(null,arguments);const{texSize,context,threadDim}=lastKernel.texSize;let result;if(lastKernel.precision==="single"){const w=texSize[0];const h=Math.ceil(texSize[1]/4);result=new Float32Array(w*h*4*4);context.readPixels(0,0,w,h*4,context.RGBA,context.FLOAT,result)}else{const bytes=new Uint8Array(texSize[0]*texSize[1]*4);context.readPixels(0,0,texSize[0],texSize[1],context.RGBA,context.UNSIGNED_BYTE,bytes);result=new Float32Array(bytes.buffer)}result=result.subarray(0,threadDim[0]*threadDim[1]*threadDim[2]);if(lastKernel.output.length===1){return result}else if(lastKernel.output.length===2){return utils.splitArray(result,lastKernel.output[0])}else if(lastKernel.output.length===3){const cube=utils.splitArray(result,lastKernel.output[0]*lastKernel.output[1]);return cube.map(function(x2){return utils.splitArray(x2,lastKernel.output[0])})}}constructor(source,settings){super(source,settings);this.transferValues=null;this.formatValues=null;this.TextureConstructor=null;this.renderOutput=null;this.renderRawOutput=null;this.texSize=null;this.translatedSource=null;this.compiledFragmentShader=null;this.compiledVertexShader=null;this.switchingKernels=null;this._textureSwitched=null;this._mappedTextureSwitched=null}checkTextureSize(){const{features}=this.constructor;if(this.texSize[0]>features.maxTextureSize||this.texSize[1]>features.maxTextureSize){throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${features.maxTextureSize},${features.maxTextureSize}]`)}}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(args){if(this.graphical){this.renderRawOutput=this.readPackedPixelsToUint8Array;this.transferValues=pixels=>pixels;this.TextureConstructor=GLTextureGraphical;return null}if(this.precision==="unsigned"){this.renderRawOutput=this.readPackedPixelsToUint8Array;this.transferValues=this.readPackedPixelsToFloat32Array;if(this.pipeline){this.renderOutput=this.renderTexture;if(this.subKernels!==null){this.renderKernels=this.renderKernelsToTextures}switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":if(this.output[2]>0){this.TextureConstructor=GLTextureUnsigned3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureUnsigned2D;return null}else{this.TextureConstructor=GLTextureUnsigned;return null}case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(args)}}else{if(this.subKernels!==null){this.renderKernels=this.renderKernelsToArrays}switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":this.renderOutput=this.renderValues;if(this.output[2]>0){this.TextureConstructor=GLTextureUnsigned3D;this.formatValues=utils.erect3DPackedFloat;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureUnsigned2D;this.formatValues=utils.erect2DPackedFloat;return null}else{this.TextureConstructor=GLTextureUnsigned;this.formatValues=utils.erectPackedFloat;return null}case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(args)}}}else if(this.precision==="single"){this.renderRawOutput=this.readFloatPixelsToFloat32Array;this.transferValues=this.readFloatPixelsToFloat32Array;if(this.pipeline){this.renderOutput=this.renderTexture;if(this.subKernels!==null){this.renderKernels=this.renderKernelsToTextures}switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":{if(this.optimizeFloatMemory){if(this.output[2]>0){this.TextureConstructor=GLTextureMemoryOptimized3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureMemoryOptimized2D;return null}else{this.TextureConstructor=GLTextureMemoryOptimized;return null}}else{if(this.output[2]>0){this.TextureConstructor=GLTextureFloat3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureFloat2D;return null}else{this.TextureConstructor=GLTextureFloat;return null}}}case"Array(2)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray2Float3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray2Float2D;return null}else{this.TextureConstructor=GLTextureArray2Float;return null}}case"Array(3)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray3Float3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray3Float2D;return null}else{this.TextureConstructor=GLTextureArray3Float;return null}}case"Array(4)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray4Float3D;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray4Float2D;return null}else{this.TextureConstructor=GLTextureArray4Float;return null}}}}this.renderOutput=this.renderValues;if(this.subKernels!==null){this.renderKernels=this.renderKernelsToArrays}if(this.optimizeFloatMemory){switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":{if(this.output[2]>0){this.TextureConstructor=GLTextureMemoryOptimized3D;this.formatValues=utils.erectMemoryOptimized3DFloat;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureMemoryOptimized2D;this.formatValues=utils.erectMemoryOptimized2DFloat;return null}else{this.TextureConstructor=GLTextureMemoryOptimized;this.formatValues=utils.erectMemoryOptimizedFloat;return null}}case"Array(2)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray2Float3D;this.formatValues=utils.erect3DArray2;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray2Float2D;this.formatValues=utils.erect2DArray2;return null}else{this.TextureConstructor=GLTextureArray2Float;this.formatValues=utils.erectArray2;return null}}case"Array(3)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray3Float3D;this.formatValues=utils.erect3DArray3;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray3Float2D;this.formatValues=utils.erect2DArray3;return null}else{this.TextureConstructor=GLTextureArray3Float;this.formatValues=utils.erectArray3;return null}}case"Array(4)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray4Float3D;this.formatValues=utils.erect3DArray4;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray4Float2D;this.formatValues=utils.erect2DArray4;return null}else{this.TextureConstructor=GLTextureArray4Float;this.formatValues=utils.erectArray4;return null}}}}else{switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":{if(this.output[2]>0){this.TextureConstructor=GLTextureFloat3D;this.formatValues=utils.erect3DFloat;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureFloat2D;this.formatValues=utils.erect2DFloat;return null}else{this.TextureConstructor=GLTextureFloat;this.formatValues=utils.erectFloat;return null}}case"Array(2)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray2Float3D;this.formatValues=utils.erect3DArray2;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray2Float2D;this.formatValues=utils.erect2DArray2;return null}else{this.TextureConstructor=GLTextureArray2Float;this.formatValues=utils.erectArray2;return null}}case"Array(3)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray3Float3D;this.formatValues=utils.erect3DArray3;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray3Float2D;this.formatValues=utils.erect2DArray3;return null}else{this.TextureConstructor=GLTextureArray3Float;this.formatValues=utils.erectArray3;return null}}case"Array(4)":{if(this.output[2]>0){this.TextureConstructor=GLTextureArray4Float3D;this.formatValues=utils.erect3DArray4;return null}else if(this.output[1]>0){this.TextureConstructor=GLTextureArray4Float2D;this.formatValues=utils.erect2DArray4;return null}else{this.TextureConstructor=GLTextureArray4Float;this.formatValues=utils.erectArray4;return null}}}}}else{throw new Error(`unhandled precision of "${this.precision}"`)}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error(`abstract method call`)}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error(`abstract method call`)}getMainResultSubKernelNumberTexture(){throw new Error(`abstract method call`)}getMainResultKernelArray2Texture(){throw new Error(`abstract method call`)}getMainResultSubKernelArray2Texture(){throw new Error(`abstract method call`)}getMainResultKernelArray3Texture(){throw new Error(`abstract method call`)}getMainResultSubKernelArray3Texture(){throw new Error(`abstract method call`)}getMainResultKernelArray4Texture(){throw new Error(`abstract method call`)}getMainResultSubKernelArray4Texture(){throw new Error(`abstract method call`)}getMainResultGraphical(){throw new Error(`abstract method call`)}getMainResultMemoryOptimizedFloats(){throw new Error(`abstract method call`)}getMainResultPackedPixels(){throw new Error(`abstract method call`)}getMainResultString(){if(this.graphical){return this.getMainResultGraphical()}else if(this.precision==="single"){if(this.optimizeFloatMemory){return this.getMainResultMemoryOptimizedFloats()}return this.getMainResultTexture()}else{return this.getMainResultPackedPixels()}}getMainResultNumberTexture(){return utils.linesToString(this.getMainResultKernelNumberTexture())+utils.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return utils.linesToString(this.getMainResultKernelArray2Texture())+utils.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return utils.linesToString(this.getMainResultKernelArray3Texture())+utils.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return utils.linesToString(this.getMainResultKernelArray4Texture())+utils.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){const variablePrecision=this.getVariablePrecisionString(this.texSize,this.tactic);return`precision ${variablePrecision} float; -`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,true)} int; -`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D; -`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray; -`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if(this.precision!=="unsigned")throw new Error('Requires this.precision to be "unsigned"');const{texSize,context:gl}=this;const result=new Uint8Array(texSize[0]*texSize[1]*4);gl.readPixels(0,0,texSize[0],texSize[1],gl.RGBA,gl.UNSIGNED_BYTE,result);return result}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if(this.precision!=="single")throw new Error('Requires this.precision to be "single"');const{texSize,context:gl}=this;const w=texSize[0];const h=texSize[1];const result=new Float32Array(w*h*4);gl.readPixels(0,0,w,h,gl.RGBA,gl.FLOAT,result);return result}getPixels(flip){const{context:gl,output}=this;const[width,height]=output;const pixels=new Uint8Array(width*height*4);gl.readPixels(0,0,width,height,gl.RGBA,gl.UNSIGNED_BYTE,pixels);return new Uint8ClampedArray((flip?pixels:utils.flipPixels(pixels,width,height)).buffer)}renderKernelsToArrays(){const result={result:this.renderOutput()};for(let i=0;i0){for(let i=0;i0){const{mappedTextures}=this;for(let i=0;i1){this.newTexture();return true}return false}cloneTexture(){this.texture._refs--;const{context:gl,size,texture,kernel}=this;if(kernel.debug){console.warn("cloning internal texture")}gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer());selectTexture(gl,texture);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);const target=gl.createTexture();selectTexture(gl,target);gl.texImage2D(gl.TEXTURE_2D,0,this.internalFormat,size[0],size[1],0,this.textureFormat,this.textureType,null);gl.copyTexSubImage2D(gl.TEXTURE_2D,0,0,0,0,0,size[0],size[1]);target._refs=1;this.texture=target}newTexture(){this.texture._refs--;const gl=this.context;const size=this.size;const kernel=this.kernel;if(kernel.debug){console.warn("new internal texture")}const target=gl.createTexture();selectTexture(gl,target);gl.texImage2D(gl.TEXTURE_2D,0,this.internalFormat,size[0],size[1],0,this.textureFormat,this.textureType,null);target._refs=1;this.texture=target}clear(){if(this.texture._refs){this.texture._refs--;const gl2=this.context;const target=this.texture=gl2.createTexture();selectTexture(gl2,target);const size=this.size;target._refs=1;gl2.texImage2D(gl2.TEXTURE_2D,0,this.internalFormat,size[0],size[1],0,this.textureFormat,this.textureType,null)}const{context:gl,texture}=this;gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer());gl.bindTexture(gl.TEXTURE_2D,texture);selectTexture(gl,texture);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT)}delete(){if(this._deleted)return;this._deleted=true;if(this.texture._refs){this.texture._refs--;if(this.texture._refs)return}this.context.deleteTexture(this.texture)}framebuffer(){if(!this._framebuffer){this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])}return this._framebuffer}}function selectTexture(gl,texture){gl.activeTexture(gl.TEXTURE15);gl.bindTexture(gl.TEXTURE_2D,texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST)}module3.exports={GLTexture}},{"../../../texture":113}],28:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureFloat}=require2("./float");class GLTextureMemoryOptimized2D extends GLTextureFloat{constructor(settings){super(settings);this.type="MemoryOptimizedNumberTexture"}toArray(){return utils.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}module3.exports={GLTextureMemoryOptimized2D}},{"../../../utils":114,"./float":25}],29:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureFloat}=require2("./float");class GLTextureMemoryOptimized3D extends GLTextureFloat{constructor(settings){super(settings);this.type="MemoryOptimizedNumberTexture"}toArray(){return utils.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}module3.exports={GLTextureMemoryOptimized3D}},{"../../../utils":114,"./float":25}],30:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureFloat}=require2("./float");class GLTextureMemoryOptimized extends GLTextureFloat{constructor(settings){super(settings);this.type="MemoryOptimizedNumberTexture"}toArray(){return utils.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}module3.exports={GLTextureMemoryOptimized}},{"../../../utils":114,"./float":25}],31:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureUnsigned}=require2("./unsigned");class GLTextureUnsigned2D extends GLTextureUnsigned{constructor(settings){super(settings);this.type="NumberTexture"}toArray(){return utils.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}module3.exports={GLTextureUnsigned2D}},{"../../../utils":114,"./unsigned":33}],32:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTextureUnsigned}=require2("./unsigned");class GLTextureUnsigned3D extends GLTextureUnsigned{constructor(settings){super(settings);this.type="NumberTexture"}toArray(){return utils.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}module3.exports={GLTextureUnsigned3D}},{"../../../utils":114,"./unsigned":33}],33:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{GLTexture}=require2("./index");class GLTextureUnsigned extends GLTexture{get textureType(){return this.context.UNSIGNED_BYTE}constructor(settings){super(settings);this.type="NumberTexture"}renderRawOutput(){const{context:gl}=this;gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer());gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,this.texture,0);const result=new Uint8Array(this.size[0]*this.size[1]*4);gl.readPixels(0,0,this.size[0],this.size[1],gl.RGBA,gl.UNSIGNED_BYTE,result);return result}renderValues(){if(this._deleted)return null;return new Float32Array(this.renderRawOutput().buffer)}toArray(){return utils.erectPackedFloat(this.renderValues(),this.output[0])}}module3.exports={GLTextureUnsigned}},{"../../../utils":114,"./index":27}],34:[function(require2,module3,exports3){const getContext=require2("gl");const{WebGLKernel}=require2("../web-gl/kernel");const{glKernelString}=require2("../gl/kernel-string");let isSupported=null;let testCanvas=null;let testContext=null;let testExtensions=null;let features=null;class HeadlessGLKernel extends WebGLKernel{static get isSupported(){if(isSupported!==null)return isSupported;this.setupFeatureChecks();isSupported=testContext!==null;return isSupported}static setupFeatureChecks(){testCanvas=null;testExtensions=null;if(typeof getContext!=="function")return;try{testContext=getContext(2,2,{preserveDrawingBuffer:true});if(!testContext||!testContext.getExtension)return;testExtensions={STACKGL_resize_drawingbuffer:testContext.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:testContext.getExtension("STACKGL_destroy_context"),OES_texture_float:testContext.getExtension("OES_texture_float"),OES_texture_float_linear:testContext.getExtension("OES_texture_float_linear"),OES_element_index_uint:testContext.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:testContext.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:testContext.getExtension("WEBGL_color_buffer_float")};features=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(context){try{return context.getParameter(context.RENDERER)==="ANGLE"}catch(e){return false}}static getIsTextureFloat(){return Boolean(testExtensions.OES_texture_float)}static getIsDrawBuffers(){return Boolean(testExtensions.WEBGL_draw_buffers)}static getChannelCount(){return testExtensions.WEBGL_draw_buffers?testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return testContext.getParameter(testContext.MAX_TEXTURE_SIZE)}static get testCanvas(){return testCanvas}static get testContext(){return testContext}static get features(){return features}initCanvas(){return{}}initContext(){return getContext(2,2,{preserveDrawingBuffer:true})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments);if(!this.fallbackRequested){this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null;this.extensions.STACKGL_destroy_context=null;this.extensions.OES_texture_float=null;this.extensions.OES_texture_float_linear=null;this.extensions.OES_element_index_uint=null;this.extensions.WEBGL_draw_buffers=null}static destroyContext(context){const extension=context.getExtension("STACKGL_destroy_context");if(extension&&extension.destroy){extension.destroy()}}toString(){const setupContextString=`const gl = context || require('gl')(1, 1); -`;const destroyContextString=` if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); } -`;return glKernelString(this.constructor,arguments,this,setupContextString,destroyContextString)}setOutput(output){super.setOutput(output);if(this.graphical&&this.extensions.STACKGL_resize_drawingbuffer){this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}return this}}module3.exports={HeadlessGLKernel}},{"../gl/kernel-string":12,"../web-gl/kernel":70,"gl":2}],35:[function(require2,module3,exports3){class KernelValue{constructor(value2,settings){const{name:name2,kernel,context,checkContext,onRequestContextHandle,onUpdateValueMismatch,origin,strictIntegers,type,tactic}=settings;if(!name2){throw new Error("name not set")}if(!type){throw new Error("type not set")}if(!origin){throw new Error("origin not set")}if(origin!=="user"&&origin!=="constants"){throw new Error(`origin must be "user" or "constants" value is "${origin}"`)}if(!onRequestContextHandle){throw new Error("onRequestContextHandle is not set")}this.name=name2;this.origin=origin;this.tactic=tactic;this.varName=origin==="constants"?`constants.${name2}`:name2;this.kernel=kernel;this.strictIntegers=strictIntegers;this.type=value2.type||type;this.size=value2.size||null;this.index=null;this.context=context;this.checkContext=checkContext!==null&&checkContext!==void 0?checkContext:true;this.contextHandle=null;this.onRequestContextHandle=onRequestContextHandle;this.onUpdateValueMismatch=onUpdateValueMismatch;this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(value2){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}module3.exports={KernelValue}},{}],36:[function(require2,module3,exports3){const{utils}=require2("../utils");const{Input}=require2("../input");class Kernel{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(context){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(context){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(source,settings){if(typeof source!=="object"){if(typeof source!=="string"){throw new Error("source not a string")}if(!utils.isFunctionString(source)){throw new Error("source not a function string")}}this.useLegacyEncoder=false;this.fallbackRequested=false;this.onRequestFallback=null;this.argumentNames=typeof source==="string"?utils.getArgumentNamesFromString(source):null;this.argumentTypes=null;this.argumentSizes=null;this.argumentBitRatios=null;this.kernelArguments=null;this.kernelConstants=null;this.forceUploadKernelConstants=null;this.source=source;this.output=null;this.debug=false;this.graphical=false;this.loopMaxIterations=0;this.constants=null;this.constantTypes=null;this.constantBitRatios=null;this.dynamicArguments=false;this.dynamicOutput=false;this.canvas=null;this.context=null;this.checkContext=null;this.gpu=null;this.functions=null;this.nativeFunctions=null;this.injectedNative=null;this.subKernels=null;this.validate=true;this.immutable=false;this.pipeline=false;this.precision=null;this.tactic=null;this.plugins=null;this.returnType=null;this.leadingReturnStatement=null;this.followingReturnStatement=null;this.optimizeFloatMemory=null;this.strictIntegers=false;this.fixIntegerDivisionAccuracy=null;this.built=false;this.signature=null}mergeSettings(settings){for(let p in settings){if(!settings.hasOwnProperty(p)||!this.hasOwnProperty(p))continue;switch(p){case"output":if(!Array.isArray(settings.output)){this.setOutput(settings.output);continue}break;case"functions":this.functions=[];for(let i=0;iplugin.name):null,returnType:this.returnType}}}buildSignature(args){const Constructor=this.constructor;this.signature=Constructor.getSignature(this,Constructor.getArgumentTypes(this,args))}static getArgumentTypes(kernel,args){const argumentTypes=new Array(args.length);for(let i=0;isettings.argumentTypes[name2])||[]}else{argumentTypes=settings.argumentTypes||[]}return{name:utils.getFunctionNameFromString(sourceString)||null,source:sourceString,argumentTypes,returnType:settings.returnType||null}}onActivate(previousKernel){}}function splitArgumentTypes(argumentTypesObject){const argumentNames=Object.keys(argumentTypesObject);const argumentTypes=[];for(let i=0;i= 0.0) { - return pow(x, 1.0 / 3.0); - } else { - return -pow(x, 1.0 / 3.0); - } - } - - float cosh(float x) { - return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; - } - - float expm1(float x) { - return pow(${Math.E}, x) - 1.0; - } - - float fround(highp float x) { - return x; - } - - float imul(float v1, float v2) { - return float(int(v1) * int(v2)); - } - - float log10(float x) { - return log2(x) * (1.0 / log2(10.0)); - } - - float log1p(float x) { - return log(1.0 + x); - } - - float _pow(float v1, float v2) { - if (v2 == 0.0) return 1.0; - return pow(v1, v2); - } - - float tanh(float x) { - float e = exp(2.0 * x); - return (e - 1.0) / (e + 1.0); - } - - float trunc(float x) { - if (x >= 0.0) { - return floor(x); - } else { - return ceil(x); - } - } - - vec4 _round(vec4 x) { - return floor(x + 0.5); - } - - float _round(float x) { - return floor(x + 0.5); - } - - const int BIT_COUNT = 32; - int modi(int x, int y) { - return x - y * (x / y); - } - - int bitwiseOr(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseXOR(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseAnd(int a, int b) { - int result = 0; - int n = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 && b > 0)) { - break; - } - } - return result; - } - int bitwiseNot(int a) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if (modi(a, 2) == 0) { - result += n; - } - a = a / 2; - n = n * 2; - } - return result; - } - int bitwiseZeroFillLeftShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n *= 2; - } - - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - int bitwiseSignedRightShift(int num, int shifts) { - return int(floor(float(num) / pow(2.0, float(shifts)))); - } - - int bitwiseZeroFillRightShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n /= 2; - } - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - vec2 integerMod(vec2 x, float y) { - vec2 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec3 integerMod(vec3 x, float y) { - vec3 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec4 integerMod(vec4 x, vec4 y) { - vec4 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - float integerMod(float x, float y) { - float res = floor(mod(x, y)); - return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); - } - - int integerMod(int x, int y) { - return x - (y * int(x / y)); - } - - __DIVIDE_WITH_INTEGER_CHECK__; - - // Here be dragons! - // DO NOT OPTIMIZE THIS CODE - // YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE - // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME - const vec2 MAGIC_VEC = vec2(1.0, -256.0); - const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); - const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 - float decode32(vec4 texel) { - __DECODE32_ENDIANNESS__; - texel *= 255.0; - vec2 gte128; - gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; - gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; - float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); - float res = exp2(_round(exponent)); - texel.b = texel.b - 128.0 * gte128.x; - res = dot(texel, SCALE_FACTOR) * exp2(_round(exponent-23.0)) + res; - res *= gte128.y * -2.0 + 1.0; - return res; - } - - float decode16(vec4 texel, int index) { - int channel = integerMod(index, 2); - if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0; - if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0; - return 0.0; - } - - float decode8(vec4 texel, int index) { - int channel = integerMod(index, 4); - if (channel == 0) return texel.r * 255.0; - if (channel == 1) return texel.g * 255.0; - if (channel == 2) return texel.b * 255.0; - if (channel == 3) return texel.a * 255.0; - return 0.0; - } - - vec4 legacyEncode32(float f) { - float F = abs(f); - float sign = f < 0.0 ? 1.0 : 0.0; - float exponent = floor(log2(F)); - float mantissa = (exp2(-exponent) * F); - // exponent += floor(log2(mantissa)); - vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; - texel.rg = integerMod(texel.rg, 256.0); - texel.b = integerMod(texel.b, 128.0); - texel.a = exponent*0.5 + 63.5; - texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; - texel = floor(texel); - texel *= 0.003921569; // 1/255 - __ENCODE32_ENDIANNESS__; - return texel; - } - - // https://github.com/gpujs/gpu.js/wiki/Encoder-details - vec4 encode32(float value) { - if (value == 0.0) return vec4(0, 0, 0, 0); - - float exponent; - float mantissa; - vec4 result; - float sgn; - - sgn = step(0.0, -value); - value = abs(value); - - exponent = floor(log2(value)); - - mantissa = value*pow(2.0, -exponent)-1.0; - exponent = exponent+127.0; - result = vec4(0,0,0,0); - - result.a = floor(exponent/2.0); - exponent = exponent - result.a*2.0; - result.a = result.a + 128.0*sgn; - - result.b = floor(mantissa * 128.0); - mantissa = mantissa - result.b / 128.0; - result.b = result.b + exponent*128.0; - - result.g = floor(mantissa*32768.0); - mantissa = mantissa - result.g/32768.0; - - result.r = floor(mantissa*8388608.0); - return result/255.0; - } - // Dragons end here - - int index; - ivec3 threadId; - - ivec3 indexTo3D(int idx, ivec3 texDim) { - int z = int(idx / (texDim.x * texDim.y)); - idx -= z * int(texDim.x * texDim.y); - int y = int(idx / texDim.x); - int x = int(integerMod(idx, texDim.x)); - return ivec3(x, y, z); - } - - float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - return decode32(texel); - } - - float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x * 2; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y)); - return decode16(texel, index); - } - - float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x * 4; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y)); - return decode8(texel, index); - } - - float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 4); - index = index / 4; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - if (channel == 0) return texel.r; - if (channel == 1) return texel.g; - if (channel == 2) return texel.b; - if (channel == 3) return texel.a; - return 0.0; - } - - vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - return texture2D(tex, st / vec2(texSize)); - } - - float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return result[0]; - } - - vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec2(result[0], result[1]); - } - - vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int channel = integerMod(index, 2); - index = index / 2; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - if (channel == 0) return vec2(texel.r, texel.g); - if (channel == 1) return vec2(texel.b, texel.a); - return vec2(0.0, 0.0); - } - - vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec3(result[0], result[1], result[2]); - } - - vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); - int vectorIndex = fieldIndex / 4; - int vectorOffset = fieldIndex - vectorIndex * 4; - int readY = vectorIndex / texSize.x; - int readX = vectorIndex - readY * texSize.x; - vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); - - if (vectorOffset == 0) { - return tex1.xyz; - } else if (vectorOffset == 1) { - return tex1.yzw; - } else { - readX++; - if (readX >= texSize.x) { - readX = 0; - readY++; - } - vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize)); - if (vectorOffset == 2) { - return vec3(tex1.z, tex1.w, tex2.x); - } else { - return vec3(tex1.w, tex2.x, tex2.y); - } - } - } - - vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - return getImage2D(tex, texSize, texDim, z, y, x); - } - - vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 2); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture2D(tex, st / vec2(texSize)); - return vec4(texel.r, texel.g, texel.b, texel.a); - } - - vec4 actualColor; - void color(float r, float g, float b, float a) { - actualColor = vec4(r,g,b,a); - } - - void color(float r, float g, float b) { - color(r,g,b,1.0); - } - - void color(sampler2D image) { - actualColor = texture2D(image, vTexCoord); - } - - float modulo(float number, float divisor) { - if (number < 0.0) { - number = abs(number); - if (divisor < 0.0) { - divisor = abs(divisor); - } - return -mod(number, divisor); - } - if (divisor < 0.0) { - divisor = abs(divisor); - } - return mod(number, divisor); - } - - __INJECTED_NATIVE__; - __MAIN_CONSTANTS__; - __MAIN_ARGUMENTS__; - __KERNEL__; - - void main(void) { - index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; - __MAIN_RESULT__; - }`;module3.exports={fragmentShader}},{}],38:[function(require2,module3,exports3){const{utils}=require2("../../utils");const{FunctionNode}=require2("../function-node");class WebGLFunctionNode extends FunctionNode{constructor(source,settings){super(source,settings);if(settings&&settings.hasOwnProperty("fixIntegerDivisionAccuracy")){this.fixIntegerDivisionAccuracy=settings.fixIntegerDivisionAccuracy}}astConditionalExpression(ast,retArr){if(ast.type!=="ConditionalExpression"){throw this.astErrorOutput("Not a conditional expression",ast)}const consequentType=this.getType(ast.consequent);const alternateType=this.getType(ast.alternate);if(consequentType===null&&alternateType===null){retArr.push("if (");this.astGeneric(ast.test,retArr);retArr.push(") {");this.astGeneric(ast.consequent,retArr);retArr.push(";");retArr.push("} else {");this.astGeneric(ast.alternate,retArr);retArr.push(";");retArr.push("}");return retArr}retArr.push("(");this.astGeneric(ast.test,retArr);retArr.push("?");this.astGeneric(ast.consequent,retArr);retArr.push(":");this.astGeneric(ast.alternate,retArr);retArr.push(")");return retArr}astFunction(ast,retArr){if(this.isRootKernel){retArr.push("void")}else{if(!this.returnType){const lastReturn=this.findLastReturn();if(lastReturn){this.returnType=this.getType(ast.body);if(this.returnType==="LiteralInteger"){this.returnType="Number"}}}const{returnType}=this;if(!returnType){retArr.push("void")}else{const type=typeMap[returnType];if(!type){throw new Error(`unknown type ${returnType}`)}retArr.push(type)}}retArr.push(" ");retArr.push(this.name);retArr.push("(");if(!this.isRootKernel){for(let i=0;i0){retArr.push(", ")}let argumentType=this.argumentTypes[this.argumentNames.indexOf(argumentName)];if(!argumentType){throw this.astErrorOutput(`Unknown argument ${argumentName} type`,ast)}if(argumentType==="LiteralInteger"){this.argumentTypes[i]=argumentType="Number"}const type=typeMap[argumentType];if(!type){throw this.astErrorOutput("Unexpected expression",ast)}const name2=utils.sanitizeName(argumentName);if(type==="sampler2D"||type==="sampler2DArray"){retArr.push(`${type} user_${name2},ivec2 user_${name2}Size,ivec3 user_${name2}Dim`)}else{retArr.push(`${type} user_${name2}`)}}}retArr.push(") {\n");for(let i=0;i"||ast.operator==="<"&&ast.right.type==="Literal"){if(!Number.isInteger(ast.right.value)){this.pushState("building-float");this.castValueToFloat(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.astGeneric(ast.right,retArr);this.popState("building-float");break}}this.pushState("building-integer");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.pushState("casting-to-integer");if(ast.right.type==="Literal"){const literalResult=[];this.astGeneric(ast.right,literalResult);const literalType=this.getType(ast.right);if(literalType==="Integer"){retArr.push(literalResult.join(""))}else{throw this.astErrorOutput(`Unhandled binary expression with literal`,ast)}}else{retArr.push("int(");this.astGeneric(ast.right,retArr);retArr.push(")")}this.popState("casting-to-integer");this.popState("building-integer");break;case"Integer & LiteralInteger":this.pushState("building-integer");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castLiteralToInteger(ast.right,retArr);this.popState("building-integer");break;case"Number & Integer":this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castValueToFloat(ast.right,retArr);this.popState("building-float");break;case"Float & LiteralInteger":case"Number & LiteralInteger":this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castLiteralToFloat(ast.right,retArr);this.popState("building-float");break;case"LiteralInteger & Float":case"LiteralInteger & Number":if(this.isState("casting-to-integer")){this.pushState("building-integer");this.castLiteralToInteger(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castValueToInteger(ast.right,retArr);this.popState("building-integer")}else{this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.pushState("casting-to-float");this.astGeneric(ast.right,retArr);this.popState("casting-to-float");this.popState("building-float")}break;case"LiteralInteger & Integer":this.pushState("building-integer");this.castLiteralToInteger(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.astGeneric(ast.right,retArr);this.popState("building-integer");break;case"Boolean & Boolean":this.pushState("building-boolean");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.astGeneric(ast.right,retArr);this.popState("building-boolean");break;case"Float & Integer":this.pushState("building-float");this.astGeneric(ast.left,retArr);retArr.push(operatorMap[ast.operator]||ast.operator);this.castValueToFloat(ast.right,retArr);this.popState("building-float");break;default:throw this.astErrorOutput(`Unhandled binary expression between ${key}`,ast)}retArr.push(")");return retArr}checkAndUpconvertOperator(ast,retArr){const bitwiseResult=this.checkAndUpconvertBitwiseOperators(ast,retArr);if(bitwiseResult){return bitwiseResult}const upconvertableOperators={"%":this.fixIntegerDivisionAccuracy?"integerCorrectionModulo":"modulo","**":"pow"};const foundOperator=upconvertableOperators[ast.operator];if(!foundOperator)return null;retArr.push(foundOperator);retArr.push("(");switch(this.getType(ast.left)){case"Integer":this.castValueToFloat(ast.left,retArr);break;case"LiteralInteger":this.castLiteralToFloat(ast.left,retArr);break;default:this.astGeneric(ast.left,retArr)}retArr.push(",");switch(this.getType(ast.right)){case"Integer":this.castValueToFloat(ast.right,retArr);break;case"LiteralInteger":this.castLiteralToFloat(ast.right,retArr);break;default:this.astGeneric(ast.right,retArr)}retArr.push(")");return retArr}checkAndUpconvertBitwiseOperators(ast,retArr){const upconvertableOperators={"&":"bitwiseAnd","|":"bitwiseOr","^":"bitwiseXOR","<<":"bitwiseZeroFillLeftShift",">>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"};const foundOperator=upconvertableOperators[ast.operator];if(!foundOperator)return null;retArr.push(foundOperator);retArr.push("(");const leftType=this.getType(ast.left);switch(leftType){case"Number":case"Float":this.castValueToInteger(ast.left,retArr);break;case"LiteralInteger":this.castLiteralToInteger(ast.left,retArr);break;default:this.astGeneric(ast.left,retArr)}retArr.push(",");const rightType=this.getType(ast.right);switch(rightType){case"Number":case"Float":this.castValueToInteger(ast.right,retArr);break;case"LiteralInteger":this.castLiteralToInteger(ast.right,retArr);break;default:this.astGeneric(ast.right,retArr)}retArr.push(")");return retArr}checkAndUpconvertBitwiseUnary(ast,retArr){const upconvertableOperators={"~":"bitwiseNot"};const foundOperator=upconvertableOperators[ast.operator];if(!foundOperator)return null;retArr.push(foundOperator);retArr.push("(");switch(this.getType(ast.argument)){case"Number":case"Float":this.castValueToInteger(ast.argument,retArr);break;case"LiteralInteger":this.castLiteralToInteger(ast.argument,retArr);break;default:this.astGeneric(ast.argument,retArr)}retArr.push(")");return retArr}castLiteralToInteger(ast,retArr){this.pushState("casting-to-integer");this.astGeneric(ast,retArr);this.popState("casting-to-integer");return retArr}castLiteralToFloat(ast,retArr){this.pushState("casting-to-float");this.astGeneric(ast,retArr);this.popState("casting-to-float");return retArr}castValueToInteger(ast,retArr){this.pushState("casting-to-integer");retArr.push("int(");this.astGeneric(ast,retArr);retArr.push(")");this.popState("casting-to-integer");return retArr}castValueToFloat(ast,retArr){this.pushState("casting-to-float");retArr.push("float(");this.astGeneric(ast,retArr);retArr.push(")");this.popState("casting-to-float");return retArr}astIdentifierExpression(idtNode,retArr){if(idtNode.type!=="Identifier"){throw this.astErrorOutput("IdentifierExpression - not an Identifier",idtNode)}const type=this.getType(idtNode);const name2=utils.sanitizeName(idtNode.name);if(idtNode.name==="Infinity"){retArr.push("3.402823466e+38")}else if(type==="Boolean"){if(this.argumentNames.indexOf(name2)>-1){retArr.push(`bool(user_${name2})`)}else{retArr.push(`user_${name2}`)}}else{retArr.push(`user_${name2}`)}return retArr}astForStatement(forNode,retArr){if(forNode.type!=="ForStatement"){throw this.astErrorOutput("Invalid for statement",forNode)}const initArr=[];const testArr=[];const updateArr=[];const bodyArr=[];let isSafe=null;if(forNode.init){const{declarations}=forNode.init;if(declarations.length>1){isSafe=false}this.astGeneric(forNode.init,initArr);for(let i=0;i0){retArr.push(initArr.join(""),"\n")}retArr.push(`for (int ${iVariableName}=0;${iVariableName}0){retArr.push(`if (!${testArr.join("")}) break; -`)}retArr.push(bodyArr.join(""));retArr.push(` -${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whileNode,retArr){if(whileNode.type!=="WhileStatement"){throw this.astErrorOutput("Invalid while statement",whileNode)}const iVariableName=this.getInternalVariableName("safeI");retArr.push(`for (int ${iVariableName}=0;${iVariableName}0){declarationSets.push(declarationSet.join(","))}result.push(declarationSets.join(";"));retArr.push(result.join(""));retArr.push(";");return retArr}astIfStatement(ifNode,retArr){retArr.push("if (");this.astGeneric(ifNode.test,retArr);retArr.push(")");if(ifNode.consequent.type==="BlockStatement"){this.astGeneric(ifNode.consequent,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.consequent,retArr);retArr.push("\n}\n")}if(ifNode.alternate){retArr.push("else ");if(ifNode.alternate.type==="BlockStatement"||ifNode.alternate.type==="IfStatement"){this.astGeneric(ifNode.alternate,retArr)}else{retArr.push(" {\n");this.astGeneric(ifNode.alternate,retArr);retArr.push("\n}\n")}}return retArr}astSwitchStatement(ast,retArr){if(ast.type!=="SwitchStatement"){throw this.astErrorOutput("Invalid switch statement",ast)}const{discriminant,cases}=ast;const type=this.getType(discriminant);const varName=`switchDiscriminant${this.astKey(ast,"_")}`;switch(type){case"Float":case"Number":retArr.push(`float ${varName} = `);this.astGeneric(discriminant,retArr);retArr.push(";\n");break;case"Integer":retArr.push(`int ${varName} = `);this.astGeneric(discriminant,retArr);retArr.push(";\n");break}if(cases.length===1&&!cases[0].test){this.astGeneric(cases[0].consequent,retArr);return retArr}let fallingThrough=false;let defaultResult=[];let movingDefaultToEnd=false;let pastFirstIf=false;for(let i=0;ii+1){movingDefaultToEnd=true;this.astGeneric(cases[i].consequent,defaultResult);continue}else{retArr.push(" else {\n")}}else{if(i===0||!pastFirstIf){pastFirstIf=true;retArr.push(`if (${varName} == `)}else{if(fallingThrough){retArr.push(`${varName} == `);fallingThrough=false}else{retArr.push(` else if (${varName} == `)}}if(type==="Integer"){const testType=this.getType(cases[i].test);switch(testType){case"Number":case"Float":this.castValueToInteger(cases[i].test,retArr);break;case"LiteralInteger":this.castLiteralToInteger(cases[i].test,retArr);break}}else if(type==="Float"){const testType=this.getType(cases[i].test);switch(testType){case"LiteralInteger":this.castLiteralToFloat(cases[i].test,retArr);break;case"Integer":this.castValueToFloat(cases[i].test,retArr);break}}else{throw new Error("unhanlded")}if(!cases[i].consequent||cases[i].consequent.length===0){fallingThrough=true;retArr.push(" || ");continue}retArr.push(`) { -`)}this.astGeneric(cases[i].consequent,retArr);retArr.push("\n}")}if(movingDefaultToEnd){retArr.push(" else {");retArr.push(defaultResult.join(""));retArr.push("}")}return retArr}astThisExpression(tNode,retArr){retArr.push("this");return retArr}astMemberExpression(mNode,retArr){const{property,name:name2,signature,origin,type,xProperty,yProperty,zProperty}=this.getMemberExpressionDetails(mNode);switch(signature){case"value.thread.value":case"this.thread.value":if(name2!=="x"&&name2!=="y"&&name2!=="z"){throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",mNode)}retArr.push(`threadId.${name2}`);return retArr;case"this.output.value":if(this.dynamicOutput){switch(name2){case"x":if(this.isState("casting-to-float")){retArr.push("float(uOutputDim.x)")}else{retArr.push("uOutputDim.x")}break;case"y":if(this.isState("casting-to-float")){retArr.push("float(uOutputDim.y)")}else{retArr.push("uOutputDim.y")}break;case"z":if(this.isState("casting-to-float")){retArr.push("float(uOutputDim.z)")}else{retArr.push("uOutputDim.z")}break;default:throw this.astErrorOutput("Unexpected expression",mNode)}}else{switch(name2){case"x":if(this.isState("casting-to-integer")){retArr.push(this.output[0])}else{retArr.push(this.output[0],".0")}break;case"y":if(this.isState("casting-to-integer")){retArr.push(this.output[1])}else{retArr.push(this.output[1],".0")}break;case"z":if(this.isState("casting-to-integer")){retArr.push(this.output[2])}else{retArr.push(this.output[2],".0")}break;default:throw this.astErrorOutput("Unexpected expression",mNode)}}return retArr;case"value":throw this.astErrorOutput("Unexpected expression",mNode);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if(origin==="Math"){retArr.push(Math[name2]);return retArr}const cleanName=utils.sanitizeName(name2);switch(property){case"r":retArr.push(`user_${cleanName}.r`);return retArr;case"g":retArr.push(`user_${cleanName}.g`);return retArr;case"b":retArr.push(`user_${cleanName}.b`);return retArr;case"a":retArr.push(`user_${cleanName}.a`);return retArr}break;case"this.constants.value":if(typeof xProperty==="undefined"){switch(type){case"Array(2)":case"Array(3)":case"Array(4)":retArr.push(`constants_${utils.sanitizeName(name2)}`);return retArr}}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":this.astCallExpression(mNode.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(property));retArr.push("]");return retArr;case"fn()[][]":this.astCallExpression(mNode.object.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(mNode.object.property));retArr.push("]");retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(mNode.property));retArr.push("]");return retArr;case"[][]":this.astArrayExpression(mNode.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(property));retArr.push("]");return retArr;default:throw this.astErrorOutput("Unexpected expression",mNode)}if(mNode.computed===false){switch(type){case"Number":case"Integer":case"Float":case"Boolean":retArr.push(`${origin}_${utils.sanitizeName(name2)}`);return retArr}}const markupName=`${origin}_${utils.sanitizeName(name2)}`;switch(type){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(mNode.object,retArr);retArr.push("[");retArr.push(this.memberExpressionPropertyMarkup(xProperty));retArr.push("]");break;case"HTMLImageArray":retArr.push(`getImage3D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(1)":retArr.push(`getFloatFromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":retArr.push(`getMemoryOptimizedVec2(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(2)":retArr.push(`getVec2FromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":retArr.push(`getMemoryOptimizedVec3(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(3)":retArr.push(`getVec3FromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":retArr.push(`getMemoryOptimizedVec4(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":retArr.push(`getVec4FromSampler2D(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if(this.precision==="single"){retArr.push(`getMemoryOptimized32(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")")}else{const bitRatio=origin==="user"?this.lookupFunctionArgumentBitRatio(this.name,name2):this.constantBitRatios[name2];switch(bitRatio){case 1:retArr.push(`get8(${markupName}, ${markupName}Size, ${markupName}Dim, `);break;case 2:retArr.push(`get16(${markupName}, ${markupName}Size, ${markupName}Dim, `);break;case 4:case 0:retArr.push(`get32(${markupName}, ${markupName}Size, ${markupName}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${bitRatio}`)}this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")")}break;case"MemoryOptimizedNumberTexture":retArr.push(`getMemoryOptimized32(${markupName}, ${markupName}Size, ${markupName}Dim, `);this.memberExpressionXYZ(xProperty,yProperty,zProperty,retArr);retArr.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":retArr.push(`${markupName}[${this.memberExpressionPropertyMarkup(yProperty)}]`);if(yProperty){retArr.push(`[${this.memberExpressionPropertyMarkup(xProperty)}]`)}break;default:throw new Error(`unhandled member expression "${type}"`)}return retArr}astCallExpression(ast,retArr){if(!ast.callee){throw this.astErrorOutput("Unknown CallExpression",ast)}let functionName=null;const isMathFunction=this.isAstMathFunction(ast);if(isMathFunction||ast.callee.object&&ast.callee.object.type==="ThisExpression"){functionName=ast.callee.property.name}else if(ast.callee.type==="SequenceExpression"&&ast.callee.expressions[0].type==="Literal"&&!isNaN(ast.callee.expressions[0].raw)){functionName=ast.callee.expressions[1].property.name}else{functionName=ast.callee.name}if(!functionName){throw this.astErrorOutput(`Unhandled function, couldn't find name`,ast)}switch(functionName){case"pow":functionName="_pow";break;case"round":functionName="_round";break}if(this.calledFunctions.indexOf(functionName)<0){this.calledFunctions.push(functionName)}if(functionName==="random"&&this.plugins&&this.plugins.length>0){for(let i=0;i0){retArr.push(", ")}switch(argumentType){case"Integer":this.castValueToFloat(argument,retArr);break;default:this.astGeneric(argument,retArr);break}}}else{const targetTypes=this.lookupFunctionArgumentTypes(functionName)||[];for(let i=0;i0){retArr.push(", ")}const argumentType=this.getType(argument);if(!targetType){this.triggerImplyArgumentType(functionName,i,argumentType,this);targetType=argumentType}switch(argumentType){case"Boolean":this.astGeneric(argument,retArr);continue;case"Number":case"Float":if(targetType==="Integer"){retArr.push("int(");this.astGeneric(argument,retArr);retArr.push(")");continue}else if(targetType==="Number"||targetType==="Float"){this.astGeneric(argument,retArr);continue}else if(targetType==="LiteralInteger"){this.castLiteralToFloat(argument,retArr);continue}break;case"Integer":if(targetType==="Number"||targetType==="Float"){retArr.push("float(");this.astGeneric(argument,retArr);retArr.push(")");continue}else if(targetType==="Integer"){this.astGeneric(argument,retArr);continue}break;case"LiteralInteger":if(targetType==="Integer"){this.castLiteralToInteger(argument,retArr);continue}else if(targetType==="Number"||targetType==="Float"){this.castLiteralToFloat(argument,retArr);continue}else if(targetType==="LiteralInteger"){this.astGeneric(argument,retArr);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(targetType===argumentType){if(argument.type==="Identifier"){retArr.push(`user_${utils.sanitizeName(argument.name)}`)}else if(argument.type==="ArrayExpression"||argument.type==="MemberExpression"||argument.type==="CallExpression"){this.astGeneric(argument,retArr)}else{throw this.astErrorOutput(`Unhandled argument type ${argument.type}`,ast)}continue}break;case"HTMLCanvas":case"HTMLImage":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(targetType===argumentType){if(argument.type!=="Identifier")throw this.astErrorOutput(`Unhandled argument type ${argument.type}`,ast);this.triggerImplyArgumentBitRatio(this.name,argument.name,functionName,i);const name2=utils.sanitizeName(argument.name);retArr.push(`user_${name2},user_${name2}Size,user_${name2}Dim`);continue}break}throw this.astErrorOutput(`Unhandled argument combination of ${argumentType} and ${targetType} for argument named "${argument.name}"`,ast)}}retArr.push(")");return retArr}astArrayExpression(arrNode,retArr){const returnType=this.getType(arrNode);const arrLen=arrNode.elements.length;switch(returnType){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":retArr.push(`mat${arrLen}(`);break;default:retArr.push(`vec${arrLen}(`)}for(let i=0;i0){retArr.push(", ")}const subNode=arrNode.elements[i];this.astGeneric(subNode,retArr)}retArr.push(")");return retArr}memberExpressionXYZ(x2,y,z,retArr){if(z){retArr.push(this.memberExpressionPropertyMarkup(z),", ")}else{retArr.push("0, ")}if(y){retArr.push(this.memberExpressionPropertyMarkup(y),", ")}else{retArr.push("0, ")}retArr.push(this.memberExpressionPropertyMarkup(x2));return retArr}memberExpressionPropertyMarkup(property){if(!property){throw new Error("Property not set")}const type=this.getType(property);const result=[];switch(type){case"Number":case"Float":this.castValueToInteger(property,result);break;case"LiteralInteger":this.castLiteralToInteger(property,result);break;default:this.astGeneric(property,result)}return result.join("")}}const typeMap={"Array":"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4","Array2D":"sampler2D","Array3D":"sampler2D","Boolean":"bool","Float":"float","Input":"sampler2D","Integer":"int","Number":"float","LiteralInteger":"float","NumberTexture":"sampler2D","MemoryOptimizedNumberTexture":"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D","HTMLVideo":"sampler2D","HTMLCanvas":"sampler2D","HTMLImage":"sampler2D","HTMLImageArray":"sampler2DArray"};const operatorMap={"===":"==","!==":"!="};module3.exports={WebGLFunctionNode}},{"../../utils":114,"../function-node":10}],39:[function(require2,module3,exports3){const{WebGLKernelValueBoolean}=require2("./kernel-value/boolean");const{WebGLKernelValueFloat}=require2("./kernel-value/float");const{WebGLKernelValueInteger}=require2("./kernel-value/integer");const{WebGLKernelValueHTMLImage}=require2("./kernel-value/html-image");const{WebGLKernelValueDynamicHTMLImage}=require2("./kernel-value/dynamic-html-image");const{WebGLKernelValueHTMLVideo}=require2("./kernel-value/html-video");const{WebGLKernelValueDynamicHTMLVideo}=require2("./kernel-value/dynamic-html-video");const{WebGLKernelValueSingleInput}=require2("./kernel-value/single-input");const{WebGLKernelValueDynamicSingleInput}=require2("./kernel-value/dynamic-single-input");const{WebGLKernelValueUnsignedInput}=require2("./kernel-value/unsigned-input");const{WebGLKernelValueDynamicUnsignedInput}=require2("./kernel-value/dynamic-unsigned-input");const{WebGLKernelValueMemoryOptimizedNumberTexture}=require2("./kernel-value/memory-optimized-number-texture");const{WebGLKernelValueDynamicMemoryOptimizedNumberTexture}=require2("./kernel-value/dynamic-memory-optimized-number-texture");const{WebGLKernelValueNumberTexture}=require2("./kernel-value/number-texture");const{WebGLKernelValueDynamicNumberTexture}=require2("./kernel-value/dynamic-number-texture");const{WebGLKernelValueSingleArray}=require2("./kernel-value/single-array");const{WebGLKernelValueDynamicSingleArray}=require2("./kernel-value/dynamic-single-array");const{WebGLKernelValueSingleArray1DI}=require2("./kernel-value/single-array1d-i");const{WebGLKernelValueDynamicSingleArray1DI}=require2("./kernel-value/dynamic-single-array1d-i");const{WebGLKernelValueSingleArray2DI}=require2("./kernel-value/single-array2d-i");const{WebGLKernelValueDynamicSingleArray2DI}=require2("./kernel-value/dynamic-single-array2d-i");const{WebGLKernelValueSingleArray3DI}=require2("./kernel-value/single-array3d-i");const{WebGLKernelValueDynamicSingleArray3DI}=require2("./kernel-value/dynamic-single-array3d-i");const{WebGLKernelValueSingleArray2}=require2("./kernel-value/single-array2");const{WebGLKernelValueSingleArray3}=require2("./kernel-value/single-array3");const{WebGLKernelValueSingleArray4}=require2("./kernel-value/single-array4");const{WebGLKernelValueUnsignedArray}=require2("./kernel-value/unsigned-array");const{WebGLKernelValueDynamicUnsignedArray}=require2("./kernel-value/dynamic-unsigned-array");const kernelValueMaps={unsigned:{dynamic:{"Boolean":WebGLKernelValueBoolean,"Integer":WebGLKernelValueInteger,"Float":WebGLKernelValueFloat,"Array":WebGLKernelValueDynamicUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGLKernelValueDynamicUnsignedInput,"NumberTexture":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGLKernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueDynamicHTMLImage,"HTMLImage":WebGLKernelValueDynamicHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueDynamicHTMLVideo},static:{"Boolean":WebGLKernelValueBoolean,"Float":WebGLKernelValueFloat,"Integer":WebGLKernelValueInteger,"Array":WebGLKernelValueUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGLKernelValueUnsignedInput,"NumberTexture":WebGLKernelValueNumberTexture,"ArrayTexture(1)":WebGLKernelValueNumberTexture,"ArrayTexture(2)":WebGLKernelValueNumberTexture,"ArrayTexture(3)":WebGLKernelValueNumberTexture,"ArrayTexture(4)":WebGLKernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueHTMLImage,"HTMLImage":WebGLKernelValueHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueHTMLVideo}},single:{dynamic:{"Boolean":WebGLKernelValueBoolean,"Integer":WebGLKernelValueInteger,"Float":WebGLKernelValueFloat,"Array":WebGLKernelValueDynamicSingleArray,"Array(2)":WebGLKernelValueSingleArray2,"Array(3)":WebGLKernelValueSingleArray3,"Array(4)":WebGLKernelValueSingleArray4,"Array1D(2)":WebGLKernelValueDynamicSingleArray1DI,"Array1D(3)":WebGLKernelValueDynamicSingleArray1DI,"Array1D(4)":WebGLKernelValueDynamicSingleArray1DI,"Array2D(2)":WebGLKernelValueDynamicSingleArray2DI,"Array2D(3)":WebGLKernelValueDynamicSingleArray2DI,"Array2D(4)":WebGLKernelValueDynamicSingleArray2DI,"Array3D(2)":WebGLKernelValueDynamicSingleArray3DI,"Array3D(3)":WebGLKernelValueDynamicSingleArray3DI,"Array3D(4)":WebGLKernelValueDynamicSingleArray3DI,"Input":WebGLKernelValueDynamicSingleInput,"NumberTexture":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGLKernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGLKernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueDynamicHTMLImage,"HTMLImage":WebGLKernelValueDynamicHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueDynamicHTMLVideo},static:{"Boolean":WebGLKernelValueBoolean,"Float":WebGLKernelValueFloat,"Integer":WebGLKernelValueInteger,"Array":WebGLKernelValueSingleArray,"Array(2)":WebGLKernelValueSingleArray2,"Array(3)":WebGLKernelValueSingleArray3,"Array(4)":WebGLKernelValueSingleArray4,"Array1D(2)":WebGLKernelValueSingleArray1DI,"Array1D(3)":WebGLKernelValueSingleArray1DI,"Array1D(4)":WebGLKernelValueSingleArray1DI,"Array2D(2)":WebGLKernelValueSingleArray2DI,"Array2D(3)":WebGLKernelValueSingleArray2DI,"Array2D(4)":WebGLKernelValueSingleArray2DI,"Array3D(2)":WebGLKernelValueSingleArray3DI,"Array3D(3)":WebGLKernelValueSingleArray3DI,"Array3D(4)":WebGLKernelValueSingleArray3DI,"Input":WebGLKernelValueSingleInput,"NumberTexture":WebGLKernelValueNumberTexture,"ArrayTexture(1)":WebGLKernelValueNumberTexture,"ArrayTexture(2)":WebGLKernelValueNumberTexture,"ArrayTexture(3)":WebGLKernelValueNumberTexture,"ArrayTexture(4)":WebGLKernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGLKernelValueMemoryOptimizedNumberTexture,"HTMLCanvas":WebGLKernelValueHTMLImage,"HTMLImage":WebGLKernelValueHTMLImage,"HTMLImageArray":false,"HTMLVideo":WebGLKernelValueHTMLVideo}}};function lookupKernelValueType(type,dynamic,precision,value2){if(!type){throw new Error("type missing")}if(!dynamic){throw new Error("dynamic missing")}if(!precision){throw new Error("precision missing")}if(value2.type){type=value2.type}const types=kernelValueMaps[precision][dynamic];if(types[type]===false){return null}else if(types[type]===void 0){throw new Error(`Could not find a KernelValue for ${type}`)}return types[type]}module3.exports={lookupKernelValueType,kernelValueMaps}},{"./kernel-value/boolean":41,"./kernel-value/dynamic-html-image":42,"./kernel-value/dynamic-html-video":43,"./kernel-value/dynamic-memory-optimized-number-texture":44,"./kernel-value/dynamic-number-texture":45,"./kernel-value/dynamic-single-array":46,"./kernel-value/dynamic-single-array1d-i":47,"./kernel-value/dynamic-single-array2d-i":48,"./kernel-value/dynamic-single-array3d-i":49,"./kernel-value/dynamic-single-input":50,"./kernel-value/dynamic-unsigned-array":51,"./kernel-value/dynamic-unsigned-input":52,"./kernel-value/float":53,"./kernel-value/html-image":54,"./kernel-value/html-video":55,"./kernel-value/integer":57,"./kernel-value/memory-optimized-number-texture":58,"./kernel-value/number-texture":59,"./kernel-value/single-array":60,"./kernel-value/single-array1d-i":61,"./kernel-value/single-array2":62,"./kernel-value/single-array2d-i":63,"./kernel-value/single-array3":64,"./kernel-value/single-array3d-i":65,"./kernel-value/single-array4":66,"./kernel-value/single-input":67,"./kernel-value/unsigned-array":68,"./kernel-value/unsigned-input":69}],40:[function(require2,module3,exports3){const{WebGLKernelValue}=require2("./index");const{Input}=require2("../../../input");class WebGLKernelArray extends WebGLKernelValue{checkSize(width,height){if(!this.kernel.validate)return;const{maxTextureSize}=this.kernel.constructor.features;if(width>maxTextureSize||height>maxTextureSize){if(width>height){throw new Error(`Argument texture width of ${width} larger than maximum size of ${maxTextureSize} for your GPU`)}else if(widthpluginName===plugin.name);if(usePlugin){pluginsToUse.push(plugin)}}}}return pluginsToUse}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(args){if(!this.validate){this.texSize=utils.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output);return}const{features:features2}=this.constructor;if(this.optimizeFloatMemory===true&&!features2.isTextureFloat){throw new Error("Float textures are not supported")}else if(this.precision==="single"&&!features2.isFloatRead){throw new Error("Single precision not supported")}else if(!this.graphical&&this.precision===null&&features2.isTextureFloat){this.precision=features2.isFloatRead?"single":"unsigned"}if(this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers){throw new Error("could not instantiate draw buffers extension")}if(this.fixIntegerDivisionAccuracy===null){this.fixIntegerDivisionAccuracy=!features2.isIntegerDivisionAccurate}else if(this.fixIntegerDivisionAccuracy&&features2.isIntegerDivisionAccurate){this.fixIntegerDivisionAccuracy=false}this.checkOutput();if(!this.output||this.output.length===0){if(args.length!==1){throw new Error("Auto output only supported for kernels with only one input")}const argType=utils.getVariableType(args[0],this.strictIntegers);switch(argType){case"Array":this.output=utils.getDimensions(argType);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=args[0].output;break;default:throw new Error("Auto output not supported for input type: "+argType)}}if(this.graphical){if(this.output.length!==2){throw new Error("Output must have 2 dimensions on graphical mode")}if(this.precision==="precision"){this.precision="unsigned";console.warn("Cannot use graphical mode and single precision at the same time")}this.texSize=utils.clone(this.output);return}else if(this.precision===null&&features2.isTextureFloat){this.precision="single"}this.texSize=utils.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output);this.checkTextureSize()}updateMaxTexSize(){const{texSize,canvas}=this;if(this.maxTexSize===null){let canvasIndex=canvases.indexOf(canvas);if(canvasIndex===-1){canvasIndex=canvases.length;canvases.push(canvas);maxTexSizes[canvasIndex]=[texSize[0],texSize[1]]}this.maxTexSize=maxTexSizes[canvasIndex]}if(this.maxTexSize[0]this.argumentNames.length){throw new Error("too many arguments for kernel")}const{context:gl}=this;let textureIndexes=0;const onRequestTexture=()=>{return this.createTexture()};const onRequestIndex=()=>{return this.constantTextureCount+textureIndexes++};const onUpdateValueMismatch=constructor=>{this.switchKernels({type:"argumentMismatch",needed:constructor})};const onRequestContextHandle=()=>{return gl.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++};for(let index=0;index{return this.createTexture()},onRequestIndex:()=>{return textureIndexes++},onRequestContextHandle:()=>{return gl.TEXTURE0+this.constantTextureCount++}});this.constantBitRatios[name2]=kernelValue.bitRatio;this.kernelConstants.push(kernelValue);kernelValue.setup();if(kernelValue.forceUploadEachRun){this.forceUploadKernelConstants.push(kernelValue)}}}build(){if(this.built)return;this.initExtensions();this.validateSettings(arguments);this.setupConstants(arguments);if(this.fallbackRequested)return;this.setupArguments(arguments);if(this.fallbackRequested)return;this.updateMaxTexSize();this.translateSource();const failureResult=this.pickRenderStrategy(arguments);if(failureResult){return failureResult}const{texSize,context:gl,canvas}=this;gl.enable(gl.SCISSOR_TEST);if(this.pipeline&&this.precision==="single"){gl.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]);canvas.width=this.maxTexSize[0];canvas.height=this.maxTexSize[1]}else{gl.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]);canvas.width=this.maxTexSize[0];canvas.height=this.maxTexSize[1]}const threadDim=this.threadDim=Array.from(this.output);while(threadDim.length<3){threadDim.push(1)}const compiledVertexShader=this.getVertexShader(arguments);const vertShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertShader,compiledVertexShader);gl.compileShader(vertShader);this.vertShader=vertShader;const compiledFragmentShader=this.getFragmentShader(arguments);const fragShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragShader,compiledFragmentShader);gl.compileShader(fragShader);this.fragShader=fragShader;if(this.debug){console.log("GLSL Shader Output:");console.log(compiledFragmentShader)}if(!gl.getShaderParameter(vertShader,gl.COMPILE_STATUS)){throw new Error("Error compiling vertex shader: "+gl.getShaderInfoLog(vertShader))}if(!gl.getShaderParameter(fragShader,gl.COMPILE_STATUS)){throw new Error("Error compiling fragment shader: "+gl.getShaderInfoLog(fragShader))}const program=this.program=gl.createProgram();gl.attachShader(program,vertShader);gl.attachShader(program,fragShader);gl.linkProgram(program);this.framebuffer=gl.createFramebuffer();this.framebuffer.width=texSize[0];this.framebuffer.height=texSize[1];this.rawValueFramebuffers={};const vertices=new Float32Array([-1,-1,1,-1,-1,1,1,1]);const texCoords=new Float32Array([0,0,1,0,0,1,1,1]);const texCoordOffset=vertices.byteLength;let buffer=this.buffer;if(!buffer){buffer=this.buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,vertices.byteLength+texCoords.byteLength,gl.STATIC_DRAW)}else{gl.bindBuffer(gl.ARRAY_BUFFER,buffer)}gl.bufferSubData(gl.ARRAY_BUFFER,0,vertices);gl.bufferSubData(gl.ARRAY_BUFFER,texCoordOffset,texCoords);const aPosLoc=gl.getAttribLocation(this.program,"aPos");gl.enableVertexAttribArray(aPosLoc);gl.vertexAttribPointer(aPosLoc,2,gl.FLOAT,false,0,0);const aTexCoordLoc=gl.getAttribLocation(this.program,"aTexCoord");gl.enableVertexAttribArray(aTexCoordLoc);gl.vertexAttribPointer(aTexCoordLoc,2,gl.FLOAT,false,0,texCoordOffset);gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer);let i=0;gl.useProgram(this.program);for(let p in this.constants){this.kernelConstants[i++].updateValue(this.constants[p])}this._setupOutputTexture();if(this.subKernels!==null&&this.subKernels.length>0){this._mappedTextureSwitched={};this._setupSubOutputTextures()}this.buildSignature(arguments);this.built=true}translateSource(){const functionBuilder=FunctionBuilder.fromKernel(this,WebGLFunctionNode,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=functionBuilder.getPrototypeString("kernel");this.setupReturnTypes(functionBuilder)}setupReturnTypes(functionBuilder){if(!this.graphical&&!this.returnType){this.returnType=functionBuilder.getKernelResultType()}if(this.subKernels&&this.subKernels.length>0){for(let i=0;iplugin.source&&this.source.match(plugin.functionMatch)?plugin.source:"").join("\n")}_getConstantsString(){const result=[];const{threadDim,texSize}=this;if(this.dynamicOutput){result.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize")}else{result.push(`ivec3 uOutputDim = ivec3(${threadDim[0]}, ${threadDim[1]}, ${threadDim[2]})`,`ivec2 uTexSize = ivec2(${texSize[0]}, ${texSize[1]})`)}return utils.linesToString(result)}_getTextureCoordinate(){const subKernels=this.subKernels;if(subKernels===null||subKernels.length<1){return"varying vec2 vTexCoord;\n"}else{return"out vec2 vTexCoord;\n"}}_getDecode32EndiannessString(){return this.endianness==="LE"?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return this.endianness==="LE"?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?`float divWithIntCheck(float x, float y) { - if (floor(x) == x && floor(y) == y && integerMod(x, y) == 0.0) { - return float(int(x) / int(y)); - } - return x / y; - } - - float integerCorrectionModulo(float number, float divisor) { - if (number < 0.0) { - number = abs(number); - if (divisor < 0.0) { - divisor = abs(divisor); - } - return -(number - (divisor * floor(divWithIntCheck(number, divisor)))); - } - if (divisor < 0.0) { - divisor = abs(divisor); - } - return number - (divisor * floor(divWithIntCheck(number, divisor))); - }`:""}_getMainArgumentsString(args){const results=[];const{argumentNames}=this;for(let i=0;i{if(map.hasOwnProperty(artifact)){return map[artifact]}throw`unhandled artifact ${artifact}`})}getFragmentShader(args){if(this.compiledFragmentShader!==null){return this.compiledFragmentShader}return this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(args))}getVertexShader(args){if(this.compiledVertexShader!==null){return this.compiledVertexShader}return this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(args))}toString(){const setupContextString=utils.linesToString([`const gl = context`]);return glKernelString(this.constructor,arguments,this,setupContextString)}destroy(removeCanvasReferences){if(!this.context)return;if(this.buffer){this.context.deleteBuffer(this.buffer)}if(this.framebuffer){this.context.deleteFramebuffer(this.framebuffer)}for(const width in this.rawValueFramebuffers){for(const height in this.rawValueFramebuffers[width]){this.context.deleteFramebuffer(this.rawValueFramebuffers[width][height]);delete this.rawValueFramebuffers[width][height]}delete this.rawValueFramebuffers[width]}if(this.vertShader){this.context.deleteShader(this.vertShader)}if(this.fragShader){this.context.deleteShader(this.fragShader)}if(this.program){this.context.deleteProgram(this.program)}if(this.texture){this.texture.delete();const textureCacheIndex=this.textureCache.indexOf(this.texture.texture);if(textureCacheIndex>-1){this.textureCache.splice(textureCacheIndex,1)}this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let i2=0;i2-1){this.textureCache.splice(textureCacheIndex,1)}}this.mappedTextures=null}if(this.kernelArguments){for(let i2=0;i20){const texture=this.textureCache.pop();this.context.deleteTexture(texture)}if(removeCanvasReferences){const idx=canvases.indexOf(this.canvas);if(idx>=0){canvases[idx]=null;maxTexSizes[idx]=null}}this.destroyExtensions();delete this.context;delete this.canvas;if(!this.gpu)return;const i=this.gpu.kernels.indexOf(this);if(i===-1)return;this.gpu.kernels.splice(i,1)}destroyExtensions(){this.extensions.OES_texture_float=null;this.extensions.OES_texture_float_linear=null;this.extensions.OES_element_index_uint=null;this.extensions.WEBGL_draw_buffers=null}static destroyContext(context){const extension=context.getExtension("WEBGL_lose_context");if(extension){extension.loseContext()}}toJSON(){const json=super.toJSON();json.functionNodes=FunctionBuilder.fromKernel(this,WebGLFunctionNode).toJSON();json.settings.threadDim=this.threadDim;return json}}module3.exports={WebGLKernel}},{"../../plugins/math-random-uniformly-distributed":112,"../../utils":114,"../function-builder":9,"../gl/kernel":13,"../gl/kernel-string":12,"./fragment-shader":37,"./function-node":38,"./kernel-value-maps":39,"./vertex-shader":71}],71:[function(require2,module3,exports3){const vertexShader=`__FLOAT_TACTIC_DECLARATION__; - __INT_TACTIC_DECLARATION__; - __SAMPLER_2D_TACTIC_DECLARATION__; - - attribute vec2 aPos; - attribute vec2 aTexCoord; - - varying vec2 vTexCoord; - uniform vec2 ratio; - - void main(void) { - gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); - vTexCoord = aTexCoord; - }`;module3.exports={vertexShader}},{}],72:[function(require2,module3,exports3){const fragmentShader=`#version 300 es - __HEADER__; - __FLOAT_TACTIC_DECLARATION__; - __INT_TACTIC_DECLARATION__; - __SAMPLER_2D_TACTIC_DECLARATION__; - __SAMPLER_2D_ARRAY_TACTIC_DECLARATION__; - - const int LOOP_MAX = __LOOP_MAX__; - - __PLUGINS__; - __CONSTANTS__; - - in vec2 vTexCoord; - - float atan2(float v1, float v2) { - if (v1 == 0.0 || v2 == 0.0) return 0.0; - return atan(v1 / v2); - } - - float cbrt(float x) { - if (x >= 0.0) { - return pow(x, 1.0 / 3.0); - } else { - return -pow(x, 1.0 / 3.0); - } - } - - float expm1(float x) { - return pow(${Math.E}, x) - 1.0; - } - - float fround(highp float x) { - return x; - } - - float imul(float v1, float v2) { - return float(int(v1) * int(v2)); - } - - float log10(float x) { - return log2(x) * (1.0 / log2(10.0)); - } - - float log1p(float x) { - return log(1.0 + x); - } - - float _pow(float v1, float v2) { - if (v2 == 0.0) return 1.0; - return pow(v1, v2); - } - - float _round(float x) { - return floor(x + 0.5); - } - - - const int BIT_COUNT = 32; - int modi(int x, int y) { - return x - y * (x / y); - } - - int bitwiseOr(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseXOR(int a, int b) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 || b > 0)) { - break; - } - } - return result; - } - int bitwiseAnd(int a, int b) { - int result = 0; - int n = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { - result += n; - } - a = a / 2; - b = b / 2; - n = n * 2; - if(!(a > 0 && b > 0)) { - break; - } - } - return result; - } - int bitwiseNot(int a) { - int result = 0; - int n = 1; - - for (int i = 0; i < BIT_COUNT; i++) { - if (modi(a, 2) == 0) { - result += n; - } - a = a / 2; - n = n * 2; - } - return result; - } - int bitwiseZeroFillLeftShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n *= 2; - } - - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - int bitwiseSignedRightShift(int num, int shifts) { - return int(floor(float(num) / pow(2.0, float(shifts)))); - } - - int bitwiseZeroFillRightShift(int n, int shift) { - int maxBytes = BIT_COUNT; - for (int i = 0; i < BIT_COUNT; i++) { - if (maxBytes >= n) { - break; - } - maxBytes *= 2; - } - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= shift) { - break; - } - n /= 2; - } - int result = 0; - int byteVal = 1; - for (int i = 0; i < BIT_COUNT; i++) { - if (i >= maxBytes) break; - if (modi(n, 2) > 0) { result += byteVal; } - n = int(n / 2); - byteVal *= 2; - } - return result; - } - - vec2 integerMod(vec2 x, float y) { - vec2 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec3 integerMod(vec3 x, float y) { - vec3 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - vec4 integerMod(vec4 x, vec4 y) { - vec4 res = floor(mod(x, y)); - return res * step(1.0 - floor(y), -res); - } - - float integerMod(float x, float y) { - float res = floor(mod(x, y)); - return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); - } - - int integerMod(int x, int y) { - return x - (y * int(x/y)); - } - - __DIVIDE_WITH_INTEGER_CHECK__; - - // Here be dragons! - // DO NOT OPTIMIZE THIS CODE - // YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE - // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME - const vec2 MAGIC_VEC = vec2(1.0, -256.0); - const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); - const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 - float decode32(vec4 texel) { - __DECODE32_ENDIANNESS__; - texel *= 255.0; - vec2 gte128; - gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; - gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; - float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); - float res = exp2(round(exponent)); - texel.b = texel.b - 128.0 * gte128.x; - res = dot(texel, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res; - res *= gte128.y * -2.0 + 1.0; - return res; - } - - float decode16(vec4 texel, int index) { - int channel = integerMod(index, 2); - return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0; - } - - float decode8(vec4 texel, int index) { - int channel = integerMod(index, 4); - return texel[channel] * 255.0; - } - - vec4 legacyEncode32(float f) { - float F = abs(f); - float sign = f < 0.0 ? 1.0 : 0.0; - float exponent = floor(log2(F)); - float mantissa = (exp2(-exponent) * F); - // exponent += floor(log2(mantissa)); - vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; - texel.rg = integerMod(texel.rg, 256.0); - texel.b = integerMod(texel.b, 128.0); - texel.a = exponent*0.5 + 63.5; - texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; - texel = floor(texel); - texel *= 0.003921569; // 1/255 - __ENCODE32_ENDIANNESS__; - return texel; - } - - // https://github.com/gpujs/gpu.js/wiki/Encoder-details - vec4 encode32(float value) { - if (value == 0.0) return vec4(0, 0, 0, 0); - - float exponent; - float mantissa; - vec4 result; - float sgn; - - sgn = step(0.0, -value); - value = abs(value); - - exponent = floor(log2(value)); - - mantissa = value*pow(2.0, -exponent)-1.0; - exponent = exponent+127.0; - result = vec4(0,0,0,0); - - result.a = floor(exponent/2.0); - exponent = exponent - result.a*2.0; - result.a = result.a + 128.0*sgn; - - result.b = floor(mantissa * 128.0); - mantissa = mantissa - result.b / 128.0; - result.b = result.b + exponent*128.0; - - result.g = floor(mantissa*32768.0); - mantissa = mantissa - result.g/32768.0; - - result.r = floor(mantissa*8388608.0); - return result/255.0; - } - // Dragons end here - - int index; - ivec3 threadId; - - ivec3 indexTo3D(int idx, ivec3 texDim) { - int z = int(idx / (texDim.x * texDim.y)); - idx -= z * int(texDim.x * texDim.y); - int y = int(idx / texDim.x); - int x = int(integerMod(idx, texDim.x)); - return ivec3(x, y, z); - } - - float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize)); - return decode32(texel); - } - - float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int w = texSize.x * 2; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y)); - return decode16(texel, index); - } - - float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int w = texSize.x * 4; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y)); - return decode8(texel, index); - } - - float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + (texDim.x * (y + (texDim.y * z))); - int channel = integerMod(index, 4); - index = index / 4; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - index = index / 4; - vec4 texel = texture(tex, st / vec2(texSize)); - return texel[channel]; - } - - vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - return texture(tex, st / vec2(texSize)); - } - - vec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - return texture(tex, vec3(st / vec2(texSize), z)); - } - - float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return result[0]; - } - - vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec2(result[0], result[1]); - } - - vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 2); - index = index / 2; - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize)); - if (channel == 0) return vec2(texel.r, texel.g); - if (channel == 1) return vec2(texel.b, texel.a); - return vec2(0.0, 0.0); - } - - vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - vec4 result = getImage2D(tex, texSize, texDim, z, y, x); - return vec3(result[0], result[1], result[2]); - } - - vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); - int vectorIndex = fieldIndex / 4; - int vectorOffset = fieldIndex - vectorIndex * 4; - int readY = vectorIndex / texSize.x; - int readX = vectorIndex - readY * texSize.x; - vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); - - if (vectorOffset == 0) { - return tex1.xyz; - } else if (vectorOffset == 1) { - return tex1.yzw; - } else { - readX++; - if (readX >= texSize.x) { - readX = 0; - readY++; - } - vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize)); - if (vectorOffset == 2) { - return vec3(tex1.z, tex1.w, tex2.x); - } else { - return vec3(tex1.w, tex2.x, tex2.y); - } - } - } - - vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - return getImage2D(tex, texSize, texDim, z, y, x); - } - - vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { - int index = x + texDim.x * (y + texDim.y * z); - int channel = integerMod(index, 2); - int w = texSize.x; - vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; - vec4 texel = texture(tex, st / vec2(texSize)); - return vec4(texel.r, texel.g, texel.b, texel.a); - } - - vec4 actualColor; - void color(float r, float g, float b, float a) { - actualColor = vec4(r,g,b,a); - } - - void color(float r, float g, float b) { - color(r,g,b,1.0); - } - - float modulo(float number, float divisor) { - if (number < 0.0) { - number = abs(number); - if (divisor < 0.0) { - divisor = abs(divisor); - } - return -mod(number, divisor); - } - if (divisor < 0.0) { - divisor = abs(divisor); - } - return mod(number, divisor); - } - - __INJECTED_NATIVE__; - __MAIN_CONSTANTS__; - __MAIN_ARGUMENTS__; - __KERNEL__; - - void main(void) { - index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; - __MAIN_RESULT__; - }`;module3.exports={fragmentShader}},{}],73:[function(require2,module3,exports3){const{utils}=require2("../../utils");const{WebGLFunctionNode}=require2("../web-gl/function-node");class WebGL2FunctionNode extends WebGLFunctionNode{astIdentifierExpression(idtNode,retArr){if(idtNode.type!=="Identifier"){throw this.astErrorOutput("IdentifierExpression - not an Identifier",idtNode)}const type=this.getType(idtNode);const name2=utils.sanitizeName(idtNode.name);if(idtNode.name==="Infinity"){retArr.push("intBitsToFloat(2139095039)")}else if(type==="Boolean"){if(this.argumentNames.indexOf(name2)>-1){retArr.push(`bool(user_${name2})`)}else{retArr.push(`user_${name2}`)}}else{retArr.push(`user_${name2}`)}return retArr}}module3.exports={WebGL2FunctionNode}},{"../../utils":114,"../web-gl/function-node":38}],74:[function(require2,module3,exports3){const{WebGL2KernelValueBoolean}=require2("./kernel-value/boolean");const{WebGL2KernelValueFloat}=require2("./kernel-value/float");const{WebGL2KernelValueInteger}=require2("./kernel-value/integer");const{WebGL2KernelValueHTMLImage}=require2("./kernel-value/html-image");const{WebGL2KernelValueDynamicHTMLImage}=require2("./kernel-value/dynamic-html-image");const{WebGL2KernelValueHTMLImageArray}=require2("./kernel-value/html-image-array");const{WebGL2KernelValueDynamicHTMLImageArray}=require2("./kernel-value/dynamic-html-image-array");const{WebGL2KernelValueHTMLVideo}=require2("./kernel-value/html-video");const{WebGL2KernelValueDynamicHTMLVideo}=require2("./kernel-value/dynamic-html-video");const{WebGL2KernelValueSingleInput}=require2("./kernel-value/single-input");const{WebGL2KernelValueDynamicSingleInput}=require2("./kernel-value/dynamic-single-input");const{WebGL2KernelValueUnsignedInput}=require2("./kernel-value/unsigned-input");const{WebGL2KernelValueDynamicUnsignedInput}=require2("./kernel-value/dynamic-unsigned-input");const{WebGL2KernelValueMemoryOptimizedNumberTexture}=require2("./kernel-value/memory-optimized-number-texture");const{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture}=require2("./kernel-value/dynamic-memory-optimized-number-texture");const{WebGL2KernelValueNumberTexture}=require2("./kernel-value/number-texture");const{WebGL2KernelValueDynamicNumberTexture}=require2("./kernel-value/dynamic-number-texture");const{WebGL2KernelValueSingleArray}=require2("./kernel-value/single-array");const{WebGL2KernelValueDynamicSingleArray}=require2("./kernel-value/dynamic-single-array");const{WebGL2KernelValueSingleArray1DI}=require2("./kernel-value/single-array1d-i");const{WebGL2KernelValueDynamicSingleArray1DI}=require2("./kernel-value/dynamic-single-array1d-i");const{WebGL2KernelValueSingleArray2DI}=require2("./kernel-value/single-array2d-i");const{WebGL2KernelValueDynamicSingleArray2DI}=require2("./kernel-value/dynamic-single-array2d-i");const{WebGL2KernelValueSingleArray3DI}=require2("./kernel-value/single-array3d-i");const{WebGL2KernelValueDynamicSingleArray3DI}=require2("./kernel-value/dynamic-single-array3d-i");const{WebGL2KernelValueSingleArray2}=require2("./kernel-value/single-array2");const{WebGL2KernelValueSingleArray3}=require2("./kernel-value/single-array3");const{WebGL2KernelValueSingleArray4}=require2("./kernel-value/single-array4");const{WebGL2KernelValueUnsignedArray}=require2("./kernel-value/unsigned-array");const{WebGL2KernelValueDynamicUnsignedArray}=require2("./kernel-value/dynamic-unsigned-array");const kernelValueMaps={unsigned:{dynamic:{"Boolean":WebGL2KernelValueBoolean,"Integer":WebGL2KernelValueInteger,"Float":WebGL2KernelValueFloat,"Array":WebGL2KernelValueDynamicUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGL2KernelValueDynamicUnsignedInput,"NumberTexture":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGL2KernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueDynamicHTMLImage,"HTMLImage":WebGL2KernelValueDynamicHTMLImage,"HTMLImageArray":WebGL2KernelValueDynamicHTMLImageArray,"HTMLVideo":WebGL2KernelValueDynamicHTMLVideo},static:{"Boolean":WebGL2KernelValueBoolean,"Float":WebGL2KernelValueFloat,"Integer":WebGL2KernelValueInteger,"Array":WebGL2KernelValueUnsignedArray,"Array(2)":false,"Array(3)":false,"Array(4)":false,"Array1D(2)":false,"Array1D(3)":false,"Array1D(4)":false,"Array2D(2)":false,"Array2D(3)":false,"Array2D(4)":false,"Array3D(2)":false,"Array3D(3)":false,"Array3D(4)":false,"Input":WebGL2KernelValueUnsignedInput,"NumberTexture":WebGL2KernelValueNumberTexture,"ArrayTexture(1)":WebGL2KernelValueNumberTexture,"ArrayTexture(2)":WebGL2KernelValueNumberTexture,"ArrayTexture(3)":WebGL2KernelValueNumberTexture,"ArrayTexture(4)":WebGL2KernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueHTMLImage,"HTMLImage":WebGL2KernelValueHTMLImage,"HTMLImageArray":WebGL2KernelValueHTMLImageArray,"HTMLVideo":WebGL2KernelValueHTMLVideo}},single:{dynamic:{"Boolean":WebGL2KernelValueBoolean,"Integer":WebGL2KernelValueInteger,"Float":WebGL2KernelValueFloat,"Array":WebGL2KernelValueDynamicSingleArray,"Array(2)":WebGL2KernelValueSingleArray2,"Array(3)":WebGL2KernelValueSingleArray3,"Array(4)":WebGL2KernelValueSingleArray4,"Array1D(2)":WebGL2KernelValueDynamicSingleArray1DI,"Array1D(3)":WebGL2KernelValueDynamicSingleArray1DI,"Array1D(4)":WebGL2KernelValueDynamicSingleArray1DI,"Array2D(2)":WebGL2KernelValueDynamicSingleArray2DI,"Array2D(3)":WebGL2KernelValueDynamicSingleArray2DI,"Array2D(4)":WebGL2KernelValueDynamicSingleArray2DI,"Array3D(2)":WebGL2KernelValueDynamicSingleArray3DI,"Array3D(3)":WebGL2KernelValueDynamicSingleArray3DI,"Array3D(4)":WebGL2KernelValueDynamicSingleArray3DI,"Input":WebGL2KernelValueDynamicSingleInput,"NumberTexture":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(1)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(2)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(3)":WebGL2KernelValueDynamicNumberTexture,"ArrayTexture(4)":WebGL2KernelValueDynamicNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueDynamicMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueDynamicHTMLImage,"HTMLImage":WebGL2KernelValueDynamicHTMLImage,"HTMLImageArray":WebGL2KernelValueDynamicHTMLImageArray,"HTMLVideo":WebGL2KernelValueDynamicHTMLVideo},static:{"Boolean":WebGL2KernelValueBoolean,"Float":WebGL2KernelValueFloat,"Integer":WebGL2KernelValueInteger,"Array":WebGL2KernelValueSingleArray,"Array(2)":WebGL2KernelValueSingleArray2,"Array(3)":WebGL2KernelValueSingleArray3,"Array(4)":WebGL2KernelValueSingleArray4,"Array1D(2)":WebGL2KernelValueSingleArray1DI,"Array1D(3)":WebGL2KernelValueSingleArray1DI,"Array1D(4)":WebGL2KernelValueSingleArray1DI,"Array2D(2)":WebGL2KernelValueSingleArray2DI,"Array2D(3)":WebGL2KernelValueSingleArray2DI,"Array2D(4)":WebGL2KernelValueSingleArray2DI,"Array3D(2)":WebGL2KernelValueSingleArray3DI,"Array3D(3)":WebGL2KernelValueSingleArray3DI,"Array3D(4)":WebGL2KernelValueSingleArray3DI,"Input":WebGL2KernelValueSingleInput,"NumberTexture":WebGL2KernelValueNumberTexture,"ArrayTexture(1)":WebGL2KernelValueNumberTexture,"ArrayTexture(2)":WebGL2KernelValueNumberTexture,"ArrayTexture(3)":WebGL2KernelValueNumberTexture,"ArrayTexture(4)":WebGL2KernelValueNumberTexture,"MemoryOptimizedNumberTexture":WebGL2KernelValueMemoryOptimizedNumberTexture,"HTMLCanvas":WebGL2KernelValueHTMLImage,"HTMLImage":WebGL2KernelValueHTMLImage,"HTMLImageArray":WebGL2KernelValueHTMLImageArray,"HTMLVideo":WebGL2KernelValueHTMLVideo}}};function lookupKernelValueType(type,dynamic,precision,value2){if(!type){throw new Error("type missing")}if(!dynamic){throw new Error("dynamic missing")}if(!precision){throw new Error("precision missing")}if(value2.type){type=value2.type}const types=kernelValueMaps[precision][dynamic];if(types[type]===false){return null}else if(types[type]===void 0){throw new Error(`Could not find a KernelValue for ${type}`)}return types[type]}module3.exports={kernelValueMaps,lookupKernelValueType}},{"./kernel-value/boolean":75,"./kernel-value/dynamic-html-image":77,"./kernel-value/dynamic-html-image-array":76,"./kernel-value/dynamic-html-video":78,"./kernel-value/dynamic-memory-optimized-number-texture":79,"./kernel-value/dynamic-number-texture":80,"./kernel-value/dynamic-single-array":81,"./kernel-value/dynamic-single-array1d-i":82,"./kernel-value/dynamic-single-array2d-i":83,"./kernel-value/dynamic-single-array3d-i":84,"./kernel-value/dynamic-single-input":85,"./kernel-value/dynamic-unsigned-array":86,"./kernel-value/dynamic-unsigned-input":87,"./kernel-value/float":88,"./kernel-value/html-image":90,"./kernel-value/html-image-array":89,"./kernel-value/html-video":91,"./kernel-value/integer":92,"./kernel-value/memory-optimized-number-texture":93,"./kernel-value/number-texture":94,"./kernel-value/single-array":95,"./kernel-value/single-array1d-i":96,"./kernel-value/single-array2":97,"./kernel-value/single-array2d-i":98,"./kernel-value/single-array3":99,"./kernel-value/single-array3d-i":100,"./kernel-value/single-array4":101,"./kernel-value/single-input":102,"./kernel-value/unsigned-array":103,"./kernel-value/unsigned-input":104}],75:[function(require2,module3,exports3){const{WebGLKernelValueBoolean}=require2("../../web-gl/kernel-value/boolean");class WebGL2KernelValueBoolean extends WebGLKernelValueBoolean{}module3.exports={WebGL2KernelValueBoolean}},{"../../web-gl/kernel-value/boolean":41}],76:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueHTMLImageArray}=require2("./html-image-array");class WebGL2KernelValueDynamicHTMLImageArray extends WebGL2KernelValueHTMLImageArray{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2DArray ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(images){const{width,height}=images[0];this.checkSize(width,height);this.dimensions=[width,height,images.length];this.textureSize=[width,height];this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(images)}}module3.exports={WebGL2KernelValueDynamicHTMLImageArray}},{"../../../utils":114,"./html-image-array":89}],77:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicHTMLImage}=require2("../../web-gl/kernel-value/dynamic-html-image");class WebGL2KernelValueDynamicHTMLImage extends WebGLKernelValueDynamicHTMLImage{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicHTMLImage}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-html-image":42}],78:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueDynamicHTMLImage}=require2("./dynamic-html-image");class WebGL2KernelValueDynamicHTMLVideo extends WebGL2KernelValueDynamicHTMLImage{}module3.exports={WebGL2KernelValueDynamicHTMLVideo}},{"../../../utils":114,"./dynamic-html-image":77}],79:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicMemoryOptimizedNumberTexture}=require2("../../web-gl/kernel-value/dynamic-memory-optimized-number-texture");class WebGL2KernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueDynamicMemoryOptimizedNumberTexture{getSource(){return utils.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-memory-optimized-number-texture":44}],80:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicNumberTexture}=require2("../../web-gl/kernel-value/dynamic-number-texture");class WebGL2KernelValueDynamicNumberTexture extends WebGLKernelValueDynamicNumberTexture{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicNumberTexture}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-number-texture":45}],81:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray}=require2("../../web-gl2/kernel-value/single-array");class WebGL2KernelValueDynamicSingleArray extends WebGL2KernelValueSingleArray{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.dimensions=utils.getDimensions(value2,true);this.textureSize=utils.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio);this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio;this.checkSize(this.textureSize[0],this.textureSize[1]);this.uploadValue=new Float32Array(this.uploadArrayLength);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array":95}],82:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray1DI}=require2("../../web-gl2/kernel-value/single-array1d-i");class WebGL2KernelValueDynamicSingleArray1DI extends WebGL2KernelValueSingleArray1DI{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.setShape(value2);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray1DI}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array1d-i":96}],83:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray2DI}=require2("../../web-gl2/kernel-value/single-array2d-i");class WebGL2KernelValueDynamicSingleArray2DI extends WebGL2KernelValueSingleArray2DI{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.setShape(value2);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray2DI}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array2d-i":98}],84:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleArray3DI}=require2("../../web-gl2/kernel-value/single-array3d-i");class WebGL2KernelValueDynamicSingleArray3DI extends WebGL2KernelValueSingleArray3DI{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){this.setShape(value2);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleArray3DI}},{"../../../utils":114,"../../web-gl2/kernel-value/single-array3d-i":100}],85:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGL2KernelValueSingleInput}=require2("../../web-gl2/kernel-value/single-input");class WebGL2KernelValueDynamicSingleInput extends WebGL2KernelValueSingleInput{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}updateValue(value2){let[w,h,d]=value2.size;this.dimensions=new Int32Array([w||1,h||1,d||1]);this.textureSize=utils.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio);this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio;this.checkSize(this.textureSize[0],this.textureSize[1]);this.uploadValue=new Float32Array(this.uploadArrayLength);this.kernel.setUniform3iv(this.dimensionsId,this.dimensions);this.kernel.setUniform2iv(this.sizeId,this.textureSize);super.updateValue(value2)}}module3.exports={WebGL2KernelValueDynamicSingleInput}},{"../../../utils":114,"../../web-gl2/kernel-value/single-input":102}],86:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicUnsignedArray}=require2("../../web-gl/kernel-value/dynamic-unsigned-array");class WebGL2KernelValueDynamicUnsignedArray extends WebGLKernelValueDynamicUnsignedArray{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicUnsignedArray}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-unsigned-array":51}],87:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueDynamicUnsignedInput}=require2("../../web-gl/kernel-value/dynamic-unsigned-input");class WebGL2KernelValueDynamicUnsignedInput extends WebGLKernelValueDynamicUnsignedInput{getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2D ${this.id}`,`uniform ${variablePrecision} ivec2 ${this.sizeId}`,`uniform ${variablePrecision} ivec3 ${this.dimensionsId}`])}}module3.exports={WebGL2KernelValueDynamicUnsignedInput}},{"../../../utils":114,"../../web-gl/kernel-value/dynamic-unsigned-input":52}],88:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelValueFloat}=require2("../../web-gl/kernel-value/float");class WebGL2KernelValueFloat extends WebGLKernelValueFloat{}module3.exports={WebGL2KernelValueFloat}},{"../../../utils":114,"../../web-gl/kernel-value/float":53}],89:[function(require2,module3,exports3){const{utils}=require2("../../../utils");const{WebGLKernelArray}=require2("../../web-gl/kernel-value/array");class WebGL2KernelValueHTMLImageArray extends WebGLKernelArray{constructor(value2,settings){super(value2,settings);this.checkSize(value2[0].width,value2[0].height);this.dimensions=[value2[0].width,value2[0].height,value2.length];this.textureSize=[value2[0].width,value2[0].height]}defineTexture(){const{context:gl}=this;gl.activeTexture(this.contextHandle);gl.bindTexture(gl.TEXTURE_2D_ARRAY,this.texture);gl.texParameteri(gl.TEXTURE_2D_ARRAY,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D_ARRAY,gl.TEXTURE_MIN_FILTER,gl.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}; -`}getSource(){const variablePrecision=this.getVariablePrecisionString();return utils.linesToString([`uniform ${variablePrecision} sampler2DArray ${this.id}`,`${variablePrecision} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${variablePrecision} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(images){const{context:gl}=this;gl.activeTexture(this.contextHandle);gl.bindTexture(gl.TEXTURE_2D_ARRAY,this.texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);gl.texImage3D(gl.TEXTURE_2D_ARRAY,0,gl.RGBA,images[0].width,images[0].height,images.length,0,gl.RGBA,gl.UNSIGNED_BYTE,null);for(let i=0;iKernel2.isSupported)}static get isKernelMapSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.kernelMap)}static get isOffscreenCanvasSupported(){return typeof Worker!=="undefined"&&typeof OffscreenCanvas!=="undefined"||typeof importScripts!=="undefined"}static get isWebGLSupported(){return WebGLKernel.isSupported}static get isWebGL2Supported(){return WebGL2Kernel.isSupported}static get isHeadlessGLSupported(){return HeadlessGLKernel.isSupported}static get isCanvasSupported(){return typeof HTMLCanvasElement!=="undefined"}static get isGPUHTMLImageArraySupported(){return WebGL2Kernel.isSupported}static get isSinglePrecisionSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.isFloatRead&&Kernel2.features.isTextureFloat)}constructor(settings){settings=settings||{};this.canvas=settings.canvas||null;this.context=settings.context||null;this.mode=settings.mode;this.Kernel=null;this.kernels=[];this.functions=[];this.nativeFunctions=[];this.injectedNative=null;if(this.mode==="dev")return;this.chooseKernel();if(settings.functions){for(let i=0;isettings.argumentTypes[argumentName])}function onRequestFallback(args){console.warn("Falling back to CPU");const fallbackKernel=new CPUKernel(source,{argumentTypes:kernelRun.argumentTypes,constantTypes:kernelRun.constantTypes,graphical:kernelRun.graphical,loopMaxIterations:kernelRun.loopMaxIterations,constants:kernelRun.constants,dynamicOutput:kernelRun.dynamicOutput,dynamicArgument:kernelRun.dynamicArguments,output:kernelRun.output,precision:kernelRun.precision,pipeline:kernelRun.pipeline,immutable:kernelRun.immutable,optimizeFloatMemory:kernelRun.optimizeFloatMemory,fixIntegerDivisionAccuracy:kernelRun.fixIntegerDivisionAccuracy,functions:kernelRun.functions,nativeFunctions:kernelRun.nativeFunctions,injectedNative:kernelRun.injectedNative,subKernels:kernelRun.subKernels,strictIntegers:kernelRun.strictIntegers,debug:kernelRun.debug});fallbackKernel.build.apply(fallbackKernel,args);const result=fallbackKernel.run.apply(fallbackKernel,args);kernelRun.replaceKernel(fallbackKernel);return result}function onRequestSwitchKernel(reasons,args,_kernel){if(_kernel.debug){console.warn("Switching kernels")}let newOutput=null;if(_kernel.signature&&!switchableKernels[_kernel.signature]){switchableKernels[_kernel.signature]=_kernel}if(_kernel.dynamicOutput){for(let i=reasons.length-1;i>=0;i--){const reason=reasons[i];if(reason.type==="outputPrecisionMismatch"){newOutput=reason.needed}}}const Constructor=_kernel.constructor;const argumentTypes=Constructor.getArgumentTypes(_kernel,args);const signature=Constructor.getSignature(_kernel,argumentTypes);const existingKernel=switchableKernels[signature];if(existingKernel){existingKernel.onActivate(_kernel);return existingKernel}const newKernel=switchableKernels[signature]=new Constructor(source,{argumentTypes,constantTypes:_kernel.constantTypes,graphical:_kernel.graphical,loopMaxIterations:_kernel.loopMaxIterations,constants:_kernel.constants,dynamicOutput:_kernel.dynamicOutput,dynamicArgument:_kernel.dynamicArguments,context:_kernel.context,canvas:_kernel.canvas,output:newOutput||_kernel.output,precision:_kernel.precision,pipeline:_kernel.pipeline,immutable:_kernel.immutable,optimizeFloatMemory:_kernel.optimizeFloatMemory,fixIntegerDivisionAccuracy:_kernel.fixIntegerDivisionAccuracy,functions:_kernel.functions,nativeFunctions:_kernel.nativeFunctions,injectedNative:_kernel.injectedNative,subKernels:_kernel.subKernels,strictIntegers:_kernel.strictIntegers,debug:_kernel.debug,gpu:_kernel.gpu,validate,returnType:_kernel.returnType,tactic:_kernel.tactic,onRequestFallback,onRequestSwitchKernel,texture:_kernel.texture,mappedTextures:_kernel.mappedTextures,drawBuffersMap:_kernel.drawBuffersMap});newKernel.build.apply(newKernel,args);kernelRun.replaceKernel(newKernel);kernels.push(newKernel);return newKernel}const mergedSettings=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate,onRequestFallback,onRequestSwitchKernel},settingsCopy);const kernel=new this.Kernel(source,mergedSettings);const kernelRun=kernelRunShortcut(kernel);if(!this.canvas){this.canvas=kernel.canvas}if(!this.context){this.context=kernel.context}kernels.push(kernel);return kernelRun}createKernelMap(){let fn;let settings;const argument2Type=typeof arguments[arguments.length-2];if(argument2Type==="function"||argument2Type==="string"){fn=arguments[arguments.length-2];settings=arguments[arguments.length-1]}else{fn=arguments[arguments.length-1]}if(this.mode!=="dev"){if(!this.Kernel.isSupported||!this.Kernel.features.kernelMap){if(this.mode&&kernelTypes.indexOf(this.mode)<0){throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}}}const settingsCopy=upgradeDeprecatedCreateKernelSettings(settings);if(settings&&typeof settings.argumentTypes==="object"){settingsCopy.argumentTypes=Object.keys(settings.argumentTypes).map(argumentName=>settings.argumentTypes[argumentName])}if(Array.isArray(arguments[0])){settingsCopy.subKernels=[];const functions=arguments[0];for(let i=0;i0){throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.')}this.nativeFunctions.push(Object.assign({name:name2,source},settings));return this}injectNative(source){this.injectedNative=source;return this}destroy(){return new Promise((resolve,reject)=>{if(!this.kernels){resolve()}setTimeout(()=>{try{for(let i=0;i{try{accept(run.apply(this,arguments))}catch(e){reject(e)}})};shortcut.replaceKernel=function(replacementKernel){kernel=replacementKernel;bindKernelToShortcut(kernel,shortcut)};bindKernelToShortcut(kernel,shortcut);return shortcut}function bindKernelToShortcut(kernel,shortcut){if(shortcut.kernel){shortcut.kernel=kernel;return}const properties=utils.allPropertiesOf(kernel);for(let i=0;ishortcut.kernel[property]);shortcut.__defineSetter__(property,value2=>{shortcut.kernel[property]=value2})}}shortcut.kernel=kernel}module3.exports={kernelRunShortcut}},{"./utils":114}],112:[function(require2,module3,exports3){const source=`// https://www.shadertoy.com/view/4t2SDh - //note: uniformly distributed, normalized rand, [0,1] - highp float randomSeedShift = 1.0; - highp float slide = 1.0; - uniform highp float randomSeed1; - uniform highp float randomSeed2; - - highp float nrand(highp vec2 n) { - highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453); - randomSeedShift = result; - if (randomSeedShift > 0.5) { - slide += 0.00009; - } else { - slide += 0.0009; - } - return result; - }`;const name2="math-random-uniformly-distributed";const functionMatch=`Math.random()`;const functionReplace=`nrand(vTexCoord)`;const functionReturnType="Number";const onBeforeRun=kernel=>{kernel.setUniform1f("randomSeed1",Math.random());kernel.setUniform1f("randomSeed2",Math.random())};const plugin={name:name2,onBeforeRun,functionMatch,functionReplace,functionReturnType,source};module3.exports=plugin},{}],113:[function(require2,module3,exports3){class Texture{constructor(settings){const{texture,size,dimensions,output,context,type="NumberTexture",kernel,internalFormat,textureFormat}=settings;if(!output)throw new Error('settings property "output" required.');if(!context)throw new Error('settings property "context" required.');if(!texture)throw new Error('settings property "texture" required.');if(!kernel)throw new Error('settings property "kernel" required.');this.texture=texture;if(texture._refs){texture._refs++}else{texture._refs=1}this.size=size;this.dimensions=dimensions;this.output=output;this.context=context;this.kernel=kernel;this.type=type;this._deleted=false;this.internalFormat=internalFormat;this.textureFormat=textureFormat}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}module3.exports={Texture}},{}],114:[function(require2,module3,exports3){const acorn=require2("acorn");const{Input}=require2("./input");const{Texture}=require2("./texture");const FUNCTION_NAME=/function ([^(]*)/;const STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;const ARGUMENT_NAMES=/([^\s,]+)/g;const utils={systemEndianness(){return _systemEndianness},getSystemEndianness(){const b=new ArrayBuffer(4);const a=new Uint32Array(b);const c=new Uint8Array(b);a[0]=3735928559;if(c[0]===239)return"LE";if(c[0]===222)return"BE";throw new Error("unknown endianness")},isFunction(funcObj){return typeof funcObj==="function"},isFunctionString(fn){if(typeof fn==="string"){return fn.slice(0,"function".length).toLowerCase()==="function"}return false},getFunctionNameFromString(funcStr){const result=FUNCTION_NAME.exec(funcStr);if(!result||result.length===0)return null;return result[1].trim()},getFunctionBodyFromString(funcStr){return funcStr.substring(funcStr.indexOf("{")+1,funcStr.lastIndexOf("}"))},getArgumentNamesFromString(fn){const fnStr=fn.replace(STRIP_COMMENTS,"");let result=fnStr.slice(fnStr.indexOf("(")+1,fnStr.indexOf(")")).match(ARGUMENT_NAMES);if(result===null){result=[]}return result},clone(obj){if(obj===null||typeof obj!=="object"||obj.hasOwnProperty("isActiveClone"))return obj;const temp=obj.constructor();for(let key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){obj.isActiveClone=null;temp[key]=utils.clone(obj[key]);delete obj.isActiveClone}}return temp},isArray(array){return!isNaN(array.length)},getVariableType(value2,strictIntegers){if(utils.isArray(value2)){if(value2.length>0&&value2[0].nodeName==="IMG"){return"HTMLImageArray"}return"Array"}switch(value2.constructor){case Boolean:return"Boolean";case Number:if(strictIntegers&&Number.isInteger(value2)){return"Integer"}return"Float";case Texture:return value2.type;case Input:return"Input"}switch(value2.nodeName){case"IMG":return"HTMLImage";case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}if(value2.hasOwnProperty("type")){return value2.type}return"Unknown"},getKernelTextureSize(settings,dimensions){let[w,h,d]=dimensions;let texelCount=(w||1)*(h||1)*(d||1);if(settings.optimizeFloatMemory&&settings.precision==="single"){w=texelCount=Math.ceil(texelCount/4)}if(h>1&&w*h===texelCount){return new Int32Array([w,h])}return utils.closestSquareDimensions(texelCount)},closestSquareDimensions(length){const sqrt=Math.sqrt(length);let high=Math.ceil(sqrt);let low=Math.floor(sqrt);while(high*low0){return lines.join(";\n")+";\n"}else{return"\n"}},warnDeprecated(type,oldName,newName){if(newName){console.warn(`You are using a deprecated ${type} "${oldName}". It has been replaced with "${newName}". Fixing, but please upgrade as it will soon be removed.`)}else{console.warn(`You are using a deprecated ${type} "${oldName}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)}},flipPixels:(pixels,width,height)=>{const halfHeight=height/2|0;const bytesPerRow=width*4;const temp=new Uint8ClampedArray(width*4);const result=pixels.slice(0);for(let y=0;y{return array.subarray(0,width)},erect2DPackedFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{return array.subarray(0,width)},erectMemoryOptimized2DFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{const xResults=new Float32Array(width);let i=0;for(let x2=0;x2{const yResults=new Array(height);let i=0;for(let y=0;y{const zResults=new Array(depth);let i=0;for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const yResults=new Array(height);const XResultsMax=width*4;for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(array);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const{findDependency,thisLookup,doNotDefine}=settings;let flattened=settings.flattened;if(!flattened){flattened=settings.flattened={}}const ast=acorn.parse(source);const functionDependencies=[];let indent=0;function flatten2(ast2){if(Array.isArray(ast2)){const results=[];for(let i=0;ir!==null);if(declarations.length<1){return""}else{return`${ast2.kind} ${declarations.join(",")}`}case"VariableDeclarator":if(ast2.init.object&&ast2.init.object.type==="ThisExpression"){const lookup=thisLookup(ast2.init.property.name,true);if(lookup){return`${ast2.id.name} = ${flatten2(ast2.init)}`}else{return null}}else{return`${ast2.id.name} = ${flatten2(ast2.init)}`}case"CallExpression":{if(ast2.callee.property.name==="subarray"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.name==="gl"||ast2.callee.object.name==="context"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.type==="ThisExpression"){functionDependencies.push(findDependency("this",ast2.callee.property.name));return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else if(ast2.callee.object.name){const foundSource=findDependency(ast2.callee.object.name,ast2.callee.property.name);if(foundSource===null){return`${ast2.callee.object.name}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{functionDependencies.push(foundSource);return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}}else if(ast2.callee.object.type==="MemberExpression"){return`${flatten2(ast2.callee.object)}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{throw new Error("unknown ast.callee")}}case"ReturnStatement":return`return ${flatten2(ast2.argument)}`;case"BinaryExpression":return`(${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)})`;case"UnaryExpression":if(ast2.prefix){return`${ast2.operator} ${flatten2(ast2.argument)}`}else{return`${flatten2(ast2.argument)} ${ast2.operator}`}case"ExpressionStatement":return`${flatten2(ast2.expression)}`;case"SequenceExpression":return`(${flatten2(ast2.expressions)})`;case"ArrowFunctionExpression":return`(${ast2.params.map(flatten2).join(", ")}) => ${flatten2(ast2.body)}`;case"Literal":return ast2.raw;case"Identifier":return ast2.name;case"MemberExpression":if(ast2.object.type==="ThisExpression"){return thisLookup(ast2.property.name)}if(ast2.computed){return`${flatten2(ast2.object)}[${flatten2(ast2.property)}]`}return flatten2(ast2.object)+"."+flatten2(ast2.property);case"ThisExpression":return"this";case"NewExpression":return`new ${flatten2(ast2.callee)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`;case"ForStatement":return`for (${flatten2(ast2.init)};${flatten2(ast2.test)};${flatten2(ast2.update)}) ${flatten2(ast2.body)}`;case"AssignmentExpression":return`${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)}`;case"UpdateExpression":return`${flatten2(ast2.argument)}${ast2.operator}`;case"IfStatement":return`if (${flatten2(ast2.test)}) ${flatten2(ast2.consequent)}`;case"ThrowStatement":return`throw ${flatten2(ast2.argument)}`;case"ObjectPattern":return ast2.properties.map(flatten2).join(", ");case"ArrayPattern":return ast2.elements.map(flatten2).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${flatten2(ast2.test)}?${flatten2(ast2.consequent)}:${flatten2(ast2.alternate)}`;case"Property":if(ast2.kind==="init"){return flatten2(ast2.key)}}throw new Error(`unhandled ast.type of ${ast2.type}`)}const result=flatten2(ast);if(functionDependencies.length>0){const flattenedFunctionDependencies=[];for(let i=0;i{if(ast.type!=="VariableDeclaration")throw new Error('Ast is not of type "VariableDeclaration"');const normalizedDeclarations=[];for(let declarationIndex=0;declarationIndex{const rKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.r*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const gKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.g*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const bKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.b*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const aKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.a*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const result=[rKernel(image),gKernel(image),bKernel(image),aKernel(image)];result.rKernel=rKernel;result.gKernel=gKernel;result.bKernel=bKernel;result.aKernel=aKernel;result.gpu=gpu;return result},splitRGBAToCanvases:(gpu,rgba,width,height)=>{const visualKernelR=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(pixel.r/255,0,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelR(rgba);const visualKernelG=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,pixel.g/255,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelG(rgba);const visualKernelB=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,0,pixel.b/255,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelB(rgba);const visualKernelA=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(255,255,255,pixel.a/255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelA(rgba);return[visualKernelR.canvas,visualKernelG.canvas,visualKernelB.canvas,visualKernelA.canvas]},getMinifySafeName:fn=>{try{const ast=acorn.parse(`const value = ${fn.toString()}`);const{init}=ast.body[0].declarations[0];return init.body.name||init.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(name2){if(dollarSign.test(name2)){name2=name2.replace(dollarSign,"S_S")}if(doubleUnderscore.test(name2)){name2=name2.replace(doubleUnderscore,"U_U")}else if(singleUnderscore.test(name2)){name2=name2.replace(singleUnderscore,"u_u")}return name2}};const dollarSign=/\$/;const doubleUnderscore=/__/;const singleUnderscore=/_/;const _systemEndianness=utils.getSystemEndianness();module3.exports={utils}},{"./input":110,"./texture":113,"acorn":1}]},{},[107])(107)})}});var import_gpu_browser_min=__toESM(require_gpu_browser_min());function add(a,b){return a+b}function sub(a,b){return a-b}function mul(a,b){return a*b}function div(a,b){return a/b}function cadd(a_real,a_imag,b_real,b_imag){return[a_real+b_real,a_imag+b_imag]}function csub(a_real,a_imag,b_real,b_imag){return[a_real-b_real,a_imag-b_imag]}function cmul(a_real,a_imag,b_real,b_imag){return[a_real*b_real-a_imag*b_imag,a_real*b_imag+a_imag*b_real]}function cexp(a_real,a_imag){const er=Math.exp(a_real);return[er*Math.cos(a_imag),er*Math.sin(a_imag)]}function mag(a,b){return Math.sqrt(a*a+b*b)}function conj(imag){return 0-imag}function lof(n){const sqrt_n=Math.sqrt(n);var factor=3;while(factor<=sqrt_n){if(n%factor===0)return factor;factor+=2}}function mean(arr,len){var mean2=0;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signal[j]*Math.cos(sharedi);imag=imag-signal[j]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function FFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=imag-signals[j+(len-1)*n]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function iDFT(fft,len,freq){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+fft[j]*Math.cos(sharedi);imag=fft[j]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function iFFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=signals[j+(len-1)*n]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function correlogramsKern(arrays,len){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=mean(arrays[k],len);var arr2mean=mean(arrays[k+1],len);var arr1Est=est(arrays[k],arr1mean,len);var arr2Est2=est(arrays[k+1],arr2mean,len);var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function correlogramsPCKern(arrays,len,means,estimators){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=means[k];var arr2mean=means[k+1];var arr1Est=estimators[k];var arr2Est2=estimators[k+1];var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function dftKern(signal,len,scalar){var result=DFT(signal,len,this.thread.x);return mag(result[0],result[1])*scalar}function idftKern(amplitudes,len,scalar){var result=iDFT(amplitudes,len,this.thread.x);return mag(result[0],result[1])*scalar}function fftKern(signal,len,scalar,sampleRate){var result=FFT(signal,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function ifftKern(amplitudes,len,scalar,sampleRate){var result=iFFT(amplitudes,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function listdft2DKern(signals,scalar){var len=this.output.x;var result=DFT(signals[this.thread.y],len,this.thread.x);return mag(result[0],result[1])*scalar}function listdft1DKern(signals,len,scalar){var result=[0,0];if(this.thread.x<=len){result=DFT(signals,len,this.thread.x)}else{var n=Math.floor(this.thread.x/len);result=DFTlist(signals,len,this.thread.x-n*len,n)}return mag(result[0],result[1])*scalar}function listfft1DKern(signals,len,scalar,sps){var result=[0,0];if(this.thread.x<=len){result=FFT(signals,len,this.thread.x,sps)}else{var n=Math.floor(this.thread.x/len);result=FFTlist(signals,len,this.thread.x-n*len,n,sps)}return mag(result[0],result[1])*scalar}function dft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=DFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function fft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=FFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function idft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iDFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function ifft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iFFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function listdft1D_windowedKern(signals,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];if(this.thread.x=width){i++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+i+kernelRadius;const weights=kernel[kernelOffset];const pixel=img[this.thread.y+i][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}i++}this.color(r,g,b)}function multiImgConv2DKern(img,width,height,kernels,kernelLengths,nKernels){let r=0,g=0,b=0;for(var i=0;i=width){k++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+k+kernelRadius;const weights=kernels[i][kernelOffset];const pixel=img[this.thread.y+k][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}k++}}this.color(r,g,b)}function transpose2DKern(mat2){return mat2[this.thread.y][this.thread.x]}var createGpuKernels={correlogramsKern,correlogramsPCKern,dftKern,idftKern,fftKern,ifftKern,dft_windowedKern,idft_windowedKern,fft_windowedKern,ifft_windowedKern,listdft2DKern,listdft1DKern,listfft1DKern,listfft1D_windowedKern,listdft1D_windowedKern,listidft1D_windowedKern,listifft1D_windowedKern,bulkArrayMulKern,multiImgConv2DKern,ImgConv2DKern,transpose2DKern};var addGpuFunctions=[add,sub,mul,div,cadd,csub,cmul,cexp,mag,conj,lof,mean,est,mse,rms,xcor,softmax,DFT,DFTlist,iDFT,iDFTlist,FFT,iFFT,iFFTlist];function makeKrnl(gpu,f,opts={setDynamicOutput:true,setDynamicArguments:true,setPipeline:true,setImmutable:true,setGraphical:false}){const k=gpu.createKernel(f);if(opts.setDynamicOutput)k.setDynamicOutput(true);if(opts.output)k.setOutput(opts.output);if(opts.setDynamicArguments)k.setDynamicArguments(true);if(opts.setPipeline)k.setPipeline(true);if(opts.setImmutable)k.setImmutable(true);if(opts.setGraphical)k.setGraphical(true);return k}function makeCanvasKrnl(gpu,f,opts={output:[300,300],setDynamicArguments:true,setDynamicOutput:true,setPipeline:false,setImmutable:true,setGraphical:true},divId){const k=makeKrnl(gpu,f,opts);const canvas=k.canvas;if(typeof divId==="string")document.getElementById(toAppend).appendChild(canvas);else if(divId)toAppend.appendChild(canvas);else document.body.appendChild(canvas);return k}var gpuUtils=class{constructor(gpu=new GPUjs){this.gpu=gpu;this.kernels=new Map;this.kernel;this.PI=3.141592653589793;this.SQRT1_2=.7071067811865476;this.addFunctions();this.imgkernels={edgeDetection:[-1,-1,-1,-1,8,-1,-1,-1,-1],boxBlur:[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],sobelLeft:[1,0,-1,2,0,-2,1,0,-1],sobelRight:[-1,0,1,-2,0,2,-1,0,1],sobelTop:[1,2,1,0,0,0,-1,-2,-1],sobelBottom:[-1,2,1,0,0,0,1,2,1],identity:[0,0,0,0,1,0,0,0,0],gaussian3x3:[1,2,1,2,4,2,1,2,1],guassian7x7:[0,0,0,5,0,0,0,0,5,18,32,18,5,0,0,18,64,100,64,18,0,5,32,100,100,100,32,5,0,18,64,100,64,18,0,0,5,18,32,18,5,0,0,0,0,5,0,0,0],emboss:[-2,-1,0,-1,1,1,0,1,2],sharpen:[0,-1,0,-1,5,-1,0,-1,0]}}addFunction(func=function f(){}){this.gpu.addFunction(func)}addKernel(name2="",krnl=function foo(){},opts){let found=this.kernels.get(name2);if(!found){this.kernels.set(name2,makeKrnl(this.gpu,krnl,opts));return true}else{console.error("Kernel already exists");return false}}addCanvasKernel(name2,f,opts,divId){let found=this.kernels.get(name2);if(!found){let krnl=makeCanvasKrnl(this.gpu,f,opts,divId);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}combineKernels(name2,fs=[],ckrnl=function foo(){}){let found=this.kernels.get(name2);if(!found){fs.forEach((f,i)=>{if(typeof f==="string"){let found2=this.kernels.get(f);if(found2)fs[i]=found2;else return false}else if(typeof f==="function"){if(this.kernels.get(f.name)){}else{this.addKernel(f.name,f)}}});let krnl=this.gpu.combineKernels(...fs,ckrnl);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}callKernel(name2="",args=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}result=krnl(...args);return result}callCanvasKernel(name2="",args=[],outputDims=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}else{if(outputDims.length===2)krnl.setOutput(outputDims);result=krnl(...args);return result}}hasKernel(name2=""){let found=this.kernels.get(name2);if(!found){return false}else return true}addFunctions(){addGpuFunctions.forEach(f=>this.gpu.addFunction(f));this.correlograms=makeKrnl(this.gpu,createGpuKernels.correlogramsKern);this.correlogramsPC=makeKrnl(this.gpu,createGpuKernels.correlogramsPCKern);this.dft=makeKrnl(this.gpu,createGpuKernels.dftKern);this.idft=makeKrnl(this.gpu,createGpuKernels.idftKern);this.dft_windowed=makeKrnl(this.gpu,createGpuKernels.dft_windowedKern);this.idft_windowed=makeKrnl(this.gpu,createGpuKernels.idft_windowedKern);this.fft=makeKrnl(this.gpu,createGpuKernels.fftKern);this.ifft=makeKrnl(this.gpu,createGpuKernels.ifftKern);this.fft_windowed=makeKrnl(this.gpu,createGpuKernels.fft_windowedKern);this.ifft_windowed=makeKrnl(this.gpu,createGpuKernels.ifft_windowedKern);this.listdft2D=makeKrnl(this.gpu,createGpuKernels.listdft2DKern);this.listdft1D=makeKrnl(this.gpu,createGpuKernels.listdft1DKern);this.listdft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listdft1D_windowedKern);this.listfft1D=makeKrnl(this.gpu,createGpuKernels.listfft1DKern);this.listfft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listfft1D_windowedKern);this.listidft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listidft1D_windowedKern);this.listifft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listifft1D_windowedKern);this.bulkArrayMul=makeKrnl(this.gpu,createGpuKernels.bulkArrayMulKern);let kernels=[{name:"correlograms",krnl:this.correlograms},{name:"correlogramsPC",krnl:this.correlogramsPC},{name:"dft",krnl:this.dft},{name:"idft",krnl:this.idft},{name:"dft_windowed",krnl:this.idft_windowed},{name:"fft",krnl:this.fft},{name:"ifft",krnl:this.ifft},{name:"fft_windowed",krnl:this.fft_windowed},{name:"ifft_windowed",krnl:this.ifft_windowed},{name:"listdft2D",krnl:this.listdft2D},{name:"listdft1D",krnl:this.listdft1D},{name:"listdft1D_windowed",krnl:this.listdft1D_windowed},{name:"listfft1D",krnl:this.listfft1D},{name:"listfft1D_windowed",krnl:this.listfft1D_windowed},{name:"listidft1D_windowed",krnl:this.listidft1D_windowed},{name:"listifft1D_windowed",krnl:this.listifft1D_windowed},{name:"bulkArrayMul",krnl:this.bulkArrayMul}];kernels.forEach(k=>{this.kernels.set(k.name,k)});const signalBandpass=(signal,sampleRate,freqStart,freqEnd,scalar)=>{var dft2=this.fft_windowed(signal,sampleRate,freqStart,freqEnd,scalar,0);var filtered_signal=this.ifft_windowed(dft2,sampleRate,freqStart,freqEnd,scalar);return filtered_signal};const signalBandpassMulti=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var dfts=this.listdft1D_windowed(signals,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var filtered_signals=this.listifft1D_windowed(dfts,sampleRate,freqStart,freqEnd,scalar);return filtered_signals};this.gpuCoherence=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var xcors=this.correlograms(signals);var dfts=this.listfft1D_windowed(xcors,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var products=this.bulkArrayMul(dfts,sampleRate,5,1);return products}}gpuXCors(arrays,precompute=false,texOut=false){var outputTex;if(precompute===true){var means=[];var ests=[];arrays.forEach((arr,i2)=>{means.push(arr.reduce((prev,curr)=>curr+=prev)/arr.length);ests.push(Math.sqrt(means[i2].reduce((sum,item)=>sum+=Math.pow(item-mean1,2))))});var meansbuf=[];var estsbuf=[];var buffer=[];for(var i=0;i{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D.setOutput([signalBufferProcessed.length]);this.listdft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D(signalBufferProcessed,nSamplesPerChannel,scalar);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D_windowed.setOutput([signalBufferProcessed.length]);this.listdft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}gpuFFT(signalBuffer,nSeconds,scalar=1,sampleRate,texOut=false){var nSamples=signalBuffer.length;var sampleRate=nSamples/nSeconds;this.fft.setOutput([signalBuffer.length]);this.fft.setLoopMaxIterations(nSamples);var outputTex=this.fft(signalBuffer,nSamples,scalar,sampleRate);var output=null;if(texOut===false){var freqDist=this.makeFrequencyDistribution(nSamples,sampleRate);var signalBufferProcessed=outputTex.toArray();outputTex.delete();return[freqDist,this.orderMagnitudes(signalBufferProcessed)]}else{var tex=outputTex;outputTex.delete();return tex}}MultiChannelFFT(signalBuffer,nSeconds,scalar=1,texOut=false){var signalBufferProcessed=[];signalBuffer.forEach(row=>{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D.setOutput([signalBufferProcessed.length]);this.listfft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D(signalBufferProcessed,nSamplesPerChannel,scalar,sampleRate);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D_windowed.setOutput([signalBufferProcessed.length]);this.listfft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}orderMagnitudes(unorderedMags){return[...unorderedMags.slice(Math.ceil(unorderedMags.length*.5),unorderedMags.length),...unorderedMags.slice(0,Math.ceil(unorderedMags.length*.5))]}makeFrequencyDistribution(FFTlength,sampleRate){var N=FFTlength;var df=sampleRate/N;var freqDist=[];for(var i=-N/2;i1){magList.forEach((row,k)=>{summedMags.push([]);var _max=1/Math.max(...row);for(var i2=0;i2{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean2=void 0)=>{let avg=mean2;if(!mean2)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean2=this.mean(arr);let std=this.std(arr,mean2);let z=new Array(arr.length);for(let i=0;ia+(b-mean2)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean2=this.mean(arr);let std=this.std(arr,mean2);return populationMean?std/populationMean:std/mean2};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y)=>acc+Math.pow(y-meanY,2),0);const ssResidual=observed.reduce((acc,y,i)=>acc+Math.pow(y-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x2)=>sum+x2,0);const sumY=yCoords.reduce((sum,y)=>sum+y,0);const sumXY=xCoords.reduce((sum,x2,i)=>sum+x2*yCoords[i],0);const sumX2=xCoords.reduce((sum,x2)=>sum+x2*x2,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{return vec.map((v,i)=>v-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v,i)=>v/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v,i)=>v+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v,i)=>v-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v,i)=>v/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x2,y,z)=>{var r=Math.sqrt(x2*x2+y*y+z*z);var theta=Math.atan2(y,x2);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y=x2;return y},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x2=Math.cos(t);return x2},yFunc=t=>{let y=Math.sin(t);return y},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u,v)=>u,yFunc=(u,v)=>v,zFunc=(u,v)=>u+v,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u=rangeU[0];u{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value2,index)=>{const row=Array(values.length).fill(0);row[index]=value2;return row})};static householderMatrix=v=>{const size=v.length;const vvT=v.map(rowVal=>v.map(colVal=>rowVal*colVal));const vTv=this.normalize(v)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A,B)=>{return A.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean2=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value2=>(value2-min)/(max-min))};static garroteThreshold=(data,value2)=>{return data.map(x2=>{if(Math.abs(x2)<=value2){return 0}else{return x2-value2*value2/x2}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean12=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v,i)=>(v-mean12)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x2,x2),this.cov1d(x2,y),this.cov1d(x2,z)],[this.cov1d(y,x2),this.cov1d(y,y),this.cov1d(y,z)],[this.cov1d(z,x2),this.cov1d(z,y),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean2=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean2*mean2-det);let eig1=mean2+sqrt;let eig2=mean2-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean2=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v=>v-mean2)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N=signalA.length;const M=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean12=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(delaybuf[delay+i]-mean12));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x2=arr.filter((element,index)=>{return index%factor===0});return x2};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y=>y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x2)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A,numIter=100)=>{let b=Array(A.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A[0].length>A.length){A=this.transpose(A)}const m=A.length;const n=A[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x2):this.normalize(x2);const u=this.vecsub(x2,e);const normU=this.normalize(u);const v=u.map(val=>val/normU);const Qk=this.householderMatrix(v);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean2=this.mean(smoothed);let std=this.std(smoothed,mean2);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean2)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean2)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}}}return value2}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value2==="function"?value2.toString():value2,path.join("."))}}}return typeof value2==="function"?value2.toString():value2}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx++}}}}}function checkValues(key,value2){let val;if(value2!=null){if(typeof value2==="object"){let c=value2.constructor.name;if(key&&c==="Object"){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}if(c==="Array"){if(value2.length>20){val=value2.slice(value2.length-20)}else val=value2}else if(c.includes("Set")){val=Array.from(value2)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value2){if(value2[prop]==null){obj[prop]=value2[prop]}else if(Array.isArray(value2[prop])){if(value2[prop].length>20)obj[prop]=value2[prop].slice(value2[prop].length-20);else obj[prop]=value2[prop]}else if(value2[prop].constructor.name==="Object"){obj[prop]={};for(const p in value2[prop]){if(Array.isArray(value2[prop][p])){if(value2[prop][p].length>20)obj[prop][p]=value2[prop][p].slice(value2[prop][p].length-20);else obj[prop][p]=value2[prop][p]}else{if(value2[prop][p]!=null){let con=value2[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value2[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value2[prop][p]}}else{obj[prop][p]=value2[prop][p]}}}}else{let con=value2[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value2[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value2[prop]}}}val=obj}else{val=value2}}else{val=value2}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var GPUService=class extends Service{gpu=new gpuUtils;constructor(options){super(options);this.load(this)}addFunc=fn=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addFunction(fn)};addKernel=(name2,fn,options)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addKernel(name2,fn,options)};combineKernels=(name2,fs,ckrnl)=>{for(let i=0;i{this.gpu.callKernel(name2,args)};dft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.gpuDFT(signalBuffer,nSeconds,scalar)};multidft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT(signalBuffer,nSeconds,scalar)};multidftbandpass=(buffered,nSeconds,freqStart,freqEnd,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT_Bandpass(buffered,nSeconds,freqStart,freqEnd,scalar)};coherence=(buffered,nSeconds,freqStart,freqEnd)=>{const correlograms=Math2.correlograms(buffered);const buffer=[...buffered,...correlograms];var dfts;var scalar=1;dfts=this.gpu.MultiChannelDFT_Bandpass(buffer,nSeconds,freqStart,freqEnd,scalar);const cordfts=dfts[1].splice(buffered.length,buffer.length-buffered.length);const coherenceResults=[];const nChannels=buffered.length;var k=0;var l=0;cordfts.forEach((row,i)=>{if(l+k===nChannels){var temp=cordfts.splice(i,1);k++;cordfts.splice(k,0,...temp);l=0}l++});var autoFFTproducts=[];k=0;l=1;cordfts.forEach((dft2,i)=>{var newdft=new Array(dft2.length).fill(0);if(i{newdft[j]=amp});autoFFTproducts.push(newdft)}else{dft2.forEach((amp,j)=>{let denom=autoFFTproducts[k][j]*autoFFTproducts[k+l][j];if(denom!==0)newdft[j]=amp*amp/denom;else newdft[j]=0;if(newdft[j]>1){newdft[j]=1}});l++;if(l+k===nChannels){k++;l=1}coherenceResults.push(newdft)}});return[dfts[0],dfts[1],coherenceResults]}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var dft={sps:250,nSec:1,freqStart:0,freqEnd:125,watch:["0","1","2","3"],blocking:false,__operator:function(arraybuffer){let results=globalThis.gpu.multidftbandpass(arraybuffer,this.nSec,this.freqStart,this.freqEnd,1);let dft2={};this.watch.forEach((tag,i)=>{dft2[tag]=results[1][i]});return{frequencies:results[0],dft:dft2}}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var coherence={sps:250,nSec:1,freqStart:0,freqEnd:125,tags:["0","1","2","3"],coherenceTags:[],__onconnected:function(node){node.tags.forEach((tag,i)=>{if(i!==node.tags.length-1){for(let j=i+1;j{dft2[tag]=results[1][i]});let coherence2={};this.coherenceTags.forEach((tag,i)=>{coherence2[tag]=results[2][i]});return{timestamp:ts,frequencies:results[0],dft:dft2,coherence:coherence2}}};var gpualgorithms={dft,coherence};})(); -/*! Bundled license information: - -gpujsutils/dist/index.esm.js: - (** - * gpu.js - * http://gpu.rocks/ - * - * GPU Accelerated JavaScript - * - * @version 2.11.0 - * @date Tue Jan 05 2021 15:55:59 GMT-0500 (Eastern Standard Time) - * - * @license MIT - * The MIT License - * - * Copyright (c) 2021 gpu.js Team - *) -*/ diff --git a/src/extras/dist/index.services.esm.js b/src/extras/dist/index.services.esm.js deleted file mode 100644 index 46e6014b..00000000 --- a/src/extras/dist/index.services.esm.js +++ /dev/null @@ -1,50 +0,0 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x3=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x3,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x3)(function(x3){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x3+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_bson=__commonJS({"struct/datastructures/bson.cjs"(exports){"use strict";var BSON_MAJOR_VERSION=5;var BSON_INT32_MAX=2147483647;var BSON_INT32_MIN=-2147483648;var BSON_INT64_MAX=Math.pow(2,63)-1;var BSON_INT64_MIN=-Math.pow(2,63);var JS_INT_MAX=Math.pow(2,53);var JS_INT_MIN=-Math.pow(2,53);var BSON_DATA_NUMBER=1;var BSON_DATA_STRING=2;var BSON_DATA_OBJECT=3;var BSON_DATA_ARRAY=4;var BSON_DATA_BINARY=5;var BSON_DATA_UNDEFINED=6;var BSON_DATA_OID=7;var BSON_DATA_BOOLEAN=8;var BSON_DATA_DATE=9;var BSON_DATA_NULL=10;var BSON_DATA_REGEXP=11;var BSON_DATA_DBPOINTER=12;var BSON_DATA_CODE=13;var BSON_DATA_SYMBOL=14;var BSON_DATA_CODE_W_SCOPE=15;var BSON_DATA_INT=16;var BSON_DATA_TIMESTAMP=17;var BSON_DATA_LONG=18;var BSON_DATA_DECIMAL128=19;var BSON_DATA_MIN_KEY=255;var BSON_DATA_MAX_KEY=127;var BSON_BINARY_SUBTYPE_DEFAULT=0;var BSON_BINARY_SUBTYPE_UUID_NEW=4;var BSONType=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});var BSONError=class extends Error{get bsonError(){return true}get name(){return"BSONError"}constructor(message){super(message)}static isBSONError(value){return value!=null&&typeof value==="object"&&"bsonError"in value&&value.bsonError===true&&"name"in value&&"message"in value&&"stack"in value}};var BSONVersionError=class extends BSONError{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`)}};var BSONRuntimeError=class extends BSONError{get name(){return"BSONRuntimeError"}constructor(message){super(message)}};function nodejsMathRandomBytes(byteLength){return nodeJsByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var nodejsRandomBytes=(()=>{try{return __require("crypto").randomBytes}catch{return nodejsMathRandomBytes}})();var nodeJsByteUtils={toLocalBufferType(potentialBuffer){if(Buffer.isBuffer(potentialBuffer)){return potentialBuffer}if(ArrayBuffer.isView(potentialBuffer)){return Buffer.from(potentialBuffer.buffer,potentialBuffer.byteOffset,potentialBuffer.byteLength)}const stringTag=potentialBuffer?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialBuffer);if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return Buffer.from(potentialBuffer)}throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`)},allocate(size){return Buffer.alloc(size)},equals(a,b){return nodeJsByteUtils.toLocalBufferType(a).equals(b)},fromNumberArray(array){return Buffer.from(array)},fromBase64(base64){return Buffer.from(base64,"base64")},toBase64(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64")},fromISO88591(codePoints){return Buffer.from(codePoints,"binary")},toISO88591(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary")},fromHex(hex){return Buffer.from(hex,"hex")},toHex(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex")},fromUTF8(text){return Buffer.from(text,"utf8")},toUTF8(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8")},utf8ByteLength(input){return Buffer.byteLength(input,"utf8")},encodeUTF8Into(buffer2,source,byteOffset){return nodeJsByteUtils.toLocalBufferType(buffer2).write(source,byteOffset,void 0,"utf8")},randomBytes:nodejsRandomBytes};function isReactNative(){const{navigator}=globalThis;return typeof navigator==="object"&&navigator.product==="ReactNative"}function webMathRandomBytes(byteLength){if(byteLength<0){throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`)}return webByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var webRandomBytes=(()=>{const{crypto}=globalThis;if(crypto!=null&&typeof crypto.getRandomValues==="function"){return byteLength=>{return crypto.getRandomValues(webByteUtils.allocate(byteLength))}}else{if(isReactNative()){const{console:console2}=globalThis;console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return webMathRandomBytes}})();var HEX_DIGIT=/(\d|[a-f])/i;var webByteUtils={toLocalBufferType(potentialUint8array){const stringTag=potentialUint8array?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialUint8array);if(stringTag==="Uint8Array"){return potentialUint8array}if(ArrayBuffer.isView(potentialUint8array)){return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset,potentialUint8array.byteOffset+potentialUint8array.byteLength))}if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return new Uint8Array(potentialUint8array)}throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`)},allocate(size){if(typeof size!=="number"){throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`)}return new Uint8Array(size)},equals(a,b){if(a.byteLength!==b.byteLength){return false}for(let i=0;ic.charCodeAt(0))},toBase64(uint8array){return btoa(webByteUtils.toISO88591(uint8array))},fromISO88591(codePoints){return Uint8Array.from(codePoints,c=>c.charCodeAt(0)&255)},toISO88591(uint8array){return Array.from(Uint16Array.from(uint8array),b=>String.fromCharCode(b)).join("")},fromHex(hex){const evenLengthHex=hex.length%2===0?hex:hex.slice(0,hex.length-1);const buffer2=[];for(let i=0;ibyte.toString(16).padStart(2,"0")).join("")},fromUTF8(text){return new TextEncoder().encode(text)},toUTF8(uint8array){return new TextDecoder("utf8",{fatal:false}).decode(uint8array)},utf8ByteLength(input){return webByteUtils.fromUTF8(input).byteLength},encodeUTF8Into(buffer2,source,byteOffset){const bytes=webByteUtils.fromUTF8(source);buffer2.set(bytes,byteOffset);return bytes.byteLength},randomBytes:webRandomBytes};var hasGlobalBuffer=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==true;var ByteUtils=hasGlobalBuffer?nodeJsByteUtils:webByteUtils;var BSONDataView=class extends DataView{static fromUint8Array(input){return new DataView(input.buffer,input.byteOffset,input.byteLength)}};var VALIDATION_REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;var uuidValidateString=str2=>typeof str2==="string"&&VALIDATION_REGEX.test(str2);var uuidHexStringToBuffer=hexString=>{if(!uuidValidateString(hexString)){throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".')}const sanitizedHexString=hexString.replace(/-/g,"");return ByteUtils.fromHex(sanitizedHexString)};function bufferToUuidHexString(buffer2,includeDashes=true){if(includeDashes){return[ByteUtils.toHex(buffer2.subarray(0,4)),ByteUtils.toHex(buffer2.subarray(4,6)),ByteUtils.toHex(buffer2.subarray(6,8)),ByteUtils.toHex(buffer2.subarray(8,10)),ByteUtils.toHex(buffer2.subarray(10,16))].join("-")}return ByteUtils.toHex(buffer2)}function isAnyArrayBuffer(value){return["[object ArrayBuffer]","[object SharedArrayBuffer]"].includes(Object.prototype.toString.call(value))}function isUint8Array(value){return Object.prototype.toString.call(value)==="[object Uint8Array]"}function isRegExp(d2){return Object.prototype.toString.call(d2)==="[object RegExp]"}function isMap(d2){return Object.prototype.toString.call(d2)==="[object Map]"}function isDate(d2){return Object.prototype.toString.call(d2)==="[object Date]"}var BSONValue=class{get[Symbol.for("@@mdb.bson.version")](){return BSON_MAJOR_VERSION}};var Binary=class _Binary extends BSONValue{get _bsontype(){return"Binary"}constructor(buffer2,subType){super();if(!(buffer2==null)&&!(typeof buffer2==="string")&&!ArrayBuffer.isView(buffer2)&&!(buffer2 instanceof ArrayBuffer)&&!Array.isArray(buffer2)){throw new BSONError("Binary can only be constructed from string, Buffer, TypedArray, or Array")}this.sub_type=subType??_Binary.BSON_BINARY_SUBTYPE_DEFAULT;if(buffer2==null){this.buffer=ByteUtils.allocate(_Binary.BUFFER_SIZE);this.position=0}else{if(typeof buffer2==="string"){this.buffer=ByteUtils.fromISO88591(buffer2)}else if(Array.isArray(buffer2)){this.buffer=ByteUtils.fromNumberArray(buffer2)}else{this.buffer=ByteUtils.toLocalBufferType(buffer2)}this.position=this.buffer.byteLength}}put(byteValue){if(typeof byteValue==="string"&&byteValue.length!==1){throw new BSONError("only accepts single character String")}else if(typeof byteValue!=="number"&&byteValue.length!==1)throw new BSONError("only accepts single character Uint8Array or Array");let decodedByte;if(typeof byteValue==="string"){decodedByte=byteValue.charCodeAt(0)}else if(typeof byteValue==="number"){decodedByte=byteValue}else{decodedByte=byteValue[0]}if(decodedByte<0||decodedByte>255){throw new BSONError("only accepts number in a valid unsigned byte range 0-255")}if(this.buffer.byteLength>this.position){this.buffer[this.position++]=decodedByte}else{const newSpace=ByteUtils.allocate(_Binary.BUFFER_SIZE+this.buffer.length);newSpace.set(this.buffer,0);this.buffer=newSpace;this.buffer[this.position++]=decodedByte}}write(sequence,offset){offset=typeof offset==="number"?offset:this.position;if(this.buffer.byteLengththis.position?offset+sequence.length:this.position}else if(typeof sequence==="string"){const bytes=ByteUtils.fromISO88591(sequence);this.buffer.set(bytes,offset);this.position=offset+sequence.length>this.position?offset+sequence.length:this.position}}read(position,length){length=length&&length>0?length:this.position;return this.buffer.slice(position,position+length)}value(asRaw){asRaw=!!asRaw;if(asRaw&&this.buffer.length===this.position){return this.buffer}if(asRaw){return this.buffer.slice(0,this.position)}return ByteUtils.toISO88591(this.buffer.subarray(0,this.position))}length(){return this.position}toJSON(){return ByteUtils.toBase64(this.buffer)}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.buffer);if(encoding==="base64")return ByteUtils.toBase64(this.buffer);if(encoding==="utf8"||encoding==="utf-8")return ByteUtils.toUTF8(this.buffer);return ByteUtils.toUTF8(this.buffer)}toExtendedJSON(options){options=options||{};const base64String=ByteUtils.toBase64(this.buffer);const subType=Number(this.sub_type).toString(16);if(options.legacy){return{$binary:base64String,$type:subType.length===1?"0"+subType:subType}}return{$binary:{base64:base64String,subType:subType.length===1?"0"+subType:subType}}}toUUID(){if(this.sub_type===_Binary.SUBTYPE_UUID){return new UUID(this.buffer.slice(0,this.position))}throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`)}static fromExtendedJSON(doc,options){options=options||{};let data;let type;if("$binary"in doc){if(options.legacy&&typeof doc.$binary==="string"&&"$type"in doc){type=doc.$type?parseInt(doc.$type,16):0;data=ByteUtils.fromBase64(doc.$binary)}else{if(typeof doc.$binary!=="string"){type=doc.$binary.subType?parseInt(doc.$binary.subType,16):0;data=ByteUtils.fromBase64(doc.$binary.base64)}}}else if("$uuid"in doc){type=4;data=uuidHexStringToBuffer(doc.$uuid)}if(!data){throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`)}return type===BSON_BINARY_SUBTYPE_UUID_NEW?new UUID(data):new _Binary(data,type)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`}};Binary.BSON_BINARY_SUBTYPE_DEFAULT=0;Binary.BUFFER_SIZE=256;Binary.SUBTYPE_DEFAULT=0;Binary.SUBTYPE_FUNCTION=1;Binary.SUBTYPE_BYTE_ARRAY=2;Binary.SUBTYPE_UUID_OLD=3;Binary.SUBTYPE_UUID=4;Binary.SUBTYPE_MD5=5;Binary.SUBTYPE_ENCRYPTED=6;Binary.SUBTYPE_COLUMN=7;Binary.SUBTYPE_USER_DEFINED=128;var UUID_BYTE_LENGTH=16;var UUID=class _UUID extends Binary{constructor(input){let bytes;let hexStr;if(input==null){bytes=_UUID.generate()}else if(input instanceof _UUID){bytes=ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));hexStr=input.__id}else if(ArrayBuffer.isView(input)&&input.byteLength===UUID_BYTE_LENGTH){bytes=ByteUtils.toLocalBufferType(input)}else if(typeof input==="string"){bytes=uuidHexStringToBuffer(input)}else{throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).")}super(bytes,BSON_BINARY_SUBTYPE_UUID_NEW);this.__id=hexStr}get id(){return this.buffer}set id(value){this.buffer=value;if(_UUID.cacheHexString){this.__id=bufferToUuidHexString(value)}}toHexString(includeDashes=true){if(_UUID.cacheHexString&&this.__id){return this.__id}const uuidHexString=bufferToUuidHexString(this.id,includeDashes);if(_UUID.cacheHexString){this.__id=uuidHexString}return uuidHexString}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.id);if(encoding==="base64")return ByteUtils.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(!otherId){return false}if(otherId instanceof _UUID){return ByteUtils.equals(otherId.id,this.id)}try{return ByteUtils.equals(new _UUID(otherId).id,this.id)}catch{return false}}toBinary(){return new Binary(this.id,Binary.SUBTYPE_UUID)}static generate(){const bytes=ByteUtils.randomBytes(UUID_BYTE_LENGTH);bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return bytes}static isValid(input){if(!input){return false}if(input instanceof _UUID){return true}if(typeof input==="string"){return uuidValidateString(input)}if(isUint8Array(input)){if(input.byteLength!==UUID_BYTE_LENGTH){return false}return(input[6]&240)===64&&(input[8]&128)===128}return false}static createFromHexString(hexString){const buffer2=uuidHexStringToBuffer(hexString);return new _UUID(buffer2)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new UUID("${this.toHexString()}")`}};var Code=class _Code extends BSONValue{get _bsontype(){return"Code"}constructor(code,scope){super();this.code=code.toString();this.scope=scope??null}toJSON(){if(this.scope!=null){return{code:this.code,scope:this.scope}}return{code:this.code}}toExtendedJSON(){if(this.scope){return{$code:this.code,$scope:this.scope}}return{$code:this.code}}static fromExtendedJSON(doc){return new _Code(doc.$code,doc.$scope)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const codeJson=this.toJSON();return`new Code("${String(codeJson.code)}"${codeJson.scope!=null?`, ${JSON.stringify(codeJson.scope)}`:""})`}};function isDBRefLike(value){return value!=null&&typeof value==="object"&&"$id"in value&&value.$id!=null&&"$ref"in value&&typeof value.$ref==="string"&&(!("$db"in value)||"$db"in value&&typeof value.$db==="string")}var DBRef=class _DBRef extends BSONValue{get _bsontype(){return"DBRef"}constructor(collection,oid,db,fields){super();const parts=collection.split(".");if(parts.length===2){db=parts.shift();collection=parts.shift()}this.collection=collection;this.oid=oid;this.db=db;this.fields=fields||{}}get namespace(){return this.collection}set namespace(value){this.collection=value}toJSON(){const o=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)o.$db=this.db;return o}toExtendedJSON(options){options=options||{};let o={$ref:this.collection,$id:this.oid};if(options.legacy){return o}if(this.db)o.$db=this.db;o=Object.assign(o,this.fields);return o}static fromExtendedJSON(doc){const copy=Object.assign({},doc);delete copy.$ref;delete copy.$id;delete copy.$db;return new _DBRef(doc.$ref,doc.$id,doc.$db,copy)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const oid=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return`new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db?`, "${this.db}"`:""})`}};var wasm=void 0;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var TWO_PWR_16_DBL=1<<16;var TWO_PWR_24_DBL=1<<24;var TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL;var TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL;var TWO_PWR_63_DBL=TWO_PWR_64_DBL/2;var INT_CACHE={};var UINT_CACHE={};var MAX_INT64_STRING_LENGTH=20;var DECIMAL_REG_EX=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;var Long=class _Long extends BSONValue{get _bsontype(){return"Long"}get __isLong__(){return true}constructor(low=0,high,unsigned){super();if(typeof low==="bigint"){Object.assign(this,_Long.fromBigInt(low,!!high))}else if(typeof low==="string"){Object.assign(this,_Long.fromString(low,!!high))}else{this.low=low|0;this.high=high|0;this.unsigned=!!unsigned}}static fromBits(lowBits,highBits,unsigned){return new _Long(lowBits,highBits,unsigned)}static fromInt(value,unsigned){let obj,cachedObj,cache;if(unsigned){value>>>=0;if(cache=0<=value&&value<256){cachedObj=UINT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,(value|0)<0?-1:0,true);if(cache)UINT_CACHE[value]=obj;return obj}else{value|=0;if(cache=-128<=value&&value<128){cachedObj=INT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,value<0?-1:0,false);if(cache)INT_CACHE[value]=obj;return obj}}static fromNumber(value,unsigned){if(isNaN(value))return unsigned?_Long.UZERO:_Long.ZERO;if(unsigned){if(value<0)return _Long.UZERO;if(value>=TWO_PWR_64_DBL)return _Long.MAX_UNSIGNED_VALUE}else{if(value<=-TWO_PWR_63_DBL)return _Long.MIN_VALUE;if(value+1>=TWO_PWR_63_DBL)return _Long.MAX_VALUE}if(value<0)return _Long.fromNumber(-value,unsigned).neg();return _Long.fromBits(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0,unsigned)}static fromBigInt(value,unsigned){return _Long.fromString(value.toString(),unsigned)}static fromString(str2,unsigned,radix){if(str2.length===0)throw new BSONError("empty string");if(str2==="NaN"||str2==="Infinity"||str2==="+Infinity"||str2==="-Infinity")return _Long.ZERO;if(typeof unsigned==="number"){radix=unsigned,unsigned=false}else{unsigned=!!unsigned}radix=radix||10;if(radix<2||360)throw new BSONError("interior hyphen");else if(p2===0){return _Long.fromString(str2.substring(1),unsigned,radix).neg()}const radixToPower=_Long.fromNumber(Math.pow(radix,8));let result=_Long.ZERO;for(let i=0;i>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=addend.high>>>16;const b32=addend.high&65535;const b16=addend.low>>>16;const b00=addend.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}and(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low&other.low,this.high&other.high,this.unsigned)}compare(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.eq(other))return 0;const thisNeg=this.isNegative(),otherNeg=other.isNegative();if(thisNeg&&!otherNeg)return-1;if(!thisNeg&&otherNeg)return 1;if(!this.unsigned)return this.sub(other).isNegative()?-1:1;return other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}comp(other){return this.compare(other)}divide(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(divisor.isZero())throw new BSONError("division by zero");if(wasm){if(!this.unsigned&&this.high===-2147483648&&divisor.low===-1&&divisor.high===-1){return this}const low=(this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?_Long.UZERO:_Long.ZERO;let approx,rem,res;if(!this.unsigned){if(this.eq(_Long.MIN_VALUE)){if(divisor.eq(_Long.ONE)||divisor.eq(_Long.NEG_ONE))return _Long.MIN_VALUE;else if(divisor.eq(_Long.MIN_VALUE))return _Long.ONE;else{const halfThis=this.shr(1);approx=halfThis.div(divisor).shl(1);if(approx.eq(_Long.ZERO)){return divisor.isNegative()?_Long.ONE:_Long.NEG_ONE}else{rem=this.sub(divisor.mul(approx));res=approx.add(rem.div(divisor));return res}}}else if(divisor.eq(_Long.MIN_VALUE))return this.unsigned?_Long.UZERO:_Long.ZERO;if(this.isNegative()){if(divisor.isNegative())return this.neg().div(divisor.neg());return this.neg().div(divisor).neg()}else if(divisor.isNegative())return this.div(divisor.neg()).neg();res=_Long.ZERO}else{if(!divisor.unsigned)divisor=divisor.toUnsigned();if(divisor.gt(this))return _Long.UZERO;if(divisor.gt(this.shru(1)))return _Long.UONE;res=_Long.UZERO}rem=this;while(rem.gte(divisor)){approx=Math.max(1,Math.floor(rem.toNumber()/divisor.toNumber()));const log2=Math.ceil(Math.log(approx)/Math.LN2);const delta=log2<=48?1:Math.pow(2,log2-48);let approxRes=_Long.fromNumber(approx);let approxRem=approxRes.mul(divisor);while(approxRem.isNegative()||approxRem.gt(rem)){approx-=delta;approxRes=_Long.fromNumber(approx,this.unsigned);approxRem=approxRes.mul(divisor)}if(approxRes.isZero())approxRes=_Long.ONE;res=res.add(approxRes);rem=rem.sub(approxRem)}return res}div(divisor){return this.divide(divisor)}equals(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.unsigned!==other.unsigned&&this.high>>>31===1&&other.high>>>31===1)return false;return this.high===other.high&&this.low===other.low}eq(other){return this.equals(other)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative()){return this.eq(_Long.MIN_VALUE)?64:this.neg().getNumBitsAbs()}const val=this.high!==0?this.high:this.low;let bit;for(bit=31;bit>0;bit--)if((val&1<0}gt(other){return this.greaterThan(other)}greaterThanOrEqual(other){return this.comp(other)>=0}gte(other){return this.greaterThanOrEqual(other)}ge(other){return this.greaterThanOrEqual(other)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(other){return this.comp(other)<0}lt(other){return this.lessThan(other)}lessThanOrEqual(other){return this.comp(other)<=0}lte(other){return this.lessThanOrEqual(other)}modulo(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(wasm){const low=(this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}return this.sub(this.div(divisor).mul(divisor))}mod(divisor){return this.modulo(divisor)}rem(divisor){return this.modulo(divisor)}multiply(multiplier){if(this.isZero())return _Long.ZERO;if(!_Long.isLong(multiplier))multiplier=_Long.fromValue(multiplier);if(wasm){const low=wasm.mul(this.low,this.high,multiplier.low,multiplier.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(multiplier.isZero())return _Long.ZERO;if(this.eq(_Long.MIN_VALUE))return multiplier.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(multiplier.eq(_Long.MIN_VALUE))return this.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(this.isNegative()){if(multiplier.isNegative())return this.neg().mul(multiplier.neg());else return this.neg().mul(multiplier).neg()}else if(multiplier.isNegative())return this.mul(multiplier.neg()).neg();if(this.lt(_Long.TWO_PWR_24)&&multiplier.lt(_Long.TWO_PWR_24))return _Long.fromNumber(this.toNumber()*multiplier.toNumber(),this.unsigned);const a48=this.high>>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=multiplier.high>>>16;const b32=multiplier.high&65535;const b16=multiplier.low>>>16;const b00=multiplier.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}mul(multiplier){return this.multiply(multiplier)}negate(){if(!this.unsigned&&this.eq(_Long.MIN_VALUE))return _Long.MIN_VALUE;return this.not().add(_Long.ONE)}neg(){return this.negate()}not(){return _Long.fromBits(~this.low,~this.high,this.unsigned)}notEquals(other){return!this.equals(other)}neq(other){return this.notEquals(other)}ne(other){return this.notEquals(other)}or(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low|other.low,this.high|other.high,this.unsigned)}shiftLeft(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();if((numBits&=63)===0)return this;else if(numBits<32)return _Long.fromBits(this.low<>>32-numBits,this.unsigned);else return _Long.fromBits(0,this.low<>>numBits|this.high<<32-numBits,this.high>>numBits,this.unsigned);else return _Long.fromBits(this.high>>numBits-32,this.high>=0?0:-1,this.unsigned)}shr(numBits){return this.shiftRight(numBits)}shiftRightUnsigned(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();numBits&=63;if(numBits===0)return this;else{const high=this.high;if(numBits<32){const low=this.low;return _Long.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits,this.unsigned)}else if(numBits===32)return _Long.fromBits(high,0,this.unsigned);else return _Long.fromBits(high>>>numBits-32,0,this.unsigned)}}shr_u(numBits){return this.shiftRightUnsigned(numBits)}shru(numBits){return this.shiftRightUnsigned(numBits)}subtract(subtrahend){if(!_Long.isLong(subtrahend))subtrahend=_Long.fromValue(subtrahend);return this.add(subtrahend.neg())}sub(subtrahend){return this.subtract(subtrahend)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0);return this.high*TWO_PWR_32_DBL+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(le){return le?this.toBytesLE():this.toBytesBE()}toBytesLE(){const hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}toBytesBE(){const hi=this.high,lo=this.low;return[hi>>>24,hi>>>16&255,hi>>>8&255,hi&255,lo>>>24,lo>>>16&255,lo>>>8&255,lo&255]}toSigned(){if(!this.unsigned)return this;return _Long.fromBits(this.low,this.high,false)}toString(radix){radix=radix||10;if(radix<2||36>>0;let digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6)digits="0"+digits;result=""+digits+result}}}toUnsigned(){if(this.unsigned)return this;return _Long.fromBits(this.low,this.high,true)}xor(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low^other.low,this.high^other.high,this.unsigned)}eqz(){return this.isZero()}le(other){return this.lessThanOrEqual(other)}toExtendedJSON(options){if(options&&options.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(doc,options){const{useBigInt64=false,relaxed=true}={...options};if(doc.$numberLong.length>MAX_INT64_STRING_LENGTH){throw new BSONError("$numberLong string is too long")}if(!DECIMAL_REG_EX.test(doc.$numberLong)){throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`)}if(useBigInt64){const bigIntResult=BigInt(doc.$numberLong);return BigInt.asIntN(64,bigIntResult)}const longResult=_Long.fromString(doc.$numberLong);if(relaxed){return longResult.toNumber()}return longResult}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Long("${this.toString()}"${this.unsigned?", true":""})`}};Long.TWO_PWR_24=Long.fromInt(TWO_PWR_24_DBL);Long.MAX_UNSIGNED_VALUE=Long.fromBits(4294967295|0,4294967295|0,true);Long.ZERO=Long.fromInt(0);Long.UZERO=Long.fromInt(0,true);Long.ONE=Long.fromInt(1);Long.UONE=Long.fromInt(1,true);Long.NEG_ONE=Long.fromInt(-1);Long.MAX_VALUE=Long.fromBits(4294967295|0,2147483647|0,false);Long.MIN_VALUE=Long.fromBits(0,2147483648|0,false);var PARSE_STRING_REGEXP=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var PARSE_INF_REGEXP=/^(\+|-)?(Infinity|inf)$/i;var PARSE_NAN_REGEXP=/^(\+|-)?NaN$/i;var EXPONENT_MAX=6111;var EXPONENT_MIN=-6176;var EXPONENT_BIAS=6176;var MAX_DIGITS=34;var NAN_BUFFER=ByteUtils.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_NEGATIVE_BUFFER=ByteUtils.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_POSITIVE_BUFFER=ByteUtils.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var EXPONENT_REGEX=/^([-+])?(\d+)?$/;var COMBINATION_MASK=31;var EXPONENT_MASK=16383;var COMBINATION_INFINITY=30;var COMBINATION_NAN=31;function isDigit(value){return!isNaN(parseInt(value,10))}function divideu128(value){const DIVISOR=Long.fromNumber(1e3*1e3*1e3);let _rem=Long.fromNumber(0);if(!value.parts[0]&&!value.parts[1]&&!value.parts[2]&&!value.parts[3]){return{quotient:value,rem:_rem}}for(let i=0;i<=3;i++){_rem=_rem.shiftLeft(32);_rem=_rem.add(new Long(value.parts[i],0));value.parts[i]=_rem.div(DIVISOR).low;_rem=_rem.modulo(DIVISOR)}return{quotient:value,rem:_rem}}function multiply64x2(left,right){if(!left&&!right){return{high:Long.fromNumber(0),low:Long.fromNumber(0)}}const leftHigh=left.shiftRightUnsigned(32);const leftLow=new Long(left.getLowBits(),0);const rightHigh=right.shiftRightUnsigned(32);const rightLow=new Long(right.getLowBits(),0);let productHigh=leftHigh.multiply(rightHigh);let productMid=leftHigh.multiply(rightLow);const productMid2=leftLow.multiply(rightHigh);let productLow=leftLow.multiply(rightLow);productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productMid=new Long(productMid.getLowBits(),0).add(productMid2).add(productLow.shiftRightUnsigned(32));productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productLow=productMid.shiftLeft(32).add(new Long(productLow.getLowBits(),0));return{high:productHigh,low:productLow}}function lessThan(left,right){const uhleft=left.high>>>0;const uhright=right.high>>>0;if(uhleft>>0;const ulright=right.low>>>0;if(ulleft=7e3){throw new BSONError(""+representation+" not a valid Decimal128 string")}const stringMatch=representation.match(PARSE_STRING_REGEXP);const infMatch=representation.match(PARSE_INF_REGEXP);const nanMatch=representation.match(PARSE_NAN_REGEXP);if(!stringMatch&&!infMatch&&!nanMatch||representation.length===0){throw new BSONError(""+representation+" not a valid Decimal128 string")}if(stringMatch){const unsignedNumber=stringMatch[2];const e=stringMatch[4];const expSign=stringMatch[5];const expNumber=stringMatch[6];if(e&&expNumber===void 0)invalidErr(representation,"missing exponent power");if(e&&unsignedNumber===void 0)invalidErr(representation,"missing exponent base");if(e===void 0&&(expSign||expNumber)){invalidErr(representation,"missing e before exponent")}}if(representation[index]==="+"||representation[index]==="-"){isNegative=representation[index++]==="-"}if(!isDigit(representation[index])&&representation[index]!=="."){if(representation[index]==="i"||representation[index]==="I"){return new _Decimal128(isNegative?INF_NEGATIVE_BUFFER:INF_POSITIVE_BUFFER)}else if(representation[index]==="N"){return new _Decimal128(NAN_BUFFER)}}while(isDigit(representation[index])||representation[index]==="."){if(representation[index]==="."){if(sawRadix)invalidErr(representation,"contains multiple periods");sawRadix=true;index=index+1;continue}if(nDigitsStored<34){if(representation[index]!=="0"||foundNonZero){if(!foundNonZero){firstNonZero=nDigitsRead}foundNonZero=true;digits[digitsInsert++]=parseInt(representation[index],10);nDigitsStored=nDigitsStored+1}}if(foundNonZero)nDigits=nDigits+1;if(sawRadix)radixPosition=radixPosition+1;nDigitsRead=nDigitsRead+1;index=index+1}if(sawRadix&&!nDigitsRead)throw new BSONError(""+representation+" not a valid Decimal128 string");if(representation[index]==="e"||representation[index]==="E"){const match=representation.substr(++index).match(EXPONENT_REGEX);if(!match||!match[2])return new _Decimal128(NAN_BUFFER);exponent=parseInt(match[0],10);index=index+match[0].length}if(representation[index])return new _Decimal128(NAN_BUFFER);firstDigit=0;if(!nDigitsStored){firstDigit=0;lastDigit=0;digits[0]=0;nDigits=1;nDigitsStored=1;significantDigits=0}else{lastDigit=nDigitsStored-1;significantDigits=nDigits;if(significantDigits!==1){while(digits[firstNonZero+significantDigits-1]===0){significantDigits=significantDigits-1}}}if(exponent<=radixPosition&&radixPosition-exponent>1<<14){exponent=EXPONENT_MIN}else{exponent=exponent-radixPosition}while(exponent>EXPONENT_MAX){lastDigit=lastDigit+1;if(lastDigit-firstDigit>MAX_DIGITS){const digitsString=digits.join("");if(digitsString.match(/^0+$/)){exponent=EXPONENT_MAX;break}invalidErr(representation,"overflow")}exponent=exponent-1}while(exponent=5){roundBit=1;if(roundDigit===5){roundBit=digits[lastDigit]%2===1?1:0;for(i=firstNonZero+lastDigit+2;i=0;dIdx--){if(++digits[dIdx]>9){digits[dIdx]=0;if(dIdx===0){if(exponent>8&255;buffer2[index++]=dec.low.low>>16&255;buffer2[index++]=dec.low.low>>24&255;buffer2[index++]=dec.low.high&255;buffer2[index++]=dec.low.high>>8&255;buffer2[index++]=dec.low.high>>16&255;buffer2[index++]=dec.low.high>>24&255;buffer2[index++]=dec.high.low&255;buffer2[index++]=dec.high.low>>8&255;buffer2[index++]=dec.high.low>>16&255;buffer2[index++]=dec.high.low>>24&255;buffer2[index++]=dec.high.high&255;buffer2[index++]=dec.high.high>>8&255;buffer2[index++]=dec.high.high>>16&255;buffer2[index++]=dec.high.high>>24&255;return new _Decimal128(buffer2)}toString(){let biased_exponent;let significand_digits=0;const significand=new Array(36);for(let i=0;i>26&COMBINATION_MASK;if(combination>>3===3){if(combination===COMBINATION_INFINITY){return string.join("")+"Infinity"}else if(combination===COMBINATION_NAN){return"NaN"}else{biased_exponent=high>>15&EXPONENT_MASK;significand_msb=8+(high>>14&1)}}else{significand_msb=high>>14&7;biased_exponent=high>>17&EXPONENT_MASK}const exponent=biased_exponent-EXPONENT_BIAS;significand128.parts[0]=(high&16383)+((significand_msb&15)<<14);significand128.parts[1]=midh;significand128.parts[2]=midl;significand128.parts[3]=low;if(significand128.parts[0]===0&&significand128.parts[1]===0&&significand128.parts[2]===0&&significand128.parts[3]===0){is_zero=true}else{for(k=3;k>=0;k--){let least_digits=0;const result=divideu128(significand128);significand128=result.quotient;least_digits=result.rem.low;if(!least_digits)continue;for(j=8;j>=0;j--){significand[k*9+j]=least_digits%10;least_digits=Math.floor(least_digits/10)}}}if(is_zero){significand_digits=1;significand[index]=0}else{significand_digits=36;while(!significand[index]){significand_digits=significand_digits-1;index=index+1}}const scientific_exponent=significand_digits-1+exponent;if(scientific_exponent>=34||scientific_exponent<=-7||exponent>0){if(significand_digits>34){string.push(`${0}`);if(exponent>0)string.push(`E+${exponent}`);else if(exponent<0)string.push(`E${exponent}`);return string.join("")}string.push(`${significand[index++]}`);significand_digits=significand_digits-1;if(significand_digits){string.push(".")}for(let i=0;i0){string.push(`+${scientific_exponent}`)}else{string.push(`${scientific_exponent}`)}}else{if(exponent>=0){for(let i=0;i0){for(let i=0;i>8&255;buffer2[9]=inc>>16&255;return buffer2}toString(encoding){if(encoding==="base64")return ByteUtils.toBase64(this.id);if(encoding==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(otherId===void 0||otherId===null){return false}if(otherId instanceof _ObjectId){return this[kId][11]===otherId[kId][11]&&ByteUtils.equals(this[kId],otherId[kId])}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12&&isUint8Array(this.id)){return ByteUtils.equals(this.id,ByteUtils.fromISO88591(otherId))}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===24){return otherId.toLowerCase()===this.toHexString()}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12){return ByteUtils.equals(ByteUtils.fromUTF8(otherId),this.id)}if(typeof otherId==="object"&&"toHexString"in otherId&&typeof otherId.toHexString==="function"){const otherIdString=otherId.toHexString();const thisIdString=this.toHexString().toLowerCase();return typeof otherIdString==="string"&&otherIdString.toLowerCase()===thisIdString}return false}getTimestamp(){const timestamp=new Date;const time=BSONDataView.fromUint8Array(this.id).getUint32(0,false);timestamp.setTime(Math.floor(time)*1e3);return timestamp}static createPk(){return new _ObjectId}static createFromTime(time){const buffer2=ByteUtils.fromNumberArray([0,0,0,0,0,0,0,0,0,0,0,0]);BSONDataView.fromUint8Array(buffer2).setUint32(0,time,false);return new _ObjectId(buffer2)}static createFromHexString(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new BSONError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}return new _ObjectId(ByteUtils.fromHex(hexString))}static isValid(id){if(id==null)return false;try{new _ObjectId(id);return true}catch{return false}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(doc){return new _ObjectId(doc.$oid)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new ObjectId("${this.toHexString()}")`}};ObjectId2.index=Math.floor(Math.random()*16777215);function internalCalculateObjectSize(object,serializeFunctions,ignoreUndefined){let totalLength=4+1;if(Array.isArray(object)){for(let i=0;i=JS_INT_MIN&&value<=JS_INT_MAX){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(4+1)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}case"undefined":if(isArray||!ignoreUndefined)return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1;return 0;case"boolean":return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+1);case"object":if(value!=null&&typeof value._bsontype==="string"&&value[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(value==null||value._bsontype==="MinKey"||value._bsontype==="MaxKey"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1}else if(value._bsontype==="ObjectId"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(12+1)}else if(value instanceof Date||isDate(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(ArrayBuffer.isView(value)||value instanceof ArrayBuffer||isAnyArrayBuffer(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+4+1)+value.byteLength}else if(value._bsontype==="Long"||value._bsontype==="Double"||value._bsontype==="Timestamp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(value._bsontype==="Decimal128"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(16+1)}else if(value._bsontype==="Code"){if(value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+4+ByteUtils.utf8ByteLength(value.code.toString())+1+internalCalculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.code.toString())+1}}else if(value._bsontype==="Binary"){const binary=value;if(binary.sub_type===Binary.SUBTYPE_BYTE_ARRAY){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1+4)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1)}}else if(value._bsontype==="Symbol"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+ByteUtils.utf8ByteLength(value.value)+4+1+1}else if(value._bsontype==="DBRef"){const ordered_values=Object.assign({$ref:value.collection,$id:value.oid},value.fields);if(value.db!=null){ordered_values["$db"]=value.db}return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+internalCalculateObjectSize(ordered_values,serializeFunctions,ignoreUndefined)}else if(value instanceof RegExp||isRegExp(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.source)+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else if(value._bsontype==="BSONRegExp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.pattern)+1+ByteUtils.utf8ByteLength(value.options)+1}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+internalCalculateObjectSize(value,serializeFunctions,ignoreUndefined)+1}case"function":if(serializeFunctions){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.toString())+1}}return 0}function alphabetize(str2){return str2.split("").sort().join("")}var BSONRegExp=class _BSONRegExp extends BSONValue{get _bsontype(){return"BSONRegExp"}constructor(pattern,options){super();this.pattern=pattern;this.options=alphabetize(options??"");if(this.pattern.indexOf("\0")!==-1){throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`)}if(this.options.indexOf("\0")!==-1){throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`)}for(let i=0;i4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max")}if(low.i>4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max")}super(low.i.valueOf(),low.t.valueOf(),true)}else{throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}}toJSON(){return{$timestamp:this.toString()}}static fromInt(value){return new _Timestamp(Long.fromInt(value,true))}static fromNumber(value){return new _Timestamp(Long.fromNumber(value,true))}static fromBits(lowBits,highBits){return new _Timestamp({i:lowBits,t:highBits})}static fromString(str2,optRadix){return new _Timestamp(Long.fromString(str2,true,optRadix))}toExtendedJSON(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}}static fromExtendedJSON(doc){const i=Long.isLong(doc.$timestamp.i)?doc.$timestamp.i.getLowBitsUnsigned():doc.$timestamp.i;const t=Long.isLong(doc.$timestamp.t)?doc.$timestamp.t.getLowBitsUnsigned():doc.$timestamp.t;return new _Timestamp({t,i})}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`}};Timestamp.MAX_VALUE=Long.MAX_UNSIGNED_VALUE;var FIRST_BIT=128;var FIRST_TWO_BITS=192;var FIRST_THREE_BITS=224;var FIRST_FOUR_BITS=240;var FIRST_FIVE_BITS=248;var TWO_BIT_CHAR=192;var THREE_BIT_CHAR=224;var FOUR_BIT_CHAR=240;var CONTINUING_CHAR=128;function validateUtf8(bytes,start,end){let continuation=0;for(let i=start;i= 5, is ${size}`)}if(options.allowObjectSmallerThanBufferSize&&buffer2.length= bson size ${size}`)}if(!options.allowObjectSmallerThanBufferSize&&buffer2.length!==size){throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`)}if(size+index>buffer2.byteLength){throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`)}if(buffer2[index+size-1]!==0){throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(buffer2,index,options,isArray)}var allowedDBRefKeys=/^\$ref$|^\$id$|^\$db$/;function deserializeObject(buffer2,index,options,isArray=false){const fieldsAsRaw=options["fieldsAsRaw"]==null?null:options["fieldsAsRaw"];const raw=options["raw"]==null?false:options["raw"];const bsonRegExp=typeof options["bsonRegExp"]==="boolean"?options["bsonRegExp"]:false;const promoteBuffers=options.promoteBuffers??false;const promoteLongs=options.promoteLongs??true;const promoteValues=options.promoteValues??true;const useBigInt64=options.useBigInt64??false;if(useBigInt64&&!promoteValues){throw new BSONError("Must either request bigint or Long for int64 deserialization")}if(useBigInt64&&!promoteLongs){throw new BSONError("Must either request bigint or Long for int64 deserialization")}const validation=options.validation==null?{utf8:true}:options.validation;let globalUTFValidation=true;let validationSetting;const utf8KeysSet=new Set;const utf8ValidatedKeys=validation.utf8;if(typeof utf8ValidatedKeys==="boolean"){validationSetting=utf8ValidatedKeys}else{globalUTFValidation=false;const utf8ValidationValues=Object.keys(utf8ValidatedKeys).map(function(key){return utf8ValidatedKeys[key]});if(utf8ValidationValues.length===0){throw new BSONError("UTF-8 validation setting cannot be empty")}if(typeof utf8ValidationValues[0]!=="boolean"){throw new BSONError("Invalid UTF-8 validation option, must specify boolean values")}validationSetting=utf8ValidationValues[0];if(!utf8ValidationValues.every(item=>item===validationSetting)){throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}}if(!globalUTFValidation){for(const key of Object.keys(utf8ValidatedKeys)){utf8KeysSet.add(key)}}const startIndex=index;if(buffer2.length<5)throw new BSONError("corrupt bson message < 5 bytes long");const size=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(size<5||size>buffer2.length)throw new BSONError("corrupt bson message");const object=isArray?[]:{};let arrayIndex=0;const done=false;let isPossibleDBRef=isArray?false:null;const dataview=new DataView(buffer2.buffer,buffer2.byteOffset,buffer2.byteLength);while(!done){const elementType=buffer2[index++];if(elementType===0)break;let i=index;while(buffer2[i]!==0&&i=buffer2.byteLength)throw new BSONError("Bad BSON Document: illegal CString");const name=isArray?arrayIndex++:ByteUtils.toUTF8(buffer2.subarray(index,i));let shouldValidateKey=true;if(globalUTFValidation||utf8KeysSet.has(name)){shouldValidateKey=validationSetting}else{shouldValidateKey=!validationSetting}if(isPossibleDBRef!==false&&name[0]==="$"){isPossibleDBRef=allowedDBRefKeys.test(name)}let value;index=i+1;if(elementType===BSON_DATA_STRING){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}value=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize}else if(elementType===BSON_DATA_OID){const oid=ByteUtils.allocate(12);oid.set(buffer2.subarray(index,index+12));value=new ObjectId2(oid);index=index+12}else if(elementType===BSON_DATA_INT&&promoteValues===false){value=new Int32(buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24)}else if(elementType===BSON_DATA_INT){value=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24}else if(elementType===BSON_DATA_NUMBER&&promoteValues===false){value=new Double(dataview.getFloat64(index,true));index=index+8}else if(elementType===BSON_DATA_NUMBER){value=dataview.getFloat64(index,true);index=index+8}else if(elementType===BSON_DATA_DATE){const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;value=new Date(new Long(lowBits,highBits).toNumber())}else if(elementType===BSON_DATA_BOOLEAN){if(buffer2[index]!==0&&buffer2[index]!==1)throw new BSONError("illegal boolean type value");value=buffer2[index++]===1}else if(elementType===BSON_DATA_OBJECT){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;if(objectSize<=0||objectSize>buffer2.length-index)throw new BSONError("bad embedded document length in bson");if(raw){value=buffer2.slice(index,index+objectSize)}else{let objectOptions=options;if(!globalUTFValidation){objectOptions={...options,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,objectOptions,false)}index=index+objectSize}else if(elementType===BSON_DATA_ARRAY){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;let arrayOptions=options;const stopIndex=index+objectSize;if(fieldsAsRaw&&fieldsAsRaw[name]){arrayOptions={...options,raw:true}}if(!globalUTFValidation){arrayOptions={...arrayOptions,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,arrayOptions,true);index=index+objectSize;if(buffer2[index-1]!==0)throw new BSONError("invalid array terminator byte");if(index!==stopIndex)throw new BSONError("corrupted array bson")}else if(elementType===BSON_DATA_UNDEFINED){value=void 0}else if(elementType===BSON_DATA_NULL){value=null}else if(elementType===BSON_DATA_LONG){const dataview2=BSONDataView.fromUint8Array(buffer2.subarray(index,index+8));const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const long=new Long(lowBits,highBits);if(useBigInt64){value=dataview2.getBigInt64(0,true)}else if(promoteLongs&&promoteValues===true){value=long.lessThanOrEqual(JS_INT_MAX_LONG)&&long.greaterThanOrEqual(JS_INT_MIN_LONG)?long.toNumber():long}else{value=long}}else if(elementType===BSON_DATA_DECIMAL128){const bytes=ByteUtils.allocate(16);bytes.set(buffer2.subarray(index,index+16),0);index=index+16;value=new Decimal128(bytes)}else if(elementType===BSON_DATA_BINARY){let binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const totalBinarySize=binarySize;const subType=buffer2[index++];if(binarySize<0)throw new BSONError("Negative binary type element size found");if(binarySize>buffer2.byteLength)throw new BSONError("Binary type size larger than document size");if(buffer2["slice"]!=null){if(subType===Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(binarySize<0)throw new BSONError("Negative binary type element size found for subtype 0x02");if(binarySize>totalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySizetotalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySize=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;const optionsArray=new Array(regExpOptions.length);for(i=0;i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;value=new BSONRegExp(source,regExpOptions)}else if(elementType===BSON_DATA_SYMBOL){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const symbol=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=promoteValues?symbol:new BSONSymbol(symbol);index=index+stringSize}else if(elementType===BSON_DATA_TIMESTAMP){const i2=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);const t=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);value=new Timestamp({i:i2,t})}else if(elementType===BSON_DATA_MIN_KEY){value=new MinKey}else if(elementType===BSON_DATA_MAX_KEY){value=new MaxKey}else if(elementType===BSON_DATA_CODE){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=new Code(functionString);index=index+stringSize}else if(elementType===BSON_DATA_CODE_W_SCOPE){const totalSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(totalSize<4+4+4+1){throw new BSONError("code_w_scope total size shorter minimum expected length")}const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize;const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;const scopeObject=deserializeObject(buffer2,_index,options,false);index=index+objectSize;if(totalSize<4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too short, truncating scope")}if(totalSize>4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too long, clips outer document")}value=new Code(functionString,scopeObject)}else if(elementType===BSON_DATA_DBPOINTER){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0)throw new BSONError("bad string length in bson");if(validation!=null&&validation.utf8){if(!validateUtf8(buffer2,index,index+stringSize-1)){throw new BSONError("Invalid UTF-8 string in BSON document")}}const namespace=ByteUtils.toUTF8(buffer2.subarray(index,index+stringSize-1));index=index+stringSize;const oidBuffer=ByteUtils.allocate(12);oidBuffer.set(buffer2.subarray(index,index+12),0);const oid=new ObjectId2(oidBuffer);index=index+12;value=new DBRef(namespace,oid)}else{throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`)}if(name==="__proto__"){Object.defineProperty(object,name,{value,writable:true,enumerable:true,configurable:true})}else{object[name]=value}}if(size!==index-startIndex){if(isArray)throw new BSONError("corrupt array bson");throw new BSONError("corrupt object bson")}if(!isPossibleDBRef)return object;if(isDBRefLike(object)){const copy=Object.assign({},object);delete copy.$ref;delete copy.$id;delete copy.$db;return new DBRef(object.$ref,object.$id,object.$db,copy)}return object}function getValidatedString(buffer2,start,end,shouldValidateUtf8){const value=ByteUtils.toUTF8(buffer2.subarray(start,end));if(shouldValidateUtf8){for(let i=0;i>24&255;buffer2[index+2]=size+1>>16&255;buffer2[index+1]=size+1>>8&255;buffer2[index]=size+1&255;index=index+4+size;buffer2[index++]=0;return index}var NUMBER_SPACE=new DataView(new ArrayBuffer(8),0,8);var FOUR_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,4);var EIGHT_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,8);function serializeNumber(buffer2,key,value,index){const isNegativeZero=Object.is(value,-0);const type=!isNegativeZero&&Number.isSafeInteger(value)&&value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN?BSON_DATA_INT:BSON_DATA_NUMBER;if(type===BSON_DATA_INT){NUMBER_SPACE.setInt32(0,value,true)}else{NUMBER_SPACE.setFloat64(0,value,true)}const bytes=type===BSON_DATA_INT?FOUR_BYTE_VIEW_ON_NUMBER:EIGHT_BYTE_VIEW_ON_NUMBER;buffer2[index++]=type;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(bytes,index);index+=bytes.byteLength;return index}function serializeBigInt(buffer2,key,value,index){buffer2[index++]=BSON_DATA_LONG;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index+=numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setBigInt64(0,value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index+=EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;return index}function serializeNull(buffer2,key,_,index){buffer2[index++]=BSON_DATA_NULL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeBoolean(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BOOLEAN;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value?1:0;return index}function serializeDate(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DATE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const dateInMilis=Long.fromNumber(value.getTime());const lowBits=dateInMilis.getLowBits();const highBits=dateInMilis.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.source&&value.source.match(regexp)!=null){throw new BSONError("value "+value.source+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.source,index);buffer2[index++]=0;if(value.ignoreCase)buffer2[index++]=105;if(value.global)buffer2[index++]=115;if(value.multiline)buffer2[index++]=109;buffer2[index++]=0;return index}function serializeBSONRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.pattern.match(regexp)!=null){throw new BSONError("pattern "+value.pattern+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.pattern,index);buffer2[index++]=0;const sortedOptions=value.options.split("").sort().join("");index=index+ByteUtils.encodeUTF8Into(buffer2,sortedOptions,index);buffer2[index++]=0;return index}function serializeMinMax(buffer2,key,value,index){if(value===null){buffer2[index++]=BSON_DATA_NULL}else if(value._bsontype==="MinKey"){buffer2[index++]=BSON_DATA_MIN_KEY}else{buffer2[index++]=BSON_DATA_MAX_KEY}const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeObjectId(buffer2,key,value,index){buffer2[index++]=BSON_DATA_OID;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(isUint8Array(value.id)){buffer2.set(value.id.subarray(0,12),index)}else{throw new BSONError("object ["+JSON.stringify(value)+"] is not a valid ObjectId")}return index+12}function serializeBuffer(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=value.length;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=BSON_BINARY_SUBTYPE_DEFAULT;buffer2.set(value,index);index=index+size;return index}function serializeObject(buffer2,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined,path){if(path.has(value)){throw new BSONError("Cannot convert circular structure to BSON")}path.add(value);buffer2[index++]=Array.isArray(value)?BSON_DATA_ARRAY:BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const endIndex=serializeInto(buffer2,value,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);path.delete(value);return endIndex}function serializeDecimal128(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DECIMAL128;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(value.bytes.subarray(0,16),index);return index+16}function serializeLong(buffer2,key,value,index){buffer2[index++]=value._bsontype==="Long"?BSON_DATA_LONG:BSON_DATA_TIMESTAMP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const lowBits=value.getLowBits();const highBits=value.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeInt32(buffer2,key,value,index){value=value.valueOf();buffer2[index++]=BSON_DATA_INT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value&255;buffer2[index++]=value>>8&255;buffer2[index++]=value>>16&255;buffer2[index++]=value>>24&255;return index}function serializeDouble(buffer2,key,value,index){buffer2[index++]=BSON_DATA_NUMBER;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setFloat64(0,value.value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index=index+8;return index}function serializeFunction(buffer2,key,value,index){buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeCode(buffer2,key,value,index,checkKeys=false,depth=0,serializeFunctions=false,ignoreUndefined=true,path){if(value.scope&&typeof value.scope==="object"){buffer2[index++]=BSON_DATA_CODE_W_SCOPE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;const functionString=value.code;index=index+4;const codeSize=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=codeSize&255;buffer2[index+1]=codeSize>>8&255;buffer2[index+2]=codeSize>>16&255;buffer2[index+3]=codeSize>>24&255;buffer2[index+4+codeSize-1]=0;index=index+codeSize+4;const endIndex=serializeInto(buffer2,value.scope,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);index=endIndex-1;const totalSize=endIndex-startIndex;buffer2[startIndex++]=totalSize&255;buffer2[startIndex++]=totalSize>>8&255;buffer2[startIndex++]=totalSize>>16&255;buffer2[startIndex++]=totalSize>>24&255;buffer2[index++]=0}else{buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.code.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0}return index}function serializeBinary(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const data=value.buffer;let size=value.position;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY)size=size+4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=value.sub_type;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY){size=size-4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255}buffer2.set(data,index);index=index+value.position;return index}function serializeSymbol(buffer2,key,value,index){buffer2[index++]=BSON_DATA_SYMBOL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=ByteUtils.encodeUTF8Into(buffer2,value.value,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeDBRef(buffer2,key,value,index,depth,serializeFunctions,path){buffer2[index++]=BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;let output={$ref:value.collection||value.namespace,$id:value.oid};if(value.db!=null){output.$db=value.db}output=Object.assign(output,value.fields);const endIndex=serializeInto(buffer2,output,false,index,depth+1,serializeFunctions,true,path);const size=endIndex-startIndex;buffer2[startIndex++]=size&255;buffer2[startIndex++]=size>>8&255;buffer2[startIndex++]=size>>16&255;buffer2[startIndex++]=size>>24&255;return endIndex}function serializeInto(buffer2,object,checkKeys,startingIndex,depth,serializeFunctions,ignoreUndefined,path){if(path==null){if(object==null){buffer2[0]=5;buffer2[1]=0;buffer2[2]=0;buffer2[3]=0;buffer2[4]=0;return 5}if(Array.isArray(object)){throw new BSONError("serialize does not support an array as the root input")}if(typeof object!=="object"){throw new BSONError("serialize does not support non-object as the root input")}else if("_bsontype"in object&&typeof object._bsontype==="string"){throw new BSONError(`BSON types cannot be serialized as a document`)}else if(isDate(object)||isRegExp(object)||isUint8Array(object)||isAnyArrayBuffer(object)){throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`)}path=new Set}path.add(object);let index=startingIndex+4;if(Array.isArray(object)){for(let i=0;i>8&255;buffer2[startingIndex++]=size>>16&255;buffer2[startingIndex++]=size>>24&255;return index}function isBSONType(value){return value!=null&&typeof value==="object"&&"_bsontype"in value&&typeof value._bsontype==="string"}var keysToCodecs={$oid:ObjectId2,$binary:Binary,$uuid:Binary,$symbol:BSONSymbol,$numberInt:Int32,$numberDecimal:Decimal128,$numberDouble:Double,$numberLong:Long,$minKey:MinKey,$maxKey:MaxKey,$regex:BSONRegExp,$regularExpression:BSONRegExp,$timestamp:Timestamp};function deserializeValue(value,options={}){if(typeof value==="number"){const in32BitRange=value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN;const in64BitRange=value<=BSON_INT64_MAX&&value>=BSON_INT64_MIN;if(options.relaxed||options.legacy){return value}if(Number.isInteger(value)&&!Object.is(value,-0)){if(in32BitRange){return new Int32(value)}if(in64BitRange){if(options.useBigInt64){return BigInt(value)}return Long.fromNumber(value)}}return new Double(value)}if(value==null||typeof value!=="object")return value;if(value.$undefined)return null;const keys=Object.keys(value).filter(k=>k.startsWith("$")&&value[k]!=null);for(let i=0;ik.startsWith("$"));let valid=true;dollarKeys.forEach(k=>{if(["$ref","$id","$db"].indexOf(k)===-1)valid=false});if(valid)return DBRef.fromExtendedJSON(v2)}return value}function serializeArray(array,options){return array.map((v2,index)=>{options.seenObjects.push({propertyName:`index ${index}`,obj:null});try{return serializeValue(v2,options)}finally{options.seenObjects.pop()}})}function getISOString(date){const isoStr=date.toISOString();return date.getUTCMilliseconds()!==0?isoStr:isoStr.slice(0,-5)+"Z"}function serializeValue(value,options){if(value instanceof Map||isMap(value)){const obj=Object.create(null);for(const[k,v2]of value){if(typeof k!=="string"){throw new BSONError("Can only serialize maps with string keys")}obj[k]=v2}return serializeValue(obj,options)}if((typeof value==="object"||typeof value==="function")&&value!==null){const index=options.seenObjects.findIndex(entry=>entry.obj===value);if(index!==-1){const props=options.seenObjects.map(entry=>entry.propertyName);const leadingPart=props.slice(0,index).map(prop=>`${prop} -> `).join("");const alreadySeen=props[index];const circularPart=" -> "+props.slice(index+1,props.length-1).map(prop=>`${prop} -> `).join("");const current=props[props.length-1];const leadingSpace=" ".repeat(leadingPart.length+alreadySeen.length/2);const dashes="-".repeat(circularPart.length+(alreadySeen.length+current.length)/2-1);throw new BSONError(`Converting circular structure to EJSON: - ${leadingPart}${alreadySeen}${circularPart}${current} - ${leadingSpace}\\${dashes}/`)}options.seenObjects[options.seenObjects.length-1].obj=value}if(Array.isArray(value))return serializeArray(value,options);if(value===void 0)return null;if(value instanceof Date||isDate(value)){const dateNum=value.getTime(),inRange=dateNum>-1&&dateNum<2534023188e5;if(options.legacy){return options.relaxed&&inRange?{$date:value.getTime()}:{$date:getISOString(value)}}return options.relaxed&&inRange?{$date:getISOString(value)}:{$date:{$numberLong:value.getTime().toString()}}}if(typeof value==="number"&&(!options.relaxed||!isFinite(value))){if(Number.isInteger(value)&&!Object.is(value,-0)){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return{$numberInt:value.toString()}}if(value>=BSON_INT64_MIN&&value<=BSON_INT64_MAX){return{$numberLong:value.toString()}}}return{$numberDouble:Object.is(value,-0)?"-0.0":value.toString()}}if(typeof value==="bigint"){if(!options.relaxed){return{$numberLong:BigInt.asIntN(64,value).toString()}}return Number(BigInt.asIntN(64,value))}if(value instanceof RegExp||isRegExp(value)){let flags=value.flags;if(flags===void 0){const match=value.toString().match(/[gimuy]*$/);if(match){flags=match[0]}}const rx=new BSONRegExp(value.source,flags);return rx.toExtendedJSON(options)}if(value!=null&&typeof value==="object")return serializeDocument(value,options);return value}var BSON_TYPE_MAPPINGS={Binary:o=>new Binary(o.value(),o.sub_type),Code:o=>new Code(o.code,o.scope),DBRef:o=>new DBRef(o.collection||o.namespace,o.oid,o.db,o.fields),Decimal128:o=>new Decimal128(o.bytes),Double:o=>new Double(o.value),Int32:o=>new Int32(o.value),Long:o=>Long.fromBits(o.low!=null?o.low:o.low_,o.low!=null?o.high:o.high_,o.low!=null?o.unsigned:o.unsigned_),MaxKey:()=>new MaxKey,MinKey:()=>new MinKey,ObjectId:o=>new ObjectId2(o),BSONRegExp:o=>new BSONRegExp(o.pattern,o.options),BSONSymbol:o=>new BSONSymbol(o.value),Timestamp:o=>Timestamp.fromBits(o.low,o.high)};function serializeDocument(doc,options){if(doc==null||typeof doc!=="object")throw new BSONError("not an object instance");const bsontype=doc._bsontype;if(typeof bsontype==="undefined"){const _doc={};for(const name of Object.keys(doc)){options.seenObjects.push({propertyName:name,obj:null});try{const value=serializeValue(doc[name],options);if(name==="__proto__"){Object.defineProperty(_doc,name,{value,writable:true,enumerable:true,configurable:true})}else{_doc[name]=value}}finally{options.seenObjects.pop()}}return _doc}else if(doc!=null&&typeof doc==="object"&&typeof doc._bsontype==="string"&&doc[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(isBSONType(doc)){let outDoc=doc;if(typeof outDoc.toExtendedJSON!=="function"){const mapper=BSON_TYPE_MAPPINGS[doc._bsontype];if(!mapper){throw new BSONError("Unrecognized or invalid _bsontype: "+doc._bsontype)}outDoc=mapper(outDoc)}if(bsontype==="Code"&&outDoc.scope){outDoc=new Code(outDoc.code,serializeValue(outDoc.scope,options))}else if(bsontype==="DBRef"&&outDoc.oid){outDoc=new DBRef(serializeValue(outDoc.collection,options),serializeValue(outDoc.oid,options),serializeValue(outDoc.db,options),serializeValue(outDoc.fields,options))}return outDoc.toExtendedJSON(options)}else{throw new BSONError("_bsontype must be a string, but was: "+typeof bsontype)}}function parse(text,options){const ejsonOptions={useBigInt64:options?.useBigInt64??false,relaxed:options?.relaxed??true,legacy:options?.legacy??false};return JSON.parse(text,(key,value)=>{if(key.indexOf("\0")!==-1){throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`)}return deserializeValue(value,ejsonOptions)})}function stringify(value,replacer,space,options){if(space!=null&&typeof space==="object"){options=space;space=0}if(replacer!=null&&typeof replacer==="object"&&!Array.isArray(replacer)){options=replacer;replacer=void 0;space=0}const serializeOptions=Object.assign({relaxed:true,legacy:false},options,{seenObjects:[{propertyName:"(root)",obj:null}]});const doc=serializeValue(value,serializeOptions);return JSON.stringify(doc,replacer,space)}function EJSONserialize(value,options){options=options||{};return JSON.parse(stringify(value,options))}function EJSONdeserialize(ejson,options){options=options||{};return parse(JSON.stringify(ejson),options)}var EJSON=Object.create(null);EJSON.parse=parse;EJSON.stringify=stringify;EJSON.serialize=EJSONserialize;EJSON.deserialize=EJSONdeserialize;Object.freeze(EJSON);var MAXSIZE=1024*1024*17;var buffer=ByteUtils.allocate(MAXSIZE);function setInternalBufferSize(size){if(buffer.lengthAuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}onCollectionSet=(type,collection)=>{};runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b){if(a.timestamp&&b.timestamp)return a.timestamp-b.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_,__,___=this.data){}onSorted(_=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var defaultSpecifiers=["now","minute","5 minutes","30 minutes","hour","6 hours","12 hours","day","3 days","week","2 weeks","month","6 months","year","5 years","decade"];function genTimeSpecifiers(specifiers=defaultSpecifiers){let result=["now"];specifiers.forEach(s=>{if(s!=="now")result.push(`last ${s}`);else result.push(s)});return result}function genTimestampFromString(specifier){const now=new Date;if(specifier==="now"){}else if(specifier==="last minute"){now.setMinutes(now.getMinutes()-1)}else if(specifier==="last hour"){now.setHours(now.getHours()-1)}else if(specifier==="last day"){now.setDate(now.getDate()-1)}else if(specifier==="last week"){now.setDate(now.getDate()-7)}else if(specifier==="last month"){now.setMonth(now.getMonth()-1)}else if(specifier==="last year"){now.setFullYear(now.getFullYear()-1)}else if(specifier==="last decade"){now.setFullYear(now.getFullYear()-1*10)}else if(specifier==="last century"){now.setFullYear(now.getFullYear()-1*100)}else if(specifier==="last millennium"){now.setFullYear(now.getFullYear()-1*1e3)}else if(specifier==="last microsecond"){now.setMilliseconds(now.getMilliseconds()-1)}else if(specifier==="last nanosecond"){now.setMilliseconds(now.getMilliseconds()-1*.001)}else if(specifier.startsWith("last")){const[,count,unit]=specifier.match(/last (\d+) (\w+)/)||[];if(count&&unit){const num=parseInt(count,10);if(unit.includes("minute")){now.setMinutes(now.getMinutes()-num)}else if(unit.includes("hour")){now.setHours(now.getHours()-num)}else if(unit.includes("day")){now.setDate(now.getDate()-num)}else if(unit.includes("week")){now.setDate(now.getDate()-num*7)}else if(unit.includes("month")){now.setMonth(now.getMonth()-num)}else if(unit.includes("year")){now.setFullYear(now.getFullYear()-num)}else if(unit.includes("decade")){now.setFullYear(now.getFullYear()-num*10)}else if(unit.includes("century")){now.setFullYear(now.getFullYear()-num*100)}else if(unit.includes("millennium")){now.setFullYear(now.getFullYear()-num*1e3)}else if(unit.includes("microsecond")){now.setMilliseconds(now.getMilliseconds()-num)}else if(unit.includes("nanosecond")){now.setMilliseconds(now.getMilliseconds()-num*.001)}}}return now.getTime()}var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v2=>{if(!objProps[v2])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v2=>{obj2[k]=v2;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v2)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v2=>!objProps.includes(v2));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v2=>!objProps.includes(v2));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v2=>!objProps.includes(v2));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p2=origin[key];if(Array.isArray(p2))continue;let instanced;if(typeof p2==="function"){if(isNativeClass(p2)){p2=new p2;if(p2 instanceof GraphNode){p2=p2.prototype.constructor(p2,parent,this);instanced=true}}else p2={__operator:p2,__callable:true}}else if(typeof p2==="string"){if(this.__node.nodes.get(p2))p2=this.__node.nodes.get(p2);else p2=this.__node.roots[p2]}else if(typeof p2==="boolean"){if(this.__node.nodes.get(key))p2=this.__node.nodes.get(key);else p2=this.__node.roots[key]}if(p2&&typeof p2==="object"){if(!instanced&&!(p2 instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p2).filter(v2=>!objProps.includes(v2));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p2)).filter(v2=>!objProps.includes(v2));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p2[key2]}p2=cpy}if(!p2.__node)p2.__node={};if(!p2.__node.tag)p2.__node.tag=key;if(!p2.__node.initial)p2.__node.initial=originCpy[key];if(overwrite&&this.get(p2.__node.tag)){this.remove(p2.__node.tag,true)}else if(this.get(p2.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p2.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p2,2);if(instanced||p2 instanceof GraphNode){node=p2}else{node=new GraphNode(p2,parent,this);newnode=true}if(!newnode&&p2 instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d2=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d2.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{name="structs";currentUser;tablet=new DataTablet;collections=this.tablet.collections;id=randomId();useAccessTokens=false;useRefreshTokens=false;constructor(options,user){super(options);this.load(this);if(options.useAccessTokens)this.useAccessTokens=options.useAccessTokens;if(options.useRefreshTokens)this.useRefreshTokens=options.useRefreshTokens;if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}getToken(user){if(this.useAccessTokens)return user.accessToken;else if(this.useRefreshTokens)return user.refreshToken}setupUser=async(userinfo,callback=currentUser=>{})=>{if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u2;let newu=false;if(!user||!user._id){u2=this.userStruct(userinfo,false);newu=true;let wasSet=await this.setUser(u2);let structs=this.getLocalData(void 0,{"ownerId":u2._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u2)}else{u2=user;let toUpdate={_id:userinfo._id,ownerId:userinfo._id};let struct=this.userStruct(userinfo,false);for(const key in struct){if(userinfo[key]&&user[key]!==userinfo[key]){toUpdate[key]=userinfo[key];user[key]=userinfo[key]}else if(struct[key]&&!user[key]){toUpdate[key]=struct[key];user[key]=struct[key]}}if(Object.keys(toUpdate).length>2)await this.setUser(toUpdate);if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u2)}else{let data=await this.getAllUserData(u2._id,void 0,[genTimestampFromString("last day"),Date.now()]);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u2)}if(u2){if(this.currentUser)Object.assign(this.currentUser,u2);else this.currentUser=u2;callback(this.currentUser);return this.currentUser}else{callback(u2);return u2}};baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}this.onResult(data)};structNotification=()=>{this.checkForNotifications()};structDeleted=struct=>{this.deleteLocalData([struct])};onResult=data=>{};randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}addStruct=async(structType="struct",props={},parentUser,parentStruct,updateServer=true)=>{let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct};getUser=async(info="",basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info,basicInfo,this.getToken(this.currentUser)]});callback(res);return res}};queryUsers=async(info,skip,limit,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"queryUsers",args:[this.currentUser._id,info,skip,limit,void 0,this.getToken(this.currentUser)]});callback(res);return res}};getUsers=async(ids=[],basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids,basicInfo]});callback(res);return res}};getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};getAllUserData=async(ownerId,excluded=[],timeRange,callback=this.baseServerCallback)=>{if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[this.currentUser._id,ownerId,excluded,timeRange,this.getToken(this.currentUser)]});callback(res);return res}};query=async(collection,mongoQuery={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!mongoQuery)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,mongoQuery,findOne,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByTimeRange(collection,timeRange,ownerId,limit=0,skip=0,key){let query={};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}let range={$gt:timeRange[0],$lt:timeRange[1]};if(key)query[key]=range;else query.timestamp=range;return this.getData(collection,ownerId,query,limit,skip)}getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct?.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id,this.getToken(this.currentUser)];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};setUser=async(userStruct,callback=this.baseServerCallback)=>{if(userStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};updateServerData=this.setData;deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteUser=async(userId=this.currentUser._id,deleteData,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId,deleteData,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setGroup=async(groupStruct,callback=this.baseServerCallback)=>{if(groupStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setAuthorization=async(authorizationStruct,callback=this.baseServerCallback)=>{if(authorizationStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=await this.currentUser.request({route:"deleteAuthorization",args:[this.currentUser._id,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent){toUpdate=[parent];allReplies.forEach(r=>{let idx=parent.replies?.indexOf(r._id);if(idx>-1)parent.replies.splice(idx,1);let idx2=parent.comments?.indexOf(r._id);if(idx2>-1)parent.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent?._id){let idx=replyTo.replies?.indexOf(parent._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u2=authorizationStruct.authorizerId;if(u2){return new Promise(async resolve=>{this.getUser(u2,true,async data=>{let res;if(!collection)res=await this.getAllUserData(u2,["notification"],void 0,callback);else res=await this.getData(collection,u2,searchDict,limit,skip,callback);resolve(res);callback(res)})})}else return void 0};getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u2=o.authorizerId;if(u2){let data;let user=await this.getUser(u2,true,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u2,["notification"],void 0,callback);else data=await this.getData(collection,u2,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return{};let result={};let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result[a.authorizedId]=true});return result};getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b)=>a*(typeof b==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(void 0,{_id:struct});if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop]===""||copy[prop].constructor.name==="Map"||copy[prop].constructor.name==="Set"||typeof copy[prop]==="function")delete copy[prop];else if(Array.isArray(copy[prop])&©[prop].length===0)delete copy[prop];else if(typeof copy[prop]==="object"&&Object.keys(copy[prop]).length===0)delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(!user.name&&user.firstName)user.name=user.firstName+" "+user.lastName;else if(user.name&&!user.firstName){let split=user.name.split(" ");user.firstName=split[0];user.lastName=split[split.length-1]}if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e15);user._id=user.id;user.ownerId=user.id;let dummy=DataStructures_exports.ProfileStruct();for(const prop in props){if(Object.keys(dummy).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};addEvent=async(parentUser,author="",event="",notes="",startTime=void 0,endTime=void 0,grade=void 0,value=void 0,units=void 0,location=void 0,attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.value=value;newEvent.units=units;newEvent.users=users;newEvent.location=location;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};addChatroom=async(parentUser,authorId="",message="",attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=void 0,updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res}};var import_bson=__toESM(require_bson());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectId=str2=>{return typeof str2==="string"&&str2.length===24?new import_bson.ObjectId(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{name="structs";debug=false;db;users={};collections={};mode="local";useAuths=true;useAccessTokens=false;useRefreshTokens=false;accessTokens=new Map;refreshTokens=new Map;constructor(options,dboptions){super(options);this.load(this);if(dboptions){this.initDB(dboptions)}}initDB=dboptions=>{this.db=dboptions.db;if(dboptions?.users)this.users=dboptions.users;if(dboptions.mode)this.mode=dboptions.mode;if(dboptions?.collections)this.collections=dboptions.collections;if(dboptions.debug)this.debug=dboptions.debug;if(dboptions.useAccessTokens)this.useAccessTokens=dboptions.useAccessTokens;if(dboptions.useRefreshTokens)this.useRefreshTokens=dboptions.useRefreshTokens;if("useAuths"in dboptions)this.useAuths=dboptions.useAuths;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})};query=async(requestingUserId,collection,queryObj,findOne,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip,token)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token);if(passed)return res}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}));return data}};getUser=async(requestingUserId,lookupId,basicInfo,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId,void 0,basicInfo,token)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:void 0};else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};setUser=async(requestingUserId,struct,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(struct.accessToken){this.accessTokens.set(requestingUserId,token)}if(struct.refreshToken){this.refreshTokens.set(requestingUserId,struct.refreshToken)}delete struct.accessToken;delete struct.refreshToken;delete user.accessToken;delete user.refreshToken;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct,token)}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};getUsersByIds=async(requestingUserId,userIds,basicInfo)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds,basicInfo)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct){if(basicInfo)data.push({_id:struct._id,username:struct.username,firstName:struct.firstName,lastName:struct.lastName,fullName:struct.fullName,pictureUrl:struct.pictureUrl});else data.push(struct)}}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};deleteUser=async(requestingUserId,userId,deleteData,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId,deleteData,token)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};setData=async(requestingUserId,structs,notify,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify,token)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};getData=async(requestingUserId,collection,ownerId,dict,limit,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};getDataByIds=async(requestingUserId,structIds,ownerId,collection,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};getAllData=async(requestingUserId,ownerId,excludedCollections,timeRange,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections,timeRange,token)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};deleteData=async(requestingUserId,structIds,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds,token)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};deleteGroup=async(requestingUserId,groupId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId,token)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};getAuthorizations=async(requestingUserId,ownerId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId,token)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};deleteAuthorization=async(requestingUserId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId,token)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};getToken=user=>{return this.useAccessTokens?this.accessTokens.get(user._id):this.useRefreshTokens?this.refreshTokens.get(user._id):void 0};notificationStruct=(parentStruct={})=>{let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct};checkToNotify=async(user,structs=[],mode=this.mode)=>{if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(struct.ownerId&&user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+struct.ownerId;newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+usr;newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id)+"_"+auth.authorizedId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications,true,this.getToken(user))}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid]?.sendAll({route:"structNotification",args:true})}return true}else return false};queryMongo=async(user,collection,queryObj={},findOne=false,skip=0,token)=>{if(!collection&&!queryObj)return void 0;else if(findOne){let res=await this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token)}if(passed)return res;else return void 0}else{let res=this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];let arr=await res.toArray();if(arr.length>0){let passed=!this.useAuths;let checkedAuth="";for(const s of arr){if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)structs.push(s)}}return structs}};setMongoData=async(user,structs=[],notify=true,token)=>{let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:toObjectId(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType?struct.structType:"data").insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectId(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false};setMongoUser=async(user,struct,token)=>{if(struct._id){const _id=toObjectId(struct._id);let usersearch={_id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));copy._id=_id;if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false};setGroup=async(user,struct,mode=this.mode,token)=>{if(struct?._id){let uid=getStringId(user._id);let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(uid)<0))return false;if(uid!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u2=>{allusers.push({email:u2},{id:u2},{username:u2})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});let arr=cursor.toArray();if(arr.length>0){arr.forEach(user2=>{users[uid]=user2;ids[uid]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u2=users[id];if(struct.admins[getStringId(u2._id)]||struct.admins[u2.email]||struct.admins[u2.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u2._id)])admins[getStringId(u2._id)]=true}if(struct.peers[getStringId(u2._id)]||struct.peers[u2.email]||struct.peers[u2.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u2._id)])peers[getStringId(u2._id)]=true}if(struct.clients[getStringId(u2._id)]||struct.clients[u2.email]||struct.clients[u2.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u2._id)])clients[getStringId(u2._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType?struct.structType:"data").findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectId(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false};getMongoUser=(user,info="",requireAuth=true,basicInfo=false,token)=>{return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectId(info)})}catch(e){console.log("error creating ObjectId with ",info)}let u2=await this.collections.profile.instance.findOne({$or:query});if(!u2||u2==null)resolve(void 0);else{u2._id=getStringId(u2._id);if(!u2.ownerId)u2.ownerId=u2._id;if(basicInfo){if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}let stripped={username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id};u2=stripped;resolve({user:u2})}else if(requireAuth){if(getStringId(user._id)!==u2._id||getStringId(user._id)===u2._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u2,"READ",token);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u2._id});let aarr=await auths.toArray();if(auths.toArray().length>0){aarr.forEach(d2=>authorizations.push(d2))}let gs=this.collections.group.instance.find({users:{$all:[u2._id]}});let arr=await gs.toArray();let groups=[];if(arr.length>0){arr.forEach(d2=>groups.push(d2))}resolve({user:u2,authorizations,groups})}else{if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}resolve({user:u2})}}})};queryUsers=(user,info="",limit=0,skip=0,requireAuth=false,token)=>{if(typeof user==="string")user=this.users[user];if(!user)return;return new Promise(async resolve=>{let q={$regex:`^${info}`,$options:"i"};const query=[{email:q},{username:q},{firstName:q},{lastName:q},{name:q}];let arr;if(this.mode.includes("mongo")){let users=this.collections.profile.instance.find({$or:query},{projection:shallowqueryDummy}).skip(skip);if(limit>0)users.limit(limit);await users;arr=await users.toArray()}else{arr=[];for(let i=0;i{arr.push({firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,username:u2.username,pictureUrl:u2.pictureUrl})})}else if(dat)arr.push({firstName:dat.firstName,lastName:dat.lastName,fullName:dat.fullName,username:dat.username,pictureUrl:dat.pictureUrl})}}if(requireAuth){let result=[];let strid=getStringId(user._id);for(let i=0;i{let usrs=[];userIds.forEach(u2=>{try{usrs.push({_id:toObjectId(u2)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{if(basicInfo){found.push({username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id})}else found.push(u2)})}}return found};getMongoUsersByRole=async(user,role)=>{let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{found.push(u2)})}return found};getMongoDataByIds=async(user,structIds,ownerId,collection,token)=>{let uid=getStringId(user._id);if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectId(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});let arr=await cursor.toArray();if(arr.length>0){let passed=true;let checkedAuth="";for(let i=0;i0){let passed=true;let checkedAuth="";arr.forEach(async s=>{if(!s?.ownerId)passed=true;else if((uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}};getMongoData=async(user,collection,ownerId,dict={},limit=0,skip=0,token)=>{if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectId(dict._id);let uid=getStringId(user._id);let structs=[];let passed=true;let checkedAuth="";let cursor;if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip)}else if(collection&&Object.keys(dict).length>0){if(ownerId)dict.ownerId=ownerId;cursor=await this.db.collection(collection).find(dict).sort({$natural:-1}).skip(skip)}if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{cursor=await this.db.collection(name).find(dict).sort({$natural:-1}).skip(skip);;if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i{let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let query={ownerId};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1]);query.timestamp={$gt:timeRange[0],$lt:timeRange[1]}}let cursor=this.db.collection(name).find(query);let arr=await cursor.toArray();let count=arr.length;for(let k=0;k{let structs=[];if(structs.length>0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectId(ref._id)});if(struct){let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs};getMongoAuthorizations=async(user,ownerId=getStringId(user._id),authId="",token)=>{let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectId(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0],"READ",token);if(!passed)return void 0}return auths};getMongoGroups=async(user,userId=getStringId(user._id),groupId="")=>{let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId),users:{$all:[userId]}}))}catch{}}return groups};deleteMongoData=async(user,structRefs=[],token)=>{let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectId(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=notifications.toArray().length;for(let i=0;i{let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){await this.db.collection(struct.structType?struct.structType:"data").deleteOne({_id:toObjectId(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})}}}));return true};deleteMongoUser=async(user,userId,deleteData,token)=>{if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u2=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u2?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u2,"WRITE",token);if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(deleteData){for(const key in this.collections){this.collections[key].instance.deleteMany({ownerId:userId});this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}})}}if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId]?.sendAll({route:"structDeleted",args:{_id:userId,structType:"profile"}});return true};deleteMongoGroup=async(user,groupId,token)=>{let s=await this.collections.group.instance.findOne({_id:toObjectId(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u2=>{this.users[u2]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}})})}await this.collections.group.instance.deleteOne({_id:toObjectId(groupId)});return true}else return false};deleteMongoAuthorization=async(user,authId,token)=>{let s=await this.collections.authorization.instance.findOne({_id:toObjectId(authId)});let uid=getStringId(user._id);if(s){if(uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectId(s.associatedAuthId)});if(s.authorizerId!==uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}});else if(s.authorizedId!==uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}})}await this.collections.authorization.instance.deleteOne({_id:toObjectId(authId)});if(s.authorizerId===uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});else if(s.authorizedId===uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});return true}else return false};setAuthorization=async(user,authStruct,token)=>{let u1,u2;let mmode=this.mode.includes("mongo");if(mmode){u1=(await this.getMongoUser(user,authStruct.authorizedId,false)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,false)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})?.[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})?.[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.name)authStruct.authorizedName=u1.name;else if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u1.name)authStruct.authorizedName=u1.name;else if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE",token);if(!passed)return false}let auths=[];if(mmode){let s=await this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d2=>{if(d2.authorizerId===authStruct.authorizerId)auths.push(d2)})}}let otherAuthset;if(Array.isArray(auths)){for(let i=0;i{if(typeof user==="string"){if(this.users[user])user=this.users[user];else user={_id:user}}if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}return true}}if(this.useAccessTokens){if(!this.accessTokens.get(user._id)||this.accessTokens.get(user._id)!==token){return false}}else if(this.useRefreshTokens){if(!this.refreshTokens.get(user._id)||this.refreshTokens.get(user._id)!==token){return false}}let auth1,auth2;if(this.mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});if(!auth1)return false;auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(struct.ownerId)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(struct.ownerId)}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed};wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};overwriteLocalData=structs=>{if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}};setLocalData=structs=>{let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)};getLocalData=(collection,query)=>{let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result};deleteLocalData=struct=>{if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var shallowqueryDummy=DataStructures_exports.ProfileStruct();for(const key in shallowqueryDummy){if(key==="username"||key==="lastName"||key==="firstName"||key==="name"||key==="_id"||key==="pictureUrl")shallowqueryDummy[key]=1;else delete shallowqueryDummy[key]}var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u2=(dot11*dot02-dot01*dot12)*_denom;let v2=(dot00*dot12-dot01*dot02)*_denom;if(u2>=0&&v2>=0&&u2+v2<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v2=>{let magnitude=0;for(const key in v2){magnitude+=v2[key]*v2[key]}return Math.sqrt(magnitude)},normalize:v2=>{let magnitude=Systems.collision.magnitude(v2);let _mag=magnitude?1/magnitude:0;let vn={};for(const key in v2){vn[key]=v2[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w2=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w2||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var y=class{r;g;b;a;constructor(e,t,l,o){this.r=e,this.g=t,this.b=l,this.a=o}};var w=class{intensity;visible;numPoints;xy;color;scaleX;scaleY;offsetX;offsetY;loop;webglNumPoints;_vbuffer;_coord;constructor(){this.scaleX=1,this.scaleY=1,this.offsetX=0,this.offsetY=0,this.loop=false,this._vbuffer=0,this._coord=0,this.visible=true,this.intensity=1,this.xy=new Float32Array([]),this.numPoints=0,this.color=new y(0,0,0,1),this.webglNumPoints=0}};var v=class extends w{currentIndex=0;constructor(e,t){super(),this.webglNumPoints=t,this.numPoints=t,this.color=e,this.xy=new Float32Array(2*this.webglNumPoints)}setX(e,t){this.xy[e*2]=t}setY(e,t){this.xy[e*2+1]=t}getX(e){return this.xy[e*2]}getY(e){return this.xy[e*2+1]}lineSpaceX(e,t){for(let l=0;l{let l={x:0,y:0};return l.x=u2.x+e.x*t,l.y=u2.y+e.y*t,l};var A=u2=>P(-u2.y,u2.x);var p=(u2,e)=>{let t=R(u2,e);return t=M(t),t};var T=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x+e.x,t.y=u2.y+e.y,t};var C=(u2,e)=>u2.x*e.x+u2.y*e.y;var M=u2=>{let e={x:0,y:0},t=u2.x*u2.x+u2.y*u2.y;return t>0&&(t=1/Math.sqrt(t),e.x=u2.x*t,e.y=u2.y*t),e};var P=(u2,e)=>{let t={x:0,y:0};return t.x=u2,t.y=e,t};var R=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x-e.x,t.y=u2.y-e.y,t};var X=u2=>{let e,t={x:0,y:0},l={x:0,y:0},o=[],a=(s,r)=>{o.push({vec2:s,miterLength:r})},h=s=>({x:u2[s*2],y:u2[s*2+1]});t=p(h(1),h(0)),e=A(t),a(e,1);let n=u2.length/2;for(let s=1;s{let t=T(u2,e);return t=M(t),P(-t.y,t.x)};var N=(u2,e,t)=>{let l=P(-u2.y,u2.x);return t/C(e,l)};var d=class extends w{currentIndex=0;_linePoints;_thicknessRequested=0;_actualThickness=0;constructor(e,t,l){super(),this.webglNumPoints=t*2,this.numPoints=t,this.color=e,this._thicknessRequested=l,this._linePoints=new Float32Array(t*2),this.xy=new Float32Array(2*this.webglNumPoints)}convertToTriPoints(){let e=this._actualThickness/2,t=X(this._linePoints);for(let l=0;l{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(l.loop?t.LINE_LOOP:t.LINE_STRIP,0,l.webglNumPoints)}})}_drawSurfaces(e){let t=this.webgl;e.forEach(l=>{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(t.TRIANGLE_STRIP,0,l.webglNumPoints)}})}_drawTriangles(e){let t=this.webgl;t.bufferData(t.ARRAY_BUFFER,e.xy,t.STREAM_DRAW),t.useProgram(this._progLine);let l=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(l,false,new Float32Array([e.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,e.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let o=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(o,new Float32Array([e.offsetX+this.gOffsetX,e.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([0,0]));let h=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(h,[e.color.r,e.color.g,e.color.b,e.color.a]),t.drawArrays(t.TRIANGLE_STRIP,0,e.xy.length/2)}_drawThickLines(){this._thickLines.forEach(e=>{if(e.visible){let t=Math.min(this.gScaleX,this.gScaleY);e.setActualThickness(e.getThickness()/t),e.convertToTriPoints(),this._drawTriangles(e)}})}update(){this.clear(),this.draw()}draw(){this._drawLines(this.linesData),this._drawLines(this.linesAux),this._drawThickLines(),this._drawSurfaces(this.surfaces)}clear(){this.webgl.clear(this.webgl.COLOR_BUFFER_BIT)}_addLine(e){e._vbuffer=this.webgl.createBuffer(),this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER,e._vbuffer),this.webgl.bufferData(this.webgl.ARRAY_BUFFER,e.xy,this.webgl.STREAM_DRAW),e._coord=this.webgl.getAttribLocation(this._progLine,"coordinates"),this.webgl.vertexAttribPointer(e._coord,2,this.webgl.FLOAT,false,0,0),this.webgl.enableVertexAttribArray(e._coord)}addDataLine(e){this._addLine(e),this.linesData.push(e)}addLine=this.addDataLine;addAuxLine(e){this._addLine(e),this.linesAux.push(e)}addThickLine(e){this._addLine(e),this._thickLines.push(e)}addSurface(e){this._addLine(e),this.surfaces.push(e)}initThinLineProgram(){let e=` - attribute vec2 coordinates; - uniform mat2 uscale; - uniform vec2 uoffset; - uniform ivec2 is_log; - - void main(void) { - float x = (is_log[0]==1) ? log(coordinates.x) : coordinates.x; - float y = (is_log[1]==1) ? log(coordinates.y) : coordinates.y; - vec2 line = vec2(x, y); - gl_Position = vec4(uscale*line + uoffset, 0.0, 1.0); - }`,t=this.webgl.createShader(this.webgl.VERTEX_SHADER);this.webgl.shaderSource(t,e),this.webgl.compileShader(t);let l=` - precision mediump float; - uniform highp vec4 uColor; - void main(void) { - gl_FragColor = uColor; - }`,o=this.webgl.createShader(this.webgl.FRAGMENT_SHADER);this.webgl.shaderSource(o,l),this.webgl.compileShader(o),this._progLine=this.webgl.createProgram(),this.webgl.attachShader(this._progLine,t),this.webgl.attachShader(this._progLine,o),this.webgl.linkProgram(this._progLine)}popDataLine(){this.linesData.pop()}removeAllLines(){this._linesData=[],this._linesAux=[],this._thickLines=[],this._surfaces=[]}removeDataLines(){this._linesData=[]}removeAuxLines(){this._linesAux=[]}viewport(e,t,l,o){this.webgl.viewport(e,t,l,o)}log(e){this.debug&&console.log("[webgl-plot]:"+e)}};var S=class u{constructor(){this.plots={};this.renderOverlay=(e,t,l,o,a,h=1,n=0)=>{if(typeof l.settings.overlay=="object"&&(o.useOverlay||!("useOverlay"in o))){let s=l.settings.nLines-o.position-1,r=e.height*s/l.settings.nLines,i=e.height*(s+1)/l.settings.nLines;if(t.clearRect(0,r,e.width,i),l.settings.mode==="sweep"){t.strokeStyle=l.settings.sweepColor?l.settings.sweepColor:"rgba(0,255,0,0.8)",t.beginPath();let f=e.width*o.ct/o.values.length;t.moveTo(f,r),t.lineTo(f,i),t.stroke()}if(t.fillStyle=l.settings.overlayColor?l.settings.overlayColor:"white",a&&t.fillText(a,20,e.height*(s+.2)/l.settings.nLines),o.nSec){let f=this.formatTime(o.nSec);t.fillText(`${f}`,l.settings.mode==="sweep"?e.width-35:20,e.height*(s+.9)/l.settings.nLines),t.fillText("0:00",l.settings.mode==="sweep"?20:e.width-35,e.height*(s+.9)/l.settings.nLines)}typeof h=="number"&&t.fillText(`${Math.floor(h)===h?h:h?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.2)/l.settings.nLines),typeof n=="number"&&t.fillText(`${Math.floor(n)===n?n:n?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.8)/l.settings.nLines)}}}initPlot(e,t){if(t||(t=new x2(e.canvas,e.webglOptions)),!e._id)e._id=`plot${Math.floor(Math.random()*1e15)}`;else if(this.plots[e._id]){let r=this.plots[e._id].initial;if(e.lines){for(let i in e.lines)if(r.lines[i]&&Array.isArray(e.lines[i])){let f=e.lines[i];e.lines[i]=r.lines[i]}}e=Object.assign(r,e)}e.overlay&&(typeof e.overlay!="object"&&(e.overlay=document.createElement("canvas"),e.overlay.style.position="absolute",e.overlay.width=e.canvas.width,e.overlay.height=e.canvas.height,e.canvas.appendChild(e.overlay)),e.overlayCtx||(e.overlayCtx=e.overlay.getContext("2d"))),e.width&&(e.canvas.width=e.width,e.canvas.style&&(e.canvas.style.width=e.width+"px"),typeof e.overlay=="object"&&(e.overlay.width=e.width,e.overlay.style&&(e.overlay.style.width=e.width+"px"))),e.height&&(e.canvas.height=e.height,e.canvas.style&&(e.canvas.style.height=e.height+"px"),typeof e.overlay=="object"&&(e.overlay.height=e.height,e.overlay.style&&(e.overlay.style.height=e.height+"px"))),e.lines?.timestamp&&delete e.lines.timestamp,e.lines||(e.lines={});let l={};for(let r in e.lines)l[r]=Object.assign({},l[r]),"viewing"in e.lines[r]||(e.lines[r].viewing=true),l[r].viewing=e.lines[r].viewing,l[r].sps=e.lines[r].sps,l[r].nSec=e.lines[r].nSec,l[r].nPoints=e.lines[r].nPoints,l[r].ymin=e.lines[r].ymin,l[r].ymax=e.lines[r].ymax,l[r].units=e.lines[r].units;let o={plot:t,settings:e,initial:Object.assign(Object.assign({},e),{lines:l}),anim:()=>{t.update()}};this.plots[e._id]=o;let a=0,h=0;Object.keys(e.lines).forEach(r=>{e.lines[r]?.viewing!==false&&h++}),e.nLines=h;let n,s;typeof e.overlay=="object"&&(n=e.overlay,s=e.overlayCtx,s.clearRect(0,0,e.overlay.width,e.overlay.height),s.font=e.overlayFont?e.overlayFont:"1em Courier",s.fillStyle=e.overlayColor?e.overlayColor:"white");for(let r in e.lines){let i=e.lines[r];if(Array.isArray(i)&&(i={values:i},e.lines[r]=i),"viewing"in i||(i.viewing=true),i.color)Array.isArray(i.color)&&(i.color=new y(...i.color));else{let m=u.HSLToRGB(360*(a/h)%360,100,50,1);o.initial.lines[r].color=[...m,1],i.color=new y(...m,1)}let f;if(i.nSec&&i.sps?f=Math.ceil(i.nSec*i.sps):i.nPoints?f=i.nPoints:i.points?f=i.points:e.linePoints?f=e.linePoints:i.values?f=i.values.length:f=1e3,i.points=f,e.lines[r].viewing===false)continue;if((i.width||e.lineWidth)&&i.width!==0){let m=e.lineWidth;m||(m=i.width),i.width?i.line=new d(i.color,f,i.width):e.lineWidth&&(i.line=new d(i.color,f,e.lineWidth)),i.line.lineSpaceX(-1,2/i.line.numPoints)}else i.line=new v(i.color,f),i.line.arrangeX();i.values?.length===i.points?i.values.length!==f&&(i.interpolate?i.values.length>f?i.values=u.downsample(i.values,f):i.values.lengthi.points?i.values=i.values.slice(i.values.length-i.points):i.values=[...new Array(i.points-i.values.length).fill(0),...i.values]):Array.isArray(i.values)?i.values.length>f?i.values=i.values.slice(i.values.length-f):i.values.lengthg){let m=c;g=c,c=m}let _=Math.abs(c);if(i.absmax=_>g?_:g,"autoscale"in i||(i.autoscale=true),i.position||(i.position=e.nLines-a-1),i.autoscale?i.autoscale===2?("clamp"in i||(i.clamp=true),i.scaled=u.autoscale(i.values,i.position,h,i.centerZero,c,g,i.clamp)):(i.scaled=i.values,i.line.scaleY=u.getYScalar(i.values,h,i.centerZero,c,g),i.line.offsetY=u.getYOffset(i.position,h,c,i.line.scaleY)):i.scaled=i.values,i.scaled.forEach((m,L)=>i.line.setY(L,m)),i.line instanceof d?t.addThickLine(i.line):i.line instanceof v&&t.addDataLine(i.line),"xAxis"in i||(i.xAxis=true),i.xAxis){i.xColor?Array.isArray(i.xColor)&&(i.xColor=new y(...i.xColor)):i.xColor=new y(1,1,1,.3);let m=new v(i.xColor,2),L=i.autoscale?(a+1)*2/h-1-1/h:0;m.constY(L),m.arrangeX(),m.xy[2]=1,i.x=m,t.addAuxLine(m)}if(h>1&&i.autoscale&&a!==h-1){e.dividerColor?Array.isArray(e.dividerColor)&&(e.dividerColor=new y(...e.dividerColor)):e.dividerColor=new y(1,1,1,1);let m=new v(e.dividerColor,2);m.constY(i.autoscale?(a+1)*2/h-1:1),m.arrangeX(),m.xy[2]=1,i.divider=m,t.addAuxLine(m)}if(typeof e.overlay=="object"&&(i.useOverlay||!("useOverlay"in i))){let m=e.nLines-i.position-1;s.fillText(r,20,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(g)===g?g:g?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(c)===c?c:c?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.9)/e.nLines)}a++}return requestAnimationFrame(o.anim),this.plots[e._id]}deinitPlot(e){return typeof e=="string"&&(e=this.plots[e]),e.plot.clear(),e.plot.removeAllLines(),true}reinitPlot(e,t){if(typeof e=="string"){let l=e;e=this.plots[e],t._id||(t._id=l)}if(e.plot)return e.plot.clear(),e.plot.removeAllLines(),e.settings.overlayCtx&&e.settings.overlayCtx.clearRect(0,0,e.settings.overlay?.width,e.settings.overlay?.height),this.initPlot(t,e.plot)}getChartSettings(e,t){let l=this.plots[e];if(l){let o=Object.assign({},l.initial);for(let a in l.initial.lines)typeof l.initial.lines[a]?.ymax!="number"&&(o.lines[a].ymax=l.settings.lines[a]?.ymax),typeof l.initial.lines[a]?.ymin!="number"&&(o.lines[a].ymin=l.settings.lines[a]?.ymin),t&&(o.lines[a].values=l.settings.lines[a].values);return delete o.canvas,delete o.overlay,delete o.overlayCtx,o}}update(e,t,l=true){if(typeof e=="string"&&(e=this.plots[e]),!e)return false;let o,a;if(typeof e.settings.overlay=="object"&&(o=e.settings.overlay,a=e.settings.overlayCtx,a.font=e.settings.overlayFont?e.settings.overlayFont:"1em Courier",a.fillStyle=e.settings.overlayColor?e.settings.overlayColor:"white"),t){let h=false;for(let n in t)if(e.settings.lines[n]&&e.settings.lines[n].line){if(e.settings.lines[n]?.viewing===false)continue;let s=e.settings.lines[n];if(s.values){if(e.settings.mode&&e.settings.mode==="sweep"){"ct"in s||(s.ct=0);let g=b=>{s.ct>s.values.length&&(s.ct=0),s.values[s.ct]=b,s.ct++};Array.isArray(t[n])?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n][t[n].length-1])),t[n].forEach(g)):typeof t[n]=="number"?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n])),g(t[n])):t[n].values&&(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n].values[t[n].values.length-1])),t[n].values.forEach(g))}else Array.isArray(t[n])&&s.values?.length<1e5?(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n][t[n].length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n][t[n].length-1]),s.firstWrite=true),t[n].length===s.values.length?s.values=t[n]:u.circularBuffer(s.values,t[n])):typeof t[n]=="number"?(s.firstWrite||(s.values.fill(t[n]),s.firstWrite=true),s.values.push(t[n]),s.values.shift()):t[n]?.values&&(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true),t[n].values.length===s.values.length?s.values=t[n].values:u.circularBuffer(s.values,t[n].values));s.values.length!==s.points&&(s.interpolate?s.values.length>s.points?s.values=u.downsample(s.values,s.points):s.scaled.lengths.points?s.values.splice(0,s.values.length-s.points):s.values=new Array(s.points).fill(0).splice(s.points-s.values.length,0,s.values));let r=s.ymin,i=s.ymax,f=s.values.length<=1e5;if(r===i?(i=f?Math.max(...s.values):1,r=f?Math.min(...s.values):0):isNaN(i)&&(i=f?Math.max(...s.values):1),isNaN(r)&&(r=f?Math.min(...s.values):0),r>i){let g=r;i=r,r=g}let c=Math.abs(r);s.absmax=c>i?c:i,s.autoscale?s.autoscale===2?s.scaled=u.autoscale(s.values,s.position,e.settings.nLines,s.centerZero,r,i,s.clamp):(s.scaled=s.values,s.line.scaleY=u.getYScalar(s.values,e.settings.nLines,s.centerZero,r,i),s.line.offsetY=u.getYOffset(s.position,e.settings.nLines,r,s.line.scaleY)):s.scaled=s.values,s.scaled.forEach((g,b)=>{!s.autoscale&&s.absmax>1?s.line.setY(b,g/s.absmax):s.line.setY(b,g)}),this.renderOverlay(o,a,e,s,n,i,r)}}else e.settings.generateNewLines&&!n.includes("timestamp")&&(Array.isArray(t[n])&&(t[n]={values:t[n]}),!t[n].nSec&&!t[n].nPoints&&!e.settings.linePoints&&(t[n].nPoints=1e3),h=true);if(h)return e.settings.cleanGeneration||Object.keys(e.initial.lines).forEach(n=>{t[n]?t[n]=Object.assign(e.initial.lines[n],t[n]):t[n]=e.initial.lines[n]}),this.reinitPlot(e,{_id:e.settings._id,lines:t}),true}else for(let h in e.settings.lines){let n=e.settings.lines[h];this.renderOverlay(o,a,e,n,h,n.ymax,n.ymin)}return l&&requestAnimationFrame(e.anim),true}updateLine(e,t,l,o,a,h,n){return e.numPoints!==t.length&&(l?e.numPoints>t.length?t=u.downsample(t,e.numPoints):e.numPointse.numPoints?t=t.slice(t.length-e.numPoints):t=[...new Array(t.length).fill(0),...t]),o&&(t=u.autoscale(t,a,h,n)),t.forEach((s,r)=>e.setY(r,s)),true}formatTime(e){let t=Math.floor(e/60),l=Math.floor(t/60);t=t%60,e=e%60;let o="";return l>0&&(o+=l+":",t<10&&(o+="0")),o+=t+":",e>0&&(e<10&&(o+="0"),o+=e),o}static autoscale(e,t=0,l=1,o=false,a,h,n){if(e?.length===0)return e;let s=typeof h=="number"?h:e.length<=1e5?Math.max(...e):1,r=typeof a=="number"?a:e.length<=1e5?Math.min(...e):0,i=1/l,f=1;if(o){let c=Math.max(Math.abs(r),Math.abs(s));return c!==0&&(f=i/c),e.map(g=>(n&&(gs&&(g=s)),g*f+(i*(t+1)*2-1-i)))}else return s===r?s!==0?f=i/s:r!==0&&(f=i/Math.abs(r)):f=i/(s-r),e.map(c=>(n&&(cs&&(c=s)),2*((c-r)*f-1/(2*l))+(i*(t+1)*2-1-i)))}static getYScalar(e,t=1,l=false,o,a){if(e?.length===0)return e;let h=typeof a=="number"?a:e.length<=1e5?Math.max(...e):1,n=typeof o=="number"?o:e.length<=1e5?Math.min(...e):0,s=1/t,r=1;if(l){let i=Math.max(Math.abs(n),Math.abs(h));return i!==0&&(r=s/i),2*r}else return h===n?h!==0?r=s/h:n!==0&&(r=s/Math.abs(n)):r=s/(h-n),2*r}static getYOffset(e=0,t=1,l=0,o=1){let a=1/t,h=a*(e+1)*2-1-a;return l!==0?h-=l*o+1/t:h-=o+1/t,h}static absmax(e){return Math.max(Math.abs(Math.min(...e)),Math.max(...e))}static downsample(e,t,l=1){if(e.length>t){let o=new Array(t),a=e.length/t,h=e.length-1,n=0,s=0;for(let r=a;rh&&(i=h);for(let f=n;ft?u.downsample(e,t,l):e.lengthe.length){let l=e.length;e.splice(0,l,...t.slice(t.length-l))}else e.splice(0,e.length,...t);return e}static formatDataForCharts(e,t){if(Array.isArray(e)){if(Array.isArray(e[0])){let l={};if(e.forEach((o,a)=>{l[a]=o}),e=l,isNaN(e[0][0]))return}else if(t){if(e={[t]:e},isNaN(e[t][0]))return}else if(e={0:e},isNaN(e[0][0]))return}else if(typeof e=="object"){for(let l in e)if(typeof e[l]=="number"?e[l]=[e[l]]:e[l]?.values&&typeof e[l].values=="number"&&(e[l].values=[e[l].values]),isNaN(e[l][0]))return}else if(typeof e=="string"){let l;if(e.includes(`\r -`)){let o=e.split(`\r -`);e={},o.forEach((a,h)=>{a.includes(" ")?l=a.split(" "):a.includes(",")?l=a.split(","):a.includes("|")&&(l=a.split("|")),l&&l.forEach((n,s)=>{if(n.includes(":")){let[r,i]=n.split(":"),f=parseFloat(i);isNaN(f)||(e[r]=[f])}else{let r=parseFloat(n);isNaN(r)||(e[s]=[r])}})})}else e.includes(" ")?l=e.split(" "):e.includes(",")?l=e.split(","):e.includes("|")&&(l=e.split("|"));e={},l&&l.forEach((o,a)=>{if(o.includes(":")){let[h,n]=o.split(":"),s=parseFloat(n);isNaN(s)||(e[h]=[s])}else{let h=parseFloat(o);isNaN(h)||(e[a]=[h])}})}else typeof e=="number"&&(t?e={[t]:[e]}:e={0:[e]});return e}static padTime(e,t,l,o){let a=(e[0]-t)/l/o;return[...new Array(o-e.length).map((n,s)=>t+a*(s+1)),...e]}static interpolateForTime(e,t,l){return u.interpolate(e,Math.ceil(l*t))}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new S;return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new S;return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` -
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass