@fluxscape/runtime 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.js +2 -2
- package/dist/index.es.js.map +1 -1
- package/dist/index.iife.js +1 -1
- package/dist/index.iife.js.map +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Runtime=function(exports){"use strict";class CloudFile{constructor({name:t,url:n}){this.name=t,this.url=n}getUrl(){return this.url}getName(){return this.name}toString(){return this.url}}var R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(t,n,o){return Function.prototype.apply.call(t,n,o)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t)};function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}var NumberIsNaN=Number.isNaN||function(t){return t!==t};function EventEmitter(){EventEmitter.init.call(this)}EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get(){return defaultMaxListeners},set(e){if(typeof e!="number"||e<0||NumberIsNaN(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");defaultMaxListeners=e}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||NumberIsNaN(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function _getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function(t){for(var n=[],o=1;o<arguments.length;o++)n.push(arguments[o]);var r=t==="error",s=this._events;if(s!==void 0)r=r&&s.error===void 0;else if(!r)return!1;if(r){var a;if(n.length>0&&(a=n[0]),a instanceof Error)throw a;var u=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw u.context=a,u}var l=s[t];if(l===void 0)return!1;if(typeof l=="function")ReflectApply(l,this,n);else for(var d=l.length,p=arrayClone(l,d),o=0;o<d;++o)ReflectApply(p[o],this,n);return!0};function _addListener(e,t,n,o){var r,s,a;if(checkListener(n),s=e._events,s===void 0?(s=e._events=Object.create(null),e._eventsCount=0):(s.newListener!==void 0&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),a=s[t]),a===void 0)a=s[t]=n,++e._eventsCount;else if(typeof a=="function"?a=s[t]=o?[n,a]:[a,n]:o?a.unshift(n):a.push(n),r=_getMaxListeners(e),r>0&&a.length>r&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,ProcessEmitWarning(u)}return e}EventEmitter.prototype.addListener=function(t,n){return _addListener(this,t,n,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function(t,n){return _addListener(this,t,n,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,n){var o={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=onceWrapper.bind(o);return r.listener=n,o.wrapFn=r,r}EventEmitter.prototype.once=function(t,n){return checkListener(n),this.on(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.prependOnceListener=function(t,n){return checkListener(n),this.prependListener(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.removeListener=function(t,n){var o,r,s,a,u;if(checkListener(n),r=this._events,r===void 0)return this;if(o=r[t],o===void 0)return this;if(o===n||o.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,o.listener||n));else if(typeof o!="function"){for(s=-1,a=o.length-1;a>=0;a--)if(o[a]===n||o[a].listener===n){u=o[a].listener,s=a;break}if(s<0)return this;s===0?o.shift():spliceOne(o,s),o.length===1&&(r[t]=o[0]),r.removeListener!==void 0&&this.emit("removeListener",t,u||n)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function(t){var n,o,r;if(o=this._events,o===void 0)return this;if(o.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):o[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete o[t]),this;if(arguments.length===0){var s=Object.keys(o),a;for(r=0;r<s.length;++r)a=s[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=o[t],typeof n=="function")this.removeListener(t,n);else if(n!==void 0)for(r=n.length-1;r>=0;r--)this.removeListener(t,n[r]);return this};function _listeners(e,t,n){var o=e._events;if(o===void 0)return[];var r=o[t];return r===void 0?[]:typeof r=="function"?n?[r.listener||r]:[r]:n?unwrapListeners(r):arrayClone(r,r.length)}EventEmitter.prototype.listeners=function(t){return _listeners(this,t,!0)},EventEmitter.prototype.rawListeners=function(t){return _listeners(this,t,!1)},EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}EventEmitter.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(e,t){for(var n=new Array(t),o=0;o<t;++o)n[o]=e[o];return n}function spliceOne(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function unwrapListeners(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function once(e,t){return new Promise(function(n,o){function r(a){e.removeListener(t,s),o(a)}function s(){typeof e.removeListener=="function"&&e.removeListener("error",r),n([].slice.call(arguments))}eventTargetAgnosticAddListener(e,t,s,{once:!0}),t!=="error"&&addErrorHandlerIfEventEmitter(e,r,{once:!0})})}function addErrorHandlerIfEventEmitter(e,t,n){typeof e.on=="function"&&eventTargetAgnosticAddListener(e,"error",t,n)}function eventTargetAgnosticAddListener(e,t,n,o){if(typeof e.on=="function")o.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener=="function")e.addEventListener(t,function r(s){o.once&&e.removeEventListener(t,r),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}function NodeRegister(e){this._constructors={},this.context=e}NodeRegister.prototype.register=function(e){var t=e.metadata.name;this._constructors[t]=e},NodeRegister.prototype.createNode=function(e,t,n){if(this._constructors.hasOwnProperty(e)===!1)throw new Error("Unknown node type with name "+e);return this._constructors[e](this.context,t,n)},NodeRegister.prototype.getNodeMetadata=function(e){if(this._constructors.hasOwnProperty(e)===!1)throw new Error("Unknown node type with name "+e);return this._constructors[e].metadata},NodeRegister.prototype.hasNode=function(e){return this._constructors.hasOwnProperty(e)},NodeRegister.prototype.getInputType=function(e,t){const n=this.getNodeMetadata(e);return n.inputs[t]&&n.inputs[t].type};function Timer(e,t){this.duration=t.duration||0,this._isRunning=!1,this._hasCalledOnStart=!1,this.scheduler=e,this.repeatCount=1,this.delay=0;for(var n in t)this[n]=t[n]}Timer.prototype.start=function(){return this._isRunning&&this.stop(),this.scheduler.scheduleTimer(this),this},Timer.prototype.stop=function(){this.scheduler.stopTimer(this),this._hasCalledOnStart=!1,this._isRunning=!1,this._wasStopped=!0},Timer.prototype.isRunning=function(){return this._isRunning},Timer.prototype.durationLeft=function(){return this._durationLeft};function TimerScheduler(e){this.requestFrame=e,this.runningTimers=[],this.newTimers=[]}TimerScheduler.prototype.createTimer=function(e){return new Timer(this,e)},TimerScheduler.prototype.scheduleTimer=function(e){this.newTimers.indexOf(e)===-1&&(e.repeatCount===0&&(e.repeatCount=1e5),this.newTimers.push(e),this.requestFrame())},TimerScheduler.prototype.stopTimer=function(e){var t;e._isRunning?(t=this.runningTimers.indexOf(e),t!==-1&&this.runningTimers.splice(t,1),e.onStop&&!e._wasStopped&&e.onStop()):(t=this.newTimers.indexOf(e),t!==-1&&this.newTimers.splice(t,1))},TimerScheduler.prototype.runTimers=function(e){var t=[],n=[],o=[],r,s=this.runningTimers.length,a;for(r=0;r<s;++r)o[r]=this.runningTimers[r];for(r=0;r<s;++r)if(a=o[r],a&&e>=a._start){a._hasCalledOnStart===!1&&a.onStart&&(a.onStart(),a._hasCalledOnStart=!0);var u;a.duration>0?u=(e-a._start)/(a.duration*a.repeatCount):u=1,a._durationLeft=a.duration*(1-u);var l=u*a.repeatCount-Math.floor(u*a.repeatCount);u>=1&&(l=1),a.onRunning&&a.onRunning(l),u<1&&a._isRunning?t.push(a):a._wasStopped||n.push(a)}else t.push(a);for(this.runningTimers=t,r=0;r<n.length;++r)n[r]._isRunning=!1,n[r]._hasCalledOnStart=!1,n[r].onFinish&&n[r].onFinish();if(this.newTimers.length>0){for(r=0;r<this.newTimers.length;++r)a=this.newTimers[r],a._start=e+a.delay,a._isRunning=!0,a._wasStopped=!1,this.runningTimers.push(a),a.delay===0&&(a.onStart&&(a.onStart(),a._hasCalledOnStart=!0),a.onRunning&&a.onRunning(0));this.newTimers.length=0}},TimerScheduler.prototype.hasPendingTimers=function(){return this.runningTimers.length>0||this.newTimers.length>0};class Variants{constructor({graphModel:t,getNodeScope:n}){this.getNodeScope=n,t&&(this.graphModel=t,t.on("variantUpdated",o=>this.onVariantUpdated(o)))}getVariant(t,n){if(this.graphModel)return this.graphModel.getVariant(t,n)}onVariantUpdated(t){const n=this.getNodeScope();if(!n)return;const r=n.getNodesWithTypeRecursive(t.typename).filter(s=>s.variant?s.variant.name===t.name:s.model&&s.model.variant===t.name);for(const s of r)s.setVariant(t)}}function OutputProperty(e){if(!e.owner)throw new Error("Owner must be set");this.getter=e.getter,this.connections=[],this.owner=e.owner,this.name=e.name,this.onFirstConnectionAdded=e.onFirstConnectionAdded,this.onLastConnectionRemoved=e.onLastConnectionRemoved,this._id=void 0}Object.defineProperties(OutputProperty.prototype,{value:{get(){return this.getter.call(this.owner)}},id:{get(){return this._id||(this._id=this.owner.id+this.name),this._id}},registerConnection:{value(e,t){this.connections.push({node:e,inputPortName:t}),this.connections.length===1&&this.onFirstConnectionAdded&&this.onFirstConnectionAdded.call(this.owner)}},deregisterConnection:{value(e,t){for(var n=0;n<this.connections.length;n++){var o=this.connections[n];if(o.node===e&&o.inputPortName===t){this.connections.splice(n,1);break}}this.connections.length===0&&this.onLastConnectionRemoved&&this.onLastConnectionRemoved.call(this.owner)}},flagDependeesDirty:{value(e){for(var t=0,n=this.connections.length;t<n;t++)this.connections[t].node.flagDirty()}},sendValue:{value(e){this._lastUpdateIteration!==this.owner._updatedAtIteration?(this._lastUpdateIteration=this.owner._updatedAtIteration,this.valuesSendThisIteration=0):this.valuesSendThisIteration++,this.valuesSendThisIteration>500&&(this.owner._cyclicLoop=!0);for(var t=0,n=this.connections.length;t<n;t++){var o=this.connections[t];o.node._setValueFromConnection(o.inputPortName,e)}}},hasConnections:{value(){return this.connections.length>0}}});function Node(e,t){this.id=t,this.context=e,this._dirty=!1,this._inputs={},this._inputValues={},this._outputs={},this._inputConnections={},this._outputList=[],this._isUpdating=!1,this._inputValuesQueue={},this._afterInputsHaveUpdatedCallbacks=[],this._internal={},this._signalsSentThisUpdate={},this._deleted=!1,this._deleteListeners=[],this._isFirstUpdate=!0,this._valuesFromConnections={},this.updateOnDirtyFlagging=!0}Node.prototype.getInputValue=function(e){return this._inputValues[e]},Node.prototype.registerInput=function(e,t){if(this.hasInput(e))throw new Error("Input property "+e+" already registered");if(this._inputs[e]=t,t.type&&t.type.units){const n=t.type.defaultUnit||t.type.units[0];this._inputValues[e]={value:t.default,type:n}}else t.hasOwnProperty("default")&&(this._inputValues[e]=t.default)},Node.prototype.deregisterInput=function(e){if(this.hasInput(e)===!1)throw new Error("Input property "+e+" doesn't exist");delete this._inputs[e],delete this._inputValues[e]},Node.prototype.registerInputs=function(e){for(const t in e)this.registerInput(t,e[t])},Node.prototype.getInput=function(e){if(this.hasInput(e)===!1){console.log("Node "+this.name+": Invalid input property "+e);return}return this._inputs[e]},Node.prototype.hasInput=function(e){return e in this._inputs},Node.prototype.registerInputIfNeeded=function(){},Node.prototype.setInputValue=function(name,value){const input=this.getInput(name);if(!input){console.log("node doesn't have input",name);return}const currentInputValue=this._inputValues[name];if(isNaN(value)===!1&¤tInputValue&¤tInputValue.unit){const e=Object.assign({},currentInputValue);e.value=value,value=e}if(this._inputValues[name]=value,input.type==="color"&&this.context&&this.context.styles)value=this.context.styles.resolveColor(value);else if(input.type==="array"&&typeof value=="string")try{value=eval(value),this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+name)}catch(e){value=[],console.log(e),this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+name,{showGlobally:!0,message:"Invalid array<br>"+e.toString()})}input.set.call(this,value)},Node.prototype.hasOutput=function(e){return e in this._outputs},Node.prototype.registerOutput=function(e,t){if(this.hasOutput(e))throw new Error("Output property "+e+" already registered");const n=new OutputProperty({owner:this,getter:t.get||t.getter,name:e,onFirstConnectionAdded:t.onFirstConnectionAdded,onLastConnectionRemoved:t.onLastConnectionRemoved});this._outputs[e]=n,this._outputList.push(n)},Node.prototype.deregisterOutput=function(e){if(this.hasOutput(e)===!1)throw new Error("Output property "+e+" isn't registered");const t=this._outputs[e];if(t.hasConnections())throw new Error("Output property "+e+" has connections and can't be removed");delete this._outputs[e];var n=this._outputList.indexOf(t);this._outputList.splice(n,1)},Node.prototype.registerOutputs=function(e){for(var t in e)this.registerOutput(t,e[t])},Node.prototype.registerOutputIfNeeded=function(){},Node.prototype.getOutput=function(e){if(this.hasOutput(e)===!1)throw new Error("Node "+this.name+" doesn't have a port named "+e);return this._outputs[e]},Node.prototype.connectInput=function(e,t,n){if(this.hasInput(e)===!1)throw new Error("Invalid connection, input doesn't exist. Trying to connect from "+t.name+" output "+n+" to "+this.name+" input "+e);var o=t.getOutput(n);if(o.registerConnection(this,e),this._inputConnections[e]||(this._inputConnections[e]=[]),this._inputConnections[e].push(o),t._signalsSentThisUpdate[n])this._setValueFromConnection(e,!0),this._setValueFromConnection(e,!1);else{var r=o.value;r!==void 0&&(this._setValueFromConnection(e,r),this.context&&this.context.connectionSentValue(o,o.value))}this.flagDirty()},Node.prototype.removeInputConnection=function(e,t,n){if(!this._inputConnections[e])throw new Error("Node removeInputConnection: Input doesn't exist");const o=this._inputConnections[e];for(let r=0;r<o.length;r++){const s=o[r];if(s.owner.id===t&&s.name===n){o.splice(r,1),s.owner.getOutput(n).deregisterConnection(this,e);break}}o.length===0&&delete this._valuesFromConnections[e]},Node.prototype.isInputConnected=function(e){return this._inputConnections.hasOwnProperty(e)?this._inputConnections[e].some(t=>t.owner.name!=="Component Inputs"?!0:t.owner.nodeScope.componentOwner.isInputConnected(t.name)):!1},Node.prototype.update=function(){if(this._isUpdating||this._dirty===!1)return;this._updatedAtIteration!==this.context.updateIteration&&(this._updatedAtIteration=this.context.updateIteration,this._updateIteration=0,this._cyclicLoop&&(this._cyclicLoop=!1)),this._isUpdating=!0;const e=100;try{for(;this._dirty&&!this._cyclicLoop;){this._updateDependencies(),this._dirty=!1;const t=Object.keys(this._inputValuesQueue);let n=!0;for(;n&&!this._cyclicLoop;){n=!1;for(let r=0;r<t.length;r++){const s=t[r],a=this._inputValuesQueue[s];a.length>0&&(this.setInputValue(s,a.shift()),a.length>0&&(n=!0))}const o=this._afterInputsHaveUpdatedCallbacks;this._afterInputsHaveUpdatedCallbacks=[];for(let r=0;r<o.length;r++)o[r].call(this)}this._updateIteration++,this._updateIteration>=e&&(this._cyclicLoop=!0)}}catch(t){throw this._isUpdating=!1,t}this._cyclicLoop&&(this.context.scheduleNextFrame(()=>{this.context.nodeIsDirty(this)}),this.context.editorConnection&&!this._cyclicWarningSent&&this.context.isWarningTypeEnabled("cyclicLoops")&&(this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"cyclic-loop",{showGlobally:!0,message:"Cyclic loop detected"}),this._cyclicWarningSent=!0,console.log("cycle detected",{id:this.id,name:this.name,component:this.nodeScope.componentOwner.name}))),this._isFirstUpdate=!1,this._isUpdating=!1},Node.prototype._updateDependencies=function(){for(var e in this._inputConnections)for(var t=this._inputConnections[e],n=0;n<t.length;++n)t[n].owner.update()},Node.prototype.flagDirty=function(){this._dirty||(this._dirty=!0,this.updateOnDirtyFlagging&&this._performDirtyUpdate())},Node.prototype._performDirtyUpdate=function(){this.context&&this.context.nodeIsDirty(this);for(var e=0;e<this._outputList.length;++e)this._outputList[e].flagDependeesDirty()},Node.prototype.sendValue=function(e,t){if(this.hasOutput(e)===!1){console.log("Error: Node",this.name,"doesn't have a output named",e);return}if(t===void 0)return;const n=this.getOutput(e);n.sendValue(t),this.context&&this.context.connectionSentValue(n,t)},Node.prototype.flagOutputDirty=function(e){const t=this.getOutput(e);this.sendValue(e,t.value)},Node.prototype.flagAllOutputsDirty=function(){for(const e of this._outputList)this.sendValue(e.name,e.value)},Node.prototype.sendSignalOnOutput=function(e){if(this.hasOutput(e)===!1){console.log("Error: Node",this.name,"doesn't have a output named",e);return}const t=this.getOutput(e);t.sendValue(!0),t.sendValue(!1),this._signalsSentThisUpdate[e]=!0,this.scheduleAfterInputsHaveUpdated(function(){this._signalsSentThisUpdate[e]=!1}),this.context&&this.context.connectionSentSignal(t)},Node.prototype._setValueFromConnection=function(e,t){this._valuesFromConnections[e]=t,this.queueInput(e,t)},Node.prototype._hasInputBeenSetFromAConnection=function(e){return this._valuesFromConnections.hasOwnProperty(e)},Node.prototype.queueInput=function(e,t){if(this._inputValuesQueue[e]||(this._inputValuesQueue[e]=[]),this._isFirstUpdate){const n=this._inputValuesQueue[e][0];n===!0||(n instanceof Object&&n.unit&&!(t instanceof Object)&&(t={value:t,unit:n.unit}),this._inputValuesQueue[e].length=0)}this._inputValuesQueue[e].push(t),this.flagDirty()},Node.prototype.scheduleAfterInputsHaveUpdated=function(e){this._afterInputsHaveUpdatedCallbacks.push(e),this.flagDirty()},Node.prototype.setNodeModel=function(e){this.model=e,e.on("parameterUpdated",this._onNodeModelParameterUpdated,this),e.on("variantUpdated",this._onNodeModelVariantUpdated,this),e.on("inputPortRemoved",t=>{this.hasInput(t.name)&&this.deregisterInput(t.name)},this),e.on("outputPortRemoved",t=>{this.hasOutput(t.name)&&this.deregisterOutput(t.name)},this)},Node.prototype.addDeleteListener=function(e){this._deleteListeners.push(e)},Node.prototype._onNodeDeleted=function(){this.model&&(this.model.removeListenersWithRef(this),this.model=void 0),this._deleted=!0;for(const e of this._deleteListeners)e.call(this)},Node.prototype._onNodeModelParameterUpdated=function(e){if(this.registerInputIfNeeded(e.name),e.value!==void 0)if(e.state){if(!this._getVisualStates){console.log("Node has nos visual states, but got a parameter for state",e.state);return}this._getVisualStates().indexOf(e.state)!==-1&&this.queueInput(e.name,e.value)}else this.queueInput(e.name,e.value);else{let t;const n=this.variant;e.state?n&&n.stateParameters.hasOwnProperty(e.state)&&n.stateParameters[e.state].hasOwnProperty(e.name)?t=n.stateParameters[e.state][e.name]:this.model.parameters.hasOwnProperty(e.name)?t=this.model.parameters[e.name]:n&&n.parameters.hasOwnProperty(e.name)&&(t=n.parameters[e.name]):n&&n.parameters.hasOwnProperty(e.name)&&(t=n.parameters[e.name]),t===void 0&&(t=this.context.getDefaultValueForInput(this.model.type,e.name),this._resetReactVirtualDOM&&this._resetReactVirtualDOM()),this.queueInput(e.name,t)}},Node.prototype._onNodeModelVariantUpdated=function(e){this.setVariant(e)};function guid(){function e(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function NodeScope(e,t){this.context=e,this.nodes={},this.componentOwner=t,this.componentInstanceChildren={}}function verifyData(e,t){t.forEach(function(n){if(!e[n])throw new Error("Missing "+n)})}NodeScope.prototype.addConnection=function(e){try{verifyData(e,["sourceId","sourcePort","targetId","targetPort"])}catch(o){throw new Error("Error in connection: "+o.message)}try{var t=this.getNodeWithId(e.sourceId),n=this.getNodeWithId(e.targetId);n.registerInputIfNeeded(e.targetPort),t.registerOutputIfNeeded(e.sourcePort),n.connectInput(e.targetPort,t,e.sourcePort)}catch(o){console.error(o.message)}},NodeScope.prototype.setNodeParameters=function(e,t){const n=this.context.variants.getVariant(t.type,t.variant);if(n)e.setVariant(n);else{const s=t.parameters;var o=Object.keys(s);if(this.context.nodeRegister.hasNode(e.name)){var r=this.context.nodeRegister.getNodeMetadata(e.name);o.sort(function(a,u){var l=r.inputs[a],d=r.inputs[u];return(d?d.inputPriority:0)-(l?l.inputPriority:0)})}o.forEach(a=>{e.registerInputIfNeeded(a),e.hasInput(a)!==!1&&e.queueInput(a,s[a])})}},NodeScope.prototype.createNodeFromModel=async function(e,t){if(e.type==="Component Children"){if(e.parent){var n=this.getNodeWithId(e.parent.id);this.componentOwner.setChildRoot(n)}return}var o;try{o=await this.createNode(e.type,e.id),o.updateOnDirtyFlagging=t!==!1,o.setNodeModel(e)}catch(r){console.error(r.message),this.context.editorConnection&&this.context.isWarningTypeEnabled("nodescope")&&this.context.editorConnection.sendWarning(this.componentOwner.name,e.id,"nodelibrary-unknown-node",{message:r.message,showGlobally:!0});return}return e.variant&&o.setVariant&&o.setVariant(e.variant),this.setNodeParameters(o,e),e.parent&&this.insertNodeInTree(o,e),o},NodeScope.prototype.insertNodeInTree=function(e,t){var n=this.getNodeWithId(t.parent.id),o=t.parent.children.indexOf(t);if(!n.addChild)throw new Error("Node "+n.id+" of type "+n.constructor.name+" can't have children");n.addChild(e,o)},NodeScope.prototype.getNodeWithId=function(e){if(this.nodes.hasOwnProperty(e)===!1)throw new Error("Unknown node id "+e);return this.nodes[e]},NodeScope.prototype.hasNodeWithId=function(e){return this.nodes.hasOwnProperty(e)},NodeScope.prototype.createPrimitiveNode=function(e,t,n){if(t||(t=guid()),this.nodes.hasOwnProperty(t))throw Error("duplicate id "+t);const o=this.context.nodeRegister.createNode(e,t,this);if(n)for(const r in n)o[r]=n[r];return this.nodes[t]=o,o},NodeScope.prototype.createNode=async function(e,t,n){if(t||(t=guid()),this.nodes.hasOwnProperty(t))throw Error("duplicate id "+t);let o;if(this.context.nodeRegister.hasNode(e)){if(o=this.context.nodeRegister.createNode(e,t,this),n)for(const r in n)o[r]=n[r]}else o=await this.context.createComponentInstanceNode(e,t,this,n),this.componentInstanceChildren[t]=o;return this.nodes[t]=o,o},NodeScope.prototype.getNodesWithIdRecursive=function(e){function t(o,r,s){o.nodes.hasOwnProperty(r)&&s.push(o.nodes[r]);var a=Object.keys(o.nodes).filter(function(u){return o.nodes[u]instanceof ComponentInstanceNode});a.forEach(function(u){t(o.nodes[u].nodeScope,r,s)})}var n=[];return t(this,e,n),n},NodeScope.prototype.getNodesWithType=function(e){var t=this,n=Object.keys(this.nodes).filter(function(o){return t.nodes[o].name===e});return n.map(function(o){return t.nodes[o]})},NodeScope.prototype.getNodesWithTypeRecursive=function(e){var t=this;function n(){o=o.concat(t.getNodesWithType(e));var r=Object.keys(t.nodes).filter(function(s){return t.nodes[s]instanceof ComponentInstanceNode});r.forEach(function(s){var a=t.nodes[s].nodeScope.getNodesWithTypeRecursive(e);o=o.concat(a)})}var o=[];return n(),o},NodeScope.prototype.getAllNodesRecursive=function(){let e=[];return(()=>{e=e.concat(Object.values(this.nodes));var n=Object.keys(this.nodes).filter(o=>this.nodes[o]instanceof ComponentInstanceNode);n.forEach(o=>{var r=this.nodes[o].nodeScope.getAllNodesRecursive();e=e.concat(r)})})(),e},NodeScope.prototype.getAllNodesWithVariantRecursive=function(e){return this.getAllNodesRecursive().filter(n=>n.variant===e)},NodeScope.prototype.onNodeModelRemoved=function(e){var t=this.getNodeWithId(e.id);if(e.parent){var n=this.getNodeWithId(e.parent.id);n.removeChild(t)}t._onNodeDeleted(),delete this.nodes[t.id],delete this.componentInstanceChildren[t.id]},NodeScope.prototype.removeConnection=function(e){var t=this.getNodeWithId(e.targetId);t.removeInputConnection(e.targetPort,e.sourceId,e.sourcePort)},NodeScope.prototype.setComponentModel=async function(e){this.componentModel=e;const t=[];for(const o of e.getAllNodes()){const r=await this.createNodeFromModel(o,!1);r&&t.push(r)}e.getAllConnections().forEach(o=>this.addConnection(o)),t.forEach(o=>o.updateOnDirtyFlagging=!0),t.forEach(o=>{o._dirty&&o._performDirtyUpdate()}),e.on("connectionAdded",o=>this.addConnection(o),this),e.on("connectionRemoved",this.removeConnection,this),e.on("nodeAdded",this.createNodeFromModel,this);var n=this;e.on("nodeParentWillBeRemoved",function(o){if(o.type==="Component Children"){o.parent&&this.componentOwner.setChildRoot(null);return}const r=n.getNodeWithId(o.id);r.parent&&r.parent.removeChild(r)},this),e.on("nodeParentUpdated",function(o){if(o.type==="Component Children"){var r=this.getNodeWithId(o.parent.id);this.componentOwner.setChildRoot(r)}else{var s=n.getNodeWithId(o.id);n.insertNodeInTree(s,o)}},this),e.on("nodeRemoved",function(o){o.type!=="Component Children"&&n.onNodeModelRemoved(o)},this);for(const o in this.nodes){const r=this.nodes[o];r.nodeScopeDidInitialize&&r.nodeScopeDidInitialize()}},NodeScope.prototype.reset=function(){this.componentModel&&(this.componentModel.removeListenersWithRef(this),this.componentModel=void 0),Object.keys(this.nodes).forEach(e=>{this.nodes.hasOwnProperty(e)&&this.deleteNode(this.nodes[e])})},NodeScope.prototype.deleteNode=function(e){if(this.nodes.hasOwnProperty(e.id)===!1){console.error("Node doesn't belong to this scope",e.id,e.name);return}if(e.parent&&e.parent.removeChild(e),e.getChildren&&e.getChildren().forEach(t=>{e.removeChild(t),(t.parentNodeScope||t.nodeScope).deleteNode(t)}),this.componentModel){const t=this.componentModel.getConnectionsFrom(e.id),n=this.componentModel.getConnectionsTo(e.id);t.concat(n).forEach(o=>{this.nodes.hasOwnProperty(o.targetId)&&this.nodes.hasOwnProperty(o.sourceId)&&this.removeConnection(o)})}e._onNodeDeleted(),delete this.nodes[e.id],delete this.componentInstanceChildren[e.id]},NodeScope.prototype.sendEventFromThisScope=function(e,t,n,o,r){if(o)for(var s=this.getNodesWithType("Event Receiver").filter(function(m){return m.getChannelName()===e}),a=0;a<s.length;a++){var u=s[a].handleEvent(t);if(u)return!0}if(n==="parent"&&this.componentOwner.parentNodeScope){const m=this.componentOwner.parent?this.componentOwner.parent.nodeScope:this.componentOwner.parentNodeScope;if(!m)return;m.sendEventFromThisScope(e,t,n,!0)}else if(n==="children"){var l=this.nodes;for(var d in l){var p=l[d].children;p&&p.forEach(m=>{if(m.name&&this.context.hasComponentModelWithName(m.name)){var y=m.nodeScope.sendEventFromThisScope(e,t,n,!0);if(y)return!0}})}}else if(n==="siblings"){let m;if(this.componentOwner.parent?m=this.componentOwner.parent.nodeScope:m=this.componentOwner.parentNodeScope,!m)return;var l=m.nodes;for(var d in l){var p=l[d].children;if(p){var f=p.filter(S=>S.name&&this.context.hasComponentModelWithName(S.name)&&S.nodeScope!==this);f.forEach(S=>{var C=S.nodeScope.sendEventFromThisScope(e,t,null,!0);if(C)return!0})}}}return!1};let componentIdCounter=0;function ComponentInstanceNode(e,t,n){Node.call(this,e,t),this.nodeScope=new NodeScope(e,this),this.parentNodeScope=n,this._internal.childRoot=null,this._internal.componentOutputValues={},this._internal.componentOutputs=[],this._internal.componentInputs=[],this._internal.inputValues={},this._internal.roots=[],this._internal.instanceId="__$ndl_componentInstaceId"+componentIdCounter,this.nodeScope.modelScope=n?n.modelScope:void 0,componentIdCounter++}ComponentInstanceNode.prototype=Object.create(Node.prototype,{setComponentModel:{value:async function(e){this.componentModel=e;var t=this;await this.nodeScope.setComponentModel(e),this._internal.componentInputs=this.nodeScope.getNodesWithType("Component Inputs"),this._internal.componentOutputs=this.nodeScope.getNodesWithType("Component Outputs"),Object.values(e.getInputPorts()).forEach(this.registerComponentInputPort.bind(this)),Object.values(e.getOutputPorts()).forEach(this.registerComponentOutputPort.bind(this));const n=e.roots||[];this._internal.roots=n.map(o=>this.nodeScope.getNodeWithId(o)),e.on("rootAdded",o=>{this._internal.roots.push(this.nodeScope.getNodeWithId(o)),this.forceUpdate()},this),e.on("rootRemoved",function(o){const r=this._internal.roots.findIndex(s=>s.id===o);r!==-1&&this._internal.roots.splice(r,1),this.forceUpdate()},this),e.on("inputPortAdded",this.registerComponentInputPort.bind(this),this),e.on("outputPortAdded",this.registerComponentOutputPort.bind(this),this),e.on("inputPortRemoved",function(o){t.hasInput(o.name)&&t.deregisterInput(o.name)},this),e.on("outputPortRemoved",function(o){this.hasOutput(o.name)&&t.deregisterOutput(o.name)},this),e.on("nodeAdded",function(o){o.type==="Component Inputs"?t._internal.componentInputs.push(t.nodeScope.getNodeWithId(o.id)):o.type==="Component Outputs"&&t._internal.componentOutputs.push(t.nodeScope.getNodeWithId(o.id))},this),e.on("nodeRemoved",function(o){function r(s,a){return s.filter(u=>u.id!==a)}o.type==="Component Inputs"?t._internal.componentInputs=r(t._internal.componentInputs,o.id):o.type==="Component Outputs"&&(t._internal.componentOutputs=r(t._internal.componentOutputs,o.id))},this),e.on("renamed",function(o){t.name=o.newName},this)}},_onNodeDeleted:{value(){this.componentModel&&(this.componentModel.removeListenersWithRef(this),this.componentModel=void 0),this.nodeScope.reset(),Node.prototype._onNodeDeleted.call(this)}},registerComponentInputPort:{value(e){this.registerInput(e.name,{set(t){this._internal.inputValues[e.name]=t,this._internal.componentInputs.forEach(function(n){n.registerOutputIfNeeded(e.name),n.flagOutputDirty(e.name)})}})}},registerComponentOutputPort:{value(e){this.registerOutput(e.name,{getter(){return this._internal.componentOutputValues[e.name]}})}},setOutputFromComponentOutput:{value(e,t){this.hasOutput(e)!==!1&&(this._internal.creatorCallbacks&&this._internal.creatorCallbacks.onOutputChanged&&this._internal.creatorCallbacks.onOutputChanged(e,t,this._internal.componentOutputValues[e]),this._internal.componentOutputValues[e]=t,this.flagOutputDirty(e))}},setChildRoot:{value(e){const t=this._internal.childRoot,n=e;if(this._internal.childRoot=n,this.model&&this.model.children){const o=this.parentNodeScope,r=this.model.children.filter(s=>s.type!=="Component Children").map(s=>o.getNodeWithId(s.id));if(t)for(let s=0;s<r.length;s++)t.isChild(r[s])&&t.removeChild(r[s]);if(n)for(let s=0;s<r.length;s++){const a=r[s],u=a.model.parent.children.indexOf(a.model);this.addChild(a,u)}}}},getChildRootIndex:{value(){if(!this._internal.childRoot||!this._internal.childRoot.model||!this._internal.childRoot.model.children)return 0;for(var e=this._internal.childRoot.model.children,t=0;t<e.length;t++)if(e[t].type==="Component Children")return t;return 0}},getChildRoot:{value(){return this._internal.childRoot?this._internal.childRoot:null}},getRoots:{value(){return this._internal.roots}},triggerDidMount:{value(){this._internal.roots.forEach(e=>{e.triggerDidMount&&e.triggerDidMount()})}},render:{value(){return this._internal.roots.length===0?null:this._internal.roots[0].render()}},setChildIndex:{value(e){this.getRoots().forEach(t=>t.setChildIndex&&t.setChildIndex(e))}},addChild:{value(e,t){this.getChildRoot().addChild(e,t+this.getChildRootIndex())}},removeChild:{value(e){this.getChildRoot().removeChild(e)}},getChildren:{value(e){const t=this.getChildRoot();return t?t.getChildren():[]}},isChild:{value(e){return this.getChildRoot()?this.getChildRoot().isChild(e):!1}},contains:{value(e){return this.getRoots().some(t=>t.contains&&t.contains(e))}},_performDirtyUpdate:{value(){Node.prototype._performDirtyUpdate.call(this);for(var e=this._internal.componentInputs,t=0,n=e.length;t<n;t++)e[t].flagDirty();this._internal.componentOutputs.forEach(function(o){o.flagDirty()})}},getRef:{value(){const e=this._internal.roots[0];return e?e.getRef():void 0}},update:{value(){Node.prototype.update.call(this),this._internal.componentOutputs.forEach(function(e){e.update()})}},forceUpdate:{value(){this.parent&&(this.parent.cachedChildren=void 0,this.parent.forceUpdate())}},getInstanceId:{value(){return this._internal.instanceId}}}),ComponentInstanceNode.prototype.constructor=ComponentInstanceNode;function NodeContext(e){e=e||{},e.runningInEditor=e.hasOwnProperty("runningInEditor")?e.runningInEditor:!1,this._dirtyNodes=[],this.callbacksAfterUpdate=[],this.graphModel=e.graphModel,this.platform=e.platform,this.eventEmitter=new EventEmitter,this.eventEmitter.setMaxListeners(1e6),this.eventSenderEmitter=new EventEmitter,this.eventSenderEmitter.setMaxListeners(1e6),this.globalValues={},this.globalsEventEmitter=new EventEmitter,this.globalsEventEmitter.setMaxListeners(1e6),this.runningInEditor=e.runningInEditor,this.currentFrameTime=0,this.frameNumber=0,this.updateIteration=0,this.nodeRegister=new NodeRegister(this),this.timerScheduler=new TimerScheduler(this.scheduleUpdate.bind(this)),this.componentModels={},this.debugInspectorsEnabled=!1,this.connectionsToPulse={},this.connectionsToPulseChanged=!1,this.debugInspectors={},this.connectionPulsingCallbackScheduled=!1,this.editorConnection=e.editorConnection,this.rootComponent=void 0,this._outputHistory={},this._signalHistory={},this.warningTypes={},this.bundleFetchesInFlight=new Map,this.variants=new Variants({graphModel:this.graphModel,getNodeScope:()=>this.rootComponent?this.rootComponent.nodeScope:null}),this.editorConnection&&(this.editorConnection.on("debugInspectorsUpdated",t=>{this.onDebugInspectorsUpdated(t)}),this.editorConnection.on("getConnectionValue",({clientId:t,connectionId:n})=>{if(this.editorConnection.clientId!==t)return;const o=this._outputHistory[n];this.editorConnection.sendConnectionValue(n,o?o.value:void 0)}))}NodeContext.prototype.setRootComponent=function(e){this.rootComponent=e},NodeContext.prototype.getCurrentTime=function(){return this.platform.getCurrentTime()},NodeContext.prototype.onDebugInspectorsUpdated=function(e){this.debugInspectorsEnabled&&(e=e.map(t=>{if(t.type==="connection"){const n=t.connection;t.id=n.fromId+n.fromProperty}else t.type==="node"&&(t.id=t.nodeId);return t}),this.debugInspectors={},e.forEach(t=>this.debugInspectors[t.id]=t),this.sendDebugInspectorValues())},NodeContext.prototype.updateDirtyNodes=function(){var e,t,n=!0,o=0;for(this.updateIteration++,this.isUpdating=!0;n&&o<10;){var r=this._dirtyNodes;for(this._dirtyNodes=[],e=0,t=r.length;e<t;++e)try{r[e]._deleted||r[e].update()}catch(a){console.error(a,a.stack)}var s=this.callbacksAfterUpdate;for(this.callbacksAfterUpdate=[],e=0,t=s.length;e<t;e++)try{s[e]()}catch(a){console.error(a)}n=this.callbacksAfterUpdate.length>0||this._dirtyNodes.length>0,o++}this.isUpdating=!1},NodeContext.prototype.update=function(){this.frameNumber++,this.updateDirtyNodes(),this.timerScheduler.hasPendingTimers()&&(this.scheduleUpdate(),this.timerScheduler.runTimers(this.currentFrameTime)),this.debugInspectorsEnabled&&this.sendDebugInspectorValues()},NodeContext.prototype.reset=function(){this.eventEmitter.emit("applicationDataReloaded");var e=this.eventEmitter;["frameStart","frameEnd"].forEach(function(t){e.removeAllListeners(t)}),this.globalValues={},this._dirtyNodes.length=0,this.callbacksAfterUpdate.length=0,this.timerScheduler.runningTimers=[],this.timerScheduler.newTimers=[],this.rootComponent=void 0,this.clearDebugInspectors()},NodeContext.prototype.nodeIsDirty=function(e){this._dirtyNodes.push(e),this.scheduleUpdate()},NodeContext.prototype.scheduleUpdate=function(){this.eventEmitter.emit("scheduleUpdate")},NodeContext.prototype.scheduleAfterUpdate=function(e){this.callbacksAfterUpdate.push(e),this.scheduleUpdate()},NodeContext.prototype.scheduleNextFrame=function(e){this.eventEmitter.once("frameStart",e),this.scheduleUpdate()},NodeContext.prototype.setGlobalValue=function(e,t){this.globalValues[e]=t,this.globalsEventEmitter.emit(e)},NodeContext.prototype.getGlobalValue=function(e){return this.globalValues[e]},NodeContext.prototype.registerComponentModel=function(e){if(this.componentModels.hasOwnProperty(e.name))throw new Error("Duplicate component name "+e.name);this.componentModels[e.name]=e;var t=this;e.on("renamed",function(n){delete t.componentModels[n.oldName],t.componentModels[n.newName]=e},this)},NodeContext.prototype.deregisterComponentModel=function(e){this.componentModels.hasOwnProperty(e.name)&&(this.componentModels[e.name].removeListenersWithRef(this),delete this.componentModels[e.name])},NodeContext.prototype.fetchComponentBundle=async function(e){const t=async n=>{let r=`${Noodl.Env.BaseUrl||"/"}noodl_bundles/${n}.json`;const s=await fetch(r);if(s.status===404)throw new Error("Component not found "+n);const a=await s.json();for(const u of a)this.graphModel.hasComponentWithName(u.name)===!1&&await this.graphModel.importComponentFromEditorData(u)};if(this.bundleFetchesInFlight.has(e))await this.bundleFetchesInFlight.get(e);else{const n=t(e);this.bundleFetchesInFlight.set(e,n),await n}},NodeContext.prototype.getComponentModel=async function(e){if(!e)throw new Error("Component instance must have a name");if(this.componentModels.hasOwnProperty(e)===!1){const t=this.graphModel.getBundleContainingComponent(e);if(!t)throw new Error("Can't find component model for "+e);for(const n of this.graphModel.getBundleDependencies(t))this.fetchComponentBundle(n);await this.fetchComponentBundle(t)}return this.componentModels[e]},NodeContext.prototype.hasComponentModelWithName=function(e){return this.componentModels.hasOwnProperty(e)},NodeContext.prototype.createComponentInstanceNode=async function(e,t,n,o){var r=new ComponentInstanceNode(this,t,n);r.name=e;for(const a in o)r[a]=o[a];const s=await this.getComponentModel(e);return await r.setComponentModel(s),r},NodeContext.prototype._formatConnectionValue=function(e){if(typeof e=="object"&&e&&e.constructor&&e.constructor.name==="Node")e="<Node> "+e.name;else if(typeof e=="object"&&typeof window<"u"&&e instanceof HTMLElement)e=`DOM Node <${e.tagName}>`;else{if(typeof e=="string"&&!e.startsWith("[Signal]"))return'"'+e+'"';if(Number.isNaN(e))return"NaN"}return e},NodeContext.prototype.connectionSentValue=function(e,t){if(!this.editorConnection||!this.editorConnection.isConnected()||!this.debugInspectorsEnabled)return;const n=this.getCurrentTime();if(this._outputHistory[e.id]={value:t,timestamp:n},this.connectionsToPulse.hasOwnProperty(e.id)){this.connectionsToPulse[e.id].timestamp=n;return}const o=[];e.connections.forEach(r=>{o.push(e.owner.id+e.name+r.node.id+r.inputPortName)}),this.connectionsToPulse[e.id]={timestamp:n,connections:o},this.connectionsToPulseChanged=!0,this.connectionPulsingCallbackScheduled===!1&&(this.connectionPulsingCallbackScheduled=!0,setTimeout(this.clearOldConnectionPulsing.bind(this),100))},NodeContext.prototype.connectionSentSignal=function(e){const t=e.id;this._signalHistory.hasOwnProperty(t)||(this._signalHistory[t]={count:0}),this._signalHistory[t].count++,this.connectionSentValue(e,"[Signal] Trigger count "+this._signalHistory[t].count)},NodeContext.prototype.clearDebugInspectors=function(){this.debugInspectors={},this.connectionsToPulse={},this.editorConnection.sendPulsingConnections(this.connectionsToPulse)},NodeContext.prototype.clearOldConnectionPulsing=function(){this.connectionPulsingCallbackScheduled=!1;var e=this.getCurrentTime(),t=this,n=Object.keys(this.connectionsToPulse);n.forEach(function(o){var r=t.connectionsToPulse[o];e-r.timestamp>100&&(t.connectionsToPulseChanged=!0,delete t.connectionsToPulse[o])}),this.connectionsToPulseChanged&&(this.connectionsToPulseChanged=!1,this.editorConnection.sendPulsingConnections(this.connectionsToPulse)),Object.keys(this.connectionsToPulse).length>0&&(this.connectionPulsingCallbackScheduled=!0,setTimeout(this.clearOldConnectionPulsing.bind(this),500))},NodeContext.prototype._getDebugInspectorValueForNode=function(e){if(!this.rootComponent)return;const t=this.rootComponent.nodeScope.getNodesWithIdRecursive(e),n=t[t.length-1];if(n&&n.getInspectInfo){const o=n.getInspectInfo();if(o!==void 0)return{type:"node",id:e,value:o}}},NodeContext.prototype.sendDebugInspectorValues=function(){const e=[];for(const t in this.debugInspectors){const n=this.debugInspectors[t];if(n.type==="connection"&&this._outputHistory.hasOwnProperty(t)){const o=this._outputHistory[t].value;e.push({type:"connection",id:t,value:this._formatConnectionValue(o)})}else if(n.type==="node"){const o=this._getDebugInspectorValueForNode(t);o&&e.push(o)}}e.length>0&&this.editorConnection.sendDebugInspectorValues(e),this.connectionsToPulseChanged&&(this.connectionsToPulseChanged=!1,this.editorConnection.sendPulsingConnections(this.connectionsToPulse))},NodeContext.prototype.setDebugInspectorsEnabled=function(e){this.debugInspectorsEnabled=e,this.editorConnection.debugInspectorsEnabled=e,e&&this.sendDebugInspectorValues()},NodeContext.prototype.sendGlobalEventFromEventSender=function(e,t){this.eventSenderEmitter.emit(e,t)},NodeContext.prototype.setPopupCallbacks=function({onShow:e,onClose:t}){this.onShowPopup=e,this.onClosePopup=t},NodeContext.prototype.showPopup=async function(e,t,n){if(!this.onShowPopup)return;const o=this.rootComponent.nodeScope,r=await o.createNode(e);for(const d in t)r.setInputValue(d,t[d]);r.popupParent=n?.senderNode||null;const s=o.createPrimitiveNode("Group");s.setInputValue("flexDirection","node"),s.setInputValue("cssClassName","noodl-popup");const a=this.graphModel.getSettings().bodyScroll;s.setInputValue("position",a?"fixed":"absolute");var u=r.nodeScope.getNodesWithType("NavigationClosePopup");if(u&&u.length>0)for(var l=0;l<u.length;l++)u[l]._setCloseCallback((d,p)=>{this.scheduleNextFrame(()=>{o.hasNodeWithId(s.id)&&(this.onClosePopup(s),o.deleteNode(s),n&&n.onClosePopup&&n.onClosePopup(d,p))})});this.onShowPopup(s),requestAnimationFrame(()=>{s.addChild(r)})},NodeContext.prototype.setWarningTypes=function(e){Object.assign(this.warningTypes,e)},NodeContext.prototype.isWarningTypeEnabled=function(e){return this.warningTypes.hasOwnProperty(e)?!!this.warningTypes[e]:!0},NodeContext.prototype.getDefaultValueForInput=function(e,t){if(this.nodeRegister.hasNode(e)===!1)return;const o=this.nodeRegister.getNodeMetadata(e).inputs[t];if(o)return o.type.defaultUnit?{value:o.default,unit:o.type.defaultUnit}:o.default};function EventSender(){this.listeners={},this.listenersWithRefs={}}EventSender.prototype.on=function(e,t,n){n?(this.listenersWithRefs.hasOwnProperty(e)||(this.listenersWithRefs[e]=new Map),this.listenersWithRefs[e].get(n)||this.listenersWithRefs[e].set(n,[]),this.listenersWithRefs[e].get(n).push(t)):(this.listeners.hasOwnProperty(e)||(this.listeners[e]=[]),this.listeners[e].push(t))},EventSender.prototype.removeListenersWithRef=function(e){Object.keys(this.listenersWithRefs).forEach(t=>{const n=this.listenersWithRefs[t];n.has(e)&&n.delete(e)})},EventSender.prototype.removeAllListeners=function(e){e?(delete this.listeners[e],delete this.listenersWithRefs[e]):(this.listeners={},this.listenersWithRefs={})},EventSender.prototype.emit=async function(e,t){const n=this.listeners[e];if(n)for(let r=0;r<n.length;r++){const s=n[r];await Promise.resolve(s.call(null,t))}const o=this.listenersWithRefs[e];if(o)for(const[r,s]of o)for(const a of s)await Promise.resolve(a.call(r,t))};function Services(){}Services.events=new EventEmitter;class ActiveWarnings{constructor(){this.currentWarnings=new Map}setWarning(t,n,o){if(this.currentWarnings.has(t)){const r=this.currentWarnings.get(t);return r[n]===o?!1:(r[n]=o,!0)}else return this.currentWarnings.set(t,{[n]:o}),!0}clearWarning(t,n){const o=this.currentWarnings.get(t);return!o||!o[n]?!1:(delete o[n],Object.keys(o).length===0&&delete this.currentWarnings.delete(t),!0)}clearWarnings(t){return this.currentWarnings.has(t)===!1?!1:(this.currentWarnings.delete(t),!0)}}function EditorConnection(e){var t=e||{};EventSender.call(this),this.runtimeType=t.runtimeType,this.platform=t.platform,this.ws=t.platform&&t.platform.webSocketClass||(typeof WebSocket<"u"?WebSocket:void 0),this.wsOptions=t.platform&&t.platform.webSocketOptions||void 0,this.reconnectOnClose=!0,this.enableDebugger=!1,this.lastSendTimestamp=0,this.sendQueue=[],this.sendTimer=void 0,this.activeWarnings=new ActiveWarnings}EditorConnection.prototype=Object.create(EventSender.prototype),EditorConnection.prototype.constructor=EditorConnection,EditorConnection.prototype.isRunningLocally=function(){var e=this.platform.isRunningLocally&&this.platform.isRunningLocally()||typeof document<"u"&&(document.location.hostname==="localhost"||document.location.hostname==="127.0.0.1");return e},EditorConnection.prototype.connect=function(e){this.socket=this.wsOptions?new this.ws(e,this.wsOptions):new this.ws(e);var t=this;this.socket.addEventListener("open",function(){t.clientId=guid(),t.socket.send(JSON.stringify({cmd:"register",type:"viewer",clientId:t.clientId})),t.emit("connected")}),this.socket.addEventListener("close",function(n){t.reconnectOnClose&&t.reconnect(e),console.log("Editor connection closed",n.code,n.reason),t.emit("connectionClosed")}),this.socket.addEventListener("error",function(n){console.log("Editor connection error, trying to reconnect")}),this.socket.addEventListener("message",async n=>{const o=typeof n.data=="string"?n.data:await n.data.text(),r=JSON.parse(o);let s;r.cmd==="registered"||(r.cmd==="export"?(s=JSON.parse(r.content),r.type==="full"&&r.target===this.clientId&&t.emit("exportDataFull",s)):r.cmd==="hoverStart"?t.emit("hoverStart",r.content.id):r.cmd==="hoverEnd"?t.emit("hoverEnd",r.content.id):r.cmd==="refresh"?t.emit("reload"):r.cmd==="debugInspectors"?this.debugInspectorsEnabled&&(s=JSON.parse(r.content),t.emit("debugInspectorsUpdated",s.inspectors)):r.cmd==="debuggingEnabled"?t.isRunningLocally()&&(s=JSON.parse(r.content),t.emit("debuggingEnabledChanged",s.enabled)):r.cmd==="getConnectionValue"?t.isRunningLocally()&&(s=JSON.parse(r.content),await t.emit("getConnectionValue",{clientId:s.clientId,connectionId:s.connectionId})):r.cmd==="modelUpdate"?await t.emit("modelUpdate",r.content):r.cmd==="publish"?Services.pubsub.routeMessage(r):r.cmd==="noodlModules"?t.emit("noodlModules",JSON.parse(r.content)):r.cmd==="mqttUpdate"?t.emit("mqttUpdate",r.content):r.cmd==="activeComponentChanged"?t.emit("activeComponentChanged",r.component):console.log("Command not implemented",r))})},EditorConnection.prototype.reconnect=function(e){var t=this;setTimeout(function(){t.connect(e)},2e3)},EditorConnection.prototype.isConnected=function(){return this.socket!==void 0&&this.socket.readyState===this.ws.OPEN};const getCircularReplacer=()=>{const e=new WeakSet;return(t,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n}};EditorConnection.prototype.send=function(e){const t=this.platform.getCurrentTime(),n=t-this.lastSendTimestamp,o=r=>{try{this.socket.send(JSON.stringify(r))}catch(s){if(s.message&&s.message.startsWith("Converting circular"))try{this.socket.send(JSON.stringify(r,getCircularReplacer()))}catch(a){console.log("failed to send message to editor",r,a)}else console.log("failed to send message to editor",r,s)}};n<200||this.sendTimer||!this.isConnected()?(this.sendQueue.push(e),this.sendTimer||(this.sendTimer=setTimeout(()=>{if(this.isConnected()===!1)return;const r=50;for(let s=0;s<this.sendQueue.length;s+=r){const a=this.sendQueue.slice(s,s+r);o(a)}this.sendQueue=[],this.sendTimer=void 0,this.lastSendTimestamp=this.platform.getCurrentTime()},100))):(this.lastSendTimestamp=t,o(e))},EditorConnection.prototype.sendInspectId=function(e){this.send({cmd:"select",type:"viewer",content:JSON.stringify({id:e})})},EditorConnection.prototype.sendSelectComponent=function(e){this.send({cmd:"select",type:"viewer",content:JSON.stringify({componentName:e})})},EditorConnection.prototype.sendPulsingConnections=function(e){var t=[];Object.keys(e).forEach(function(n){var o=e[n];t=t.concat(o.connections)}),this.send({cmd:"connectiondebugpulse",type:"viewer",content:JSON.stringify({connectionsToPulse:t})})},EditorConnection.prototype.sendDebugInspectorValues=function(e){this.send({cmd:"debuginspectorvalues",type:"viewer",content:{inspectors:e}})},EditorConnection.prototype.sendConnectionValue=function(e,t){this.send({cmd:"connectionValue",type:"viewer",content:{connectionId:e,value:t}})};const dynamicPortsHash={};function _detectRename(e,t){if(!(!e||!t)&&e.length===t.length){for(var n={},o=0;o<e.length;o++){if(t.indexOf(e[o])===-1){if(n.before)return;n.before=e[o]}if(e.indexOf(t[o])===-1){if(n.after)return;n.after=t[o]}}return n.before&&n.after?n:void 0}}EditorConnection.prototype.sendDynamicPorts=function(e,t,n){var o=JSON.stringify(t);if(dynamicPortsHash[e]!==o){if(dynamicPortsHash[e]&&t&&n&&n.detectRenamed){var r=Array.isArray(n.detectRenamed)?n.detectRenamed:[n.detectRenamed],s=[];r.forEach(a=>{var u=JSON.parse(dynamicPortsHash[e]),l=[].concat(t);a.prefix&&(u=u.filter(p=>p.name.startsWith(a.prefix)),l=l.filter(p=>p.name.startsWith(a.prefix))),a.plug&&(u=u.filter(p=>p.plug===a.plug),l=l.filter(p=>p.plug===a.plug)),l=l.map(p=>p.name.substring((a.prefix||"").length)),u=u.map(p=>p.name.substring((a.prefix||"").length));var d=_detectRename(u,l);d&&s.push({plug:a.plug,patterns:[(a.prefix||"")+"{{*}}"],before:d.before,after:d.after})}),s.length>0&&(n.renamed=s),delete n.detectRenamed}dynamicPortsHash[e]=o,this.send({cmd:"instanceports",type:"viewer",content:JSON.stringify({nodeid:e,ports:t,options:n})})}},EditorConnection.prototype.sendWarning=function(e,t,n,o){this.activeWarnings.setWarning(t,n,o)&&this.send({cmd:"showwarning",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t,key:n,warning:o})})},EditorConnection.prototype.clearWarning=function(e,t,n){this.activeWarnings.clearWarning(t,n)&&this.send({cmd:"showwarning",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t,key:n,warning:void 0})})},EditorConnection.prototype.clearWarnings=function(e,t){this.activeWarnings.clearWarnings(t)&&this.send({cmd:"clearwarnings",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t})})},EditorConnection.prototype.sendPatches=function(e){this.send({cmd:"patchproject",type:"viewer",content:JSON.stringify(e)})},EditorConnection.prototype.requestFullExport=function(){this.send({cmd:"register",type:"viewer"})},EditorConnection.prototype.requestNoodlModules=function(){this.send({cmd:"getNoodlModules",type:"viewer"})};var serviceRequests={};EditorConnection.prototype.sendServiceRequest=function(e,t){e.token=guid(),e.clientId=this.clientId,serviceRequests[e.token]=t,this.send(e)},EditorConnection.prototype.close=function(){this.reconnectOnClose=!1,this.isConnected()!==!1&&this.socket.close()},EditorConnection.prototype.sendNodeLibrary=function(e){this.send({cmd:"nodelibrary",type:"viewer",runtimeType:this.runtimeType,content:e,clientId:this.clientId})},EditorConnection.prototype.sendComponentMetadata=function(e,t,n){this.send({cmd:"componentMetadata",type:"viewer",content:JSON.stringify({componentName:e,key:t,data:n})})},EditorConnection.prototype.sendProjectMetadata=function(e,t){this.send({cmd:"projectMetadata",type:"viewer",content:JSON.stringify({key:e,data:t})})};function formatDynamicPorts(e){const t=[];for(const n of e.dynamicports)if(n.ports||n.template||n.port||n.channelPort)t.push(n);else if(n.inputs||n.outputs){const o=[];if(n.inputs)for(const s of n.inputs)o.push(formatPort(s,e.inputs[s],"input"));if(n.outputs)for(const s of n.outputs)o.push(formatPort(s,e.outputs[s],"output"));const r={name:n.name||"conditionalports/basic",condition:n.condition,ports:o};t.push(r)}return t}function formatPort(e,t,n){var o={name:e,type:t.type,plug:n};return t.group&&(o.group=t.group),t.displayName&&(o.displayName=t.displayName),t.description&&(o.description=t.description),t.editorName&&(o.editorName=t.editorName),t.default!==void 0&&(o.default=t.default),t.hasOwnProperty("index")&&(o.index=t.index),t.tooltip&&(o.tooltip=t.tooltip),t.tab&&(o.tab=t.tab),t.popout&&(o.popout=t.popout),t.allowVisualStates&&(o.allowVisualStates=t.allowVisualStates),o}function generateNodeLibrary(e){var t={typecasts:[{from:"string",to:["number","boolean","image","color","enum","textStyle","dimension","array","object"]},{from:"boolean",to:["number","string","signal"]},{from:"number",to:["boolean","string","dimension"]},{from:"date",to:["string"]},{from:"signal",to:["boolean","number"]},{from:"image",to:[]},{from:"cloudfile",to:["string","image"]},{from:"color",to:[]},{from:"enum",to:[]},{from:"object",to:[]},{from:"domelement",to:[]},{from:"reference",to:[]},{from:"font",to:[]},{from:"textStyle",to:["string"]},{from:"collection",to:["array"]},{from:"array",to:["collection"]}],dynamicports:[{type:"conditionalports",name:"basic"},{type:"expand",name:"basic"}],colors:{nodes:{component:{base:"#643D8B",baseHighlighted:"#79559b",header:"#4E2877",headerHighlighted:"#643d8b",outline:"#4E2877",outlineHighlighted:"#b58900",text:"#dbd0e4"},visual:{base:"#315272",baseHighlighted:"#4d6784",header:"#173E5D",headerHighlighted:"#315272",outline:"#173E5D",outlineHighlighted:"#b58900",text:"#cfd5de"},data:{base:"#465524",baseHighlighted:"#5b6a37",header:"#314110",headerHighlighted:"#465524",outline:"#314110",outlineHighlighted:"#b58900",text:"#d2d6c5"},javascript:{base:"#7E3660",baseHighlighted:"#944e74",header:"#67214B",headerHighlighted:"#7e3660",outline:"#67214B",outlineHighlighted:"#d57bab",text:"#e4cfd9"},default:{base:"#4C4F59",baseHighlighted:"#62656e",header:"#373B45",headerHighlighted:"#4c4f59",outline:"#373B45",outlineHighlighted:"#b58900",text:"#d3d4d6"}},connections:{signal:{normal:"#006f82",highlighted:"#7ec2cf",pulsing:"#ffffff"},default:{normal:"#875d00",highlighted:"#e5ae32",pulsing:"#ffffff"}}},nodetypes:[{name:"Component Children",shortDesc:"This node is a placeholder for where children of this component will be inserted.",docs:"https://docs.noodl.net/nodes/component-utilities/component-children",color:"component",allowAsChild:!0,category:"Visual",haveComponentChildren:["Visual"]}]},n=Object.keys(e._constructors);n.forEach(function(s){var a=e._constructors[s].metadata,u={name:s,searchTags:a.searchTags};t.nodetypes.push(u),a.version&&(u.version=a.version),a.displayNodeName&&(u.displayNodeName=a.displayNodeName),a.nodeDoubleClickAction&&(u.nodeDoubleClickAction=a.nodeDoubleClickAction),a.shortDesc&&(u.shortDesc=a.shortDesc),a.module&&(u.module=a.module),a.deprecated&&(u.deprecated=!0),a.haveComponentPorts&&(u.haveComponentPorts=!0),a.category==="Visual"&&(u.allowAsChild=!0,u.allowAsExportRoot=!0,u.color="visual"),a.allowAsExportRoot!==void 0&&(u.allowAsExportRoot=a.allowAsExportRoot),a.allowChildren&&(u.allowChildrenWithCategory=["Visual"],u.color="visual"),a.allowChildrenWithCategory&&(u.allowChildrenWithCategory=a.allowChildrenWithCategory),a.singleton&&(u.singleton=!0),a.allowAsChild&&(u.allowAsChild=!0),a.docs&&(u.docs=a.docs),a.shortDocs?u.shortDocs=a.shortDocs:a.docs&&a.docs.indexOf("https://docs.noodl.net")===0&&(u.shortDocs=a.docs.replace("/#","")+"-short.md"),u.category=a.category,a.panels&&(u.panels=a.panels),a.usePortAsLabel&&(u.usePortAsLabel=a.usePortAsLabel,u.portLabelTruncationMode=a.portLabelTruncationMode),a.color&&(u.color=a.color),a.dynamicports&&(u.dynamicports=formatDynamicPorts(a)),a.exportDynamicPorts&&(u.exportDynamicPorts=a.exportDynamicPorts),a.visualStates&&(u.visualStates=a.visualStates),a.useVariants&&(u.useVariants=a.useVariants),a.connectionPanel&&(u.connectionPanel=a.connectionPanel),u.ports=[];var l=u.dynamicports||[],d={},p={};l.filter(m=>m.channelPort!==void 0).forEach(m=>{p[m.channelPort.plug+"/"+m.channelPort.name]=!0}),l.length&&(u.dynamicports=l),Object.keys(a.inputs).forEach(function(m){if(!(d.hasOwnProperty("input/"+m)||p.hasOwnProperty("input/"+m))){var y=a.inputs[m];y.exportToEditor!==!1&&u.ports.push(formatPort(m,y,"input"))}});function f(m,y){var v={name:m,type:y.type,plug:"output"};y.group&&(v.group=y.group),y.displayName&&(v.displayName=y.displayName),y.editorName&&(v.editorName=y.editorName),y.hasOwnProperty("index")&&(v.index=y.index),u.ports.push(v)}Object.keys(a.outputs).forEach(function(m){if(!(d.hasOwnProperty("output/"+m)||p.hasOwnProperty("output/"+m))){var y=a.outputs[m];f(m,y)}})});const o=[{name:"UI Elements",description:"Buttons, inputs, containers, media",type:"visual",subCategories:[{name:"Basic Elements",items:["Group","net.noodl.visual.columns","Text","Image","Video","Circle","net.noodl.visual.icon"]},{name:"UI Controls",items:["net.noodl.controls.button","net.noodl.controls.checkbox","net.noodl.controls.options","net.noodl.controls.radiobutton","Radio Button Group","net.noodl.controls.range","net.noodl.controls.textinput"]}]},{name:"Navigation & Popups",description:"Page routing, navigation, popups",type:"logic",subCategories:[{name:"Navigation",items:["Router","RouterNavigate","PageInputs","net.noodl.externallink","PageStackNavigateToPath"]},{name:"Component Stack",items:["Page Stack","PageStackNavigate","PageStackNavigateBack"]},{name:"Popups",items:["NavigationShowPopup","NavigationClosePopup"]}]},{name:"Logic & Utilities",description:"Logic, events, string manipulation",type:"logic",subCategories:[{name:"General Utils",items:["States","Value Changed","Timer","Color Blend","Number Remapper","Counter","Drag","net.noodl.animatetovalue"]},{name:"Logic",items:["Boolean To String","Switch","And","Or","Condition","Inverter"]},{name:"Events",items:["Event Sender","Event Receiver"]},{name:"String Manipulation",items:["Substring","String Mapper","String Format","Date To String","Unique Id"]},{name:"System",items:["Screen Resolution","Open File Picker"]},{name:"Variables",items:["String","Boolean","Color","Number"]}]},{name:"Component Utilities",description:"Component inputs, outputs & object",type:"component",subCategories:[{name:"",items:["Component Inputs","Component Outputs","Component Children","net.noodl.ComponentObject","net.noodl.ParentComponentObject","net.noodl.SetComponentObjectProperties","net.noodl.SetParentComponentObjectProperties"]}]},{name:"Read & Write Data",description:"Arrays, objects, cloud data",type:"data",subCategories:[{name:"",items:["RunTasks","For Each","For Each Actions","Model2","SetModelProperties","NewModel","Set Variable","Variable2"]},{name:"Array",items:["Collection2","CollectionNew","CollectionRemove","CollectionClear","CollectionInsert","Filter Collection","Map Collection","Static Data"]},{name:"Cloud Data",items:["DbModel2","NewDbModelProperties","FilterDBModels","SetDbModelProperties","DbCollection2","DeleteDbModelProperties","AddDbModelRelation","RemoveDbModelRelation","Cloud File","Upload File","CloudFunction2","DbConfig"]},{name:"User",items:["net.noodl.user.LogIn","net.noodl.user.LogOut","net.noodl.user.SignUp","net.noodl.user.User","net.noodl.user.SetUserProperties","net.noodl.user.VerifyEmail","net.noodl.user.SendEmailVerification","net.noodl.user.ResetPassword","net.noodl.user.RequestPasswordReset"]},{name:"External Data",items:["REST2"]}]},{name:"Custom Code",description:"Custom JavaScript and CSS",type:"javascript",subCategories:[{name:"",items:["Expression","JavaScriptFunction","Javascript2","CSS Definition"]}]},{name:"Cloud Functions",description:"Nodes to be used in cloud functions",type:"data",subCategories:[{name:"",items:["noodl.cloud.request","noodl.cloud.response"]},{name:"Cloud Data",items:["noodl.cloud.aggregate"]}]}];t.nodeIndex={coreNodes:o};const r=[];return n.forEach(s=>{e._constructors[s].metadata.module&&r.push(s)}),r.length&&(t.nodeIndex.moduleNodes=[{name:"",items:r}]),t}function addModuleSettings(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.settings&&o.settings.forEach(function(r){e.ports.push(r)})}}function generateProjectSettings(e,t){const n={dynamicports:[],ports:[]};return addModuleSettings(n,t),n}function NodeModel(e,t){EventSender.call(this),this.id=e,this.type=t,this.inputs=[],this.outputs=[],this.children=[],this.parameters={},this.inputPorts={},this.outputPorts={}}NodeModel.prototype=Object.create(EventSender.prototype),NodeModel.prototype.setParameter=function(e,t,n){n?(this.stateParameters||(this.stateParameters={}),this.stateParameters[n]||(this.stateParameters[n]={}),t===void 0?delete this.stateParameters[n][e]:this.stateParameters[n][e]=t):t===void 0?delete this.parameters[e]:this.parameters[e]=t,this.emit("parameterUpdated",{name:e,value:t,state:n})},NodeModel.prototype.setParameters=function(e){Object.keys(e).forEach(t=>{this.setParameter(t,e[t])})},NodeModel.prototype.setStateParameters=function(e){this.stateParameters=e},NodeModel.prototype.setStateTransitions=function(e){this.stateTransitions=e},NodeModel.prototype.setStateTransitionParamter=function(e,t,n){this.stateTransitions||(this.stateTransitions={}),t?this.stateTransitions[n][e]=t:delete this.stateTransitions[n][e]},NodeModel.prototype.setDefaultStateTransition=function(e,t){this.defaultStateTransitions||(this.defaultStateTransitions={}),this.defaultStateTransitions[t]=e},NodeModel.prototype.addInputPort=function(e){this.inputPorts[e.name]=e,this.emit("inputPortAdded",e)},NodeModel.prototype.getInputPort=function(e){return this.inputPorts[e]},NodeModel.prototype.getInputPorts=function(){return this.inputPorts},NodeModel.prototype.removeInputPortWithName=function(e){if(this.inputPorts.hasOwnProperty(e)){var t=this.inputPorts[e];delete this.inputPorts[e],this.emit("inputPortRemoved",t)}},NodeModel.prototype.updateInputPortTypes=function(e){var t=!1;for(var n in e)this.inputPorts[n]!==void 0&&(this.inputPorts[n].type=e[n].type,t=!0);t&&this.emit("inputPortTypesUpdated")},NodeModel.prototype.addOutputPort=function(e){this.outputPorts[e.name]=e,this.emit("outputPortAdded",e)},NodeModel.prototype.getOutputPort=function(e){return this.outputPorts[e]},NodeModel.prototype.getOutputPorts=function(){return this.outputPorts},NodeModel.prototype.removeOutputPortWithName=function(e){if(this.outputPorts.hasOwnProperty(e)){var t=this.outputPorts[e];delete this.outputPorts[e],this.emit("outputPortRemoved",t)}},NodeModel.prototype.updateOutputPortTypes=function(e){var t=!1;for(var n in e)this.outputPorts[n]!==void 0&&(this.outputPorts[n].type=e[n].type,t=!0);t&&this.emit("outputPortTypesUpdated")},NodeModel.prototype.addChild=function(e,t){e.parent=this,t===void 0?this.children.push(e):this.children.splice(t,0,e),this.emit("childAdded",e)},NodeModel.prototype.removeChild=function(e){e.parent=void 0;var t=this.children.indexOf(e);this.children.splice(t,1),this.emit("childRemoved",e)},NodeModel.prototype.reset=function(){this.removeAllListeners()},NodeModel.prototype.setVariant=function(e){this.variant=e,this.emit("variantUpdated",e)},NodeModel.createFromExportData=function(e){var t=new NodeModel(e.id,e.type);if(e.parameters&&t.setParameters(e.parameters),e.stateParameters&&t.setStateParameters(e.stateParameters),e.stateTransitions&&t.setStateTransitions(e.stateTransitions),e.defaultStateTransitions)for(const n in e.defaultStateTransitions)t.setDefaultStateTransition(e.defaultStateTransitions[n],n);return e.ports&&e.ports.forEach(function(n){n.plug==="outputs"&&(n.plug="output"),(n.plug==="input"||n.plug==="input/output")&&t.addInputPort(n),(n.plug==="output"||n.plug==="input/output")&&t.addOutputPort(n)}),e.variant&&t.setVariant(e.variant),t};function ComponentModel(e){EventSender.call(this),this.name=e,this.nodes=[],this.connections=[],this.roots=[],this.inputPorts={},this.outputPorts={},this.metadata={}}ComponentModel.prototype=Object.create(EventSender.prototype),ComponentModel.prototype.addNode=async function(e){e.component=this,this.nodes[e.id]=e,await this.emit("nodeAdded",e)},ComponentModel.prototype.hasNodeWithId=function(e){return this.getNodeWithId(e)!==void 0},ComponentModel.prototype.getNodeWithId=function(e){return this.nodes[e]},ComponentModel.prototype.getAllNodes=function(){return Object.values(this.nodes)},ComponentModel.prototype.getNodesWithType=function(e){var t=[],n=this;return Object.keys(this.nodes).forEach(function(o){var r=n.nodes[o];r.type===e&&t.push(r)}),t},ComponentModel.prototype.addConnection=function(e){if(this.connections.push(e),this.emit("connectionAdded",e),e.targetId){const t=this.getNodeWithId(e.targetId);t&&t.emit("inputConnectionAdded",e)}},ComponentModel.prototype.removeConnection=function(e){const t=this.connections.findIndex(n=>n.sourceId===e.sourceId&&n.sourcePort===e.sourcePort&&n.targetId===e.targetId&&n.targetPort===e.targetPort);if(t===-1){console.log("Connection doesn't exist",e);return}if(this.connections.splice(t,1),this.emit("connectionRemoved",e),e.targetId){const n=this.getNodeWithId(e.targetId);n&&n.emit("inputConnectionRemoved",e)}},ComponentModel.prototype.getConnectionsFromPort=function(e,t){return this.connections.filter(function(n){return n.sourceId===e&&n.sourcePort===t})},ComponentModel.prototype.getConnectionsToPort=function(e,t){return this.connections.filter(function(n){return n.targetId===e&&n.targetPort===t})},ComponentModel.prototype.getConnectionsFrom=function(e){return this.connections.filter(function(t){return t.sourceId===e})},ComponentModel.prototype.getConnectionsTo=function(e){return this.connections.filter(function(t){return t.targetId===e})},ComponentModel.prototype.addRootId=function(e){this.roots.indexOf(e)===-1&&(this.roots.push(e),this.emit("rootAdded",e))},ComponentModel.prototype.removeRootId=function(e){const t=this.roots.indexOf(e);t!==-1&&(this.roots.splice(t,1),this.emit("rootRemoved",e))},ComponentModel.prototype.getRoots=function(){return this.roots},ComponentModel.prototype.removeNodeWithId=async function(e){const t=this.getNodeWithId(e);if(!t)return console.warn("ERROR: Attempted to remove non-existing node with ID:",e),!1;for(;t.children.length>0;){const o=t.children[0];await this.removeNodeWithId(o.id)||t.children.shift()}const n=this.getConnectionsTo(e).concat(this.getConnectionsFrom(e));for(let o=0;o<n.length;o++)this.removeConnection(n[o]);return this.setNodeParent(t,null),this.roots.indexOf(t.id)!==-1&&this.removeRootId(t.id),await this.emit("nodeRemoved",t),t.removeAllListeners(),delete this.nodes[e],await this.emit("nodeWasRemoved",t),!0},ComponentModel.prototype.getAllConnections=function(){return this.connections},ComponentModel.prototype.getInputPorts=function(){return this.inputPorts},ComponentModel.prototype.getOutputPorts=function(){return this.outputPorts},ComponentModel.prototype.addInputPort=function(e){this.inputPorts[e.name]=e,this.emit("inputPortAdded",e)},ComponentModel.prototype.addOutputPort=function(e){this.outputPorts[e.name]=e,this.emit("outputPortAdded",e)},ComponentModel.prototype.removeOutputPortWithName=function(e){if(this.outputPorts.hasOwnProperty(e)){var t=this.outputPorts[e];delete this.outputPorts[e],this.emit("outputPortRemoved",t)}},ComponentModel.prototype.removeInputPortWithName=function(e){if(this.inputPorts.hasOwnProperty(e)){var t=this.inputPorts[e];delete this.inputPorts[e],this.emit("inputPortRemoved",t)}},ComponentModel.prototype.updateInputPortTypes=function(e){var t=!1;for(var n in e)this.inputPorts[n]!==void 0&&(this.inputPorts[n].type=e[n].type,t=!0);t&&this.emit("inputPortTypesUpdated")},ComponentModel.prototype.updateOutputPortTypes=function(e){var t=!1;for(var n in e)this.outputPorts[n]!==void 0&&(this.outputPorts[n].type=e[n].type,t=!0);t&&this.emit("outputPortTypesUpdated")},ComponentModel.prototype.renameInputPortOnNodeWithId=function(e,t,n){var o=this.getConnectionsToPort(e,t);o.forEach(this.removeConnection.bind(this));var r=this.getNodeWithId(e),s={...r.getInputPort(t)};s&&(r.removeInputPortWithName(t),s.name=n,r.addInputPort(s)),o.forEach(function(a){a.targetPort=n}),o.forEach(this.addConnection.bind(this))},ComponentModel.prototype.renameOutputPortOnNodeWithId=function(e,t,n){var o=this.getConnectionsFromPort(e,t);o.forEach(this.removeConnection.bind(this));var r=this.getNodeWithId(e),s={...r.getOutputPort(t)};r.removeOutputPortWithName(t),s.name=n,r.addOutputPort(s),o.forEach(function(a){a.sourcePort=n}),o.forEach(this.addConnection.bind(this))},ComponentModel.prototype.setNodeParent=function(e,t,n){this.roots.indexOf(e.id)!==-1&&this.removeRootId(e.id),e.parent&&(this.emit("nodeParentWillBeRemoved",e),e.parent.removeChild(e)),e.emit("parentUpdated",t),t&&(t.addChild(e,n),this.emit("nodeParentUpdated",e))},ComponentModel.prototype.importEditorNodeData=async function(e,t,n){var o=NodeModel.createFromExportData(e);if(await this.addNode(o),t&&this.setNodeParent(o,this.getNodeWithId(t),n),e.children)for(let r=0;r<e.children.length;r++){const s=e.children[r];await this.importEditorNodeData(s,o.id,r)}},ComponentModel.prototype.reset=async function(){for(;this.roots.length;)await this.removeNodeWithId(this.roots[0]);for(const e of this.nodes)this.hasNodeWithId(e)&&await this.removeNodeWithId(e);if(this.nodes.length>0)throw new Error("Not all nodes were removed during a reset");if(this.connections.length>0)throw new Error("Not all connections were removed during a reset")},ComponentModel.prototype.rename=function(e){var t=this.name;this.name=e,this.emit("renamed",{oldName:t,newName:e})},ComponentModel.prototype.setMetadata=function(e,t){this.metadata[e]=t},ComponentModel.prototype.getMetadata=function(e){return e?this.metadata[e]:this.metadata},ComponentModel.createFromExportData=async function(e){var t=new ComponentModel(e.name);if(e.metadata)for(const n in e.metadata)t.setMetadata(n,e.metadata[n]);if(e.ports&&e.ports.forEach(function(n){(n.plug==="input"||n.plug==="input/output")&&t.addInputPort(n),(n.plug==="output"||n.plug==="input/output")&&t.addOutputPort(n)}),e.nodes)for(const n of e.nodes)await t.importEditorNodeData(n);return e.connections&&e.connections.forEach(n=>t.addConnection(n)),e.roots&&e.roots.forEach(n=>t.addRootId(n)),t};function GraphModel(){EventSender.call(this),this.components={},this.settings={},this.metadata={}}GraphModel.prototype=Object.create(EventSender.prototype),GraphModel.prototype.importComponentFromEditorData=async function(e){var t=await ComponentModel.createFromExportData(e);this.addComponent(t)},GraphModel.prototype.getBundleContainingComponent=function(e){return this.componentToBundleMap.get(e)},GraphModel.prototype.getBundlesContainingSheet=function(e){const t=new Set;for(const n of this.componentToBundleMap.keys()){const o=n.indexOf("/#")!==0;(o&&e==="Default"||!o&&n.indexOf("/#"+e)===0)&&t.add(this.componentToBundleMap.get(n))}return Array.from(t)},GraphModel.prototype.getBundleDependencies=function(e){const t=new Set,n=o=>{const r=this.componentIndex[o];for(const s of r.dependencies)t.has(s)||(t.add(s),n(s))};return n(e),Array.from(t)},GraphModel.prototype.importEditorData=async function(e){this.componentIndex=e.componentIndex,this.routerIndex=e.routerIndex,this.componentToBundleMap=new Map;for(const t in e.componentIndex){const n=e.componentIndex[t];for(const o of n.components)this.componentToBundleMap.set(o,t)}this.variants=e.variants||[],e.settings&&this.setSettings(e.settings),e.metadata&&this.setAllMetaData(e.metadata);for(const t of e.components)await this.importComponentFromEditorData(t);this.setRootComponentName(e.rootComponent)},GraphModel.prototype.setRootComponentName=function(e){this.rootComponent=e,this.emit("rootComponentNameUpdated",e)},GraphModel.prototype.getNodesWithType=function(e){for(var t=[],n=Object.keys(this.components),o=0;o<n.length;o++){var r=this.components[n[o]];t=t.concat(r.getNodesWithType(e))}return t},GraphModel.prototype.getComponentWithName=function(e){return this.components[e]},GraphModel.prototype.hasComponentWithName=function(e){return!!this.components[e]},GraphModel.prototype.getAllComponents=function(){return Object.keys(this.components).map(e=>this.components[e])},GraphModel.prototype.getAllNodes=function(){for(var e=[],t=Object.keys(this.components),n=0;n<t.length;n++){var o=this.components[t[n]];e=e.concat(o.getAllNodes())}return e},GraphModel.prototype.addComponent=function(e){this.components[e.name]=e,this.getNodesWithType(e.name).forEach(this._addComponentPorts.bind(this)),e.getAllNodes().forEach(this._onNodeAdded.bind(this)),e.on("nodeAdded",this._onNodeAdded.bind(this),this),e.on("nodeRemoved",this._onNodeRemoved.bind(this),this),e.on("nodeWasRemoved",this._onNodeWasRemoved.bind(this),this),this.emit("componentAdded",e)},GraphModel.prototype.removeComponentWithName=async function(e){if(this.components.hasOwnProperty(e)===!1){console.error("GraphModel: Component with name "+e+" not in graph");return}var t=this.components[e];await t.reset(),t.removeAllListeners(),delete this.components[t.name],this.emit("componentRemoved",t)},GraphModel.prototype.renameComponent=function(e,t){if(this.components.hasOwnProperty(e)===!1){console.error("GraphModel: Component with name "+e+" not in graph");return}this.getNodesWithType(e).forEach(function(o){o.type=t});var n=this.components[e];n.rename(t),delete this.components[e],this.components[t]=n,this.emit("componentRenamed",n)},GraphModel.prototype._addComponentPorts=function(e){if(this.components.hasOwnProperty(e.type)){var t=this.components[e.type];const n=t.getInputPorts(),o=t.getOutputPorts();Object.keys(n).forEach(r=>{e.addInputPort(n[r])}),Object.keys(o).forEach(r=>{e.addOutputPort(o[r])})}},GraphModel.prototype._onNodeAdded=function(e){this._addComponentPorts(e),this.emit("nodeAdded",e),this.emit("nodeAdded."+e.type,e)},GraphModel.prototype._onNodeRemoved=function(e){this.emit("nodeRemoved",e),this.emit("nodeRemoved."+e.type,e)},GraphModel.prototype._onNodeWasRemoved=function(e){this.emit("nodeWasRemoved",e),this.emit("nodeWasRemoved."+e.type,e)},GraphModel.prototype.reset=async function(){for(const e of Object.keys(this.components))await this.removeComponentWithName(e);this.setSettings({})},GraphModel.prototype.isEmpty=function(){return Object.keys(this.components).length===0},GraphModel.prototype.setSettings=function(e){this.settings=e,this.emit("projectSettingsChanged",e)},GraphModel.prototype.getSettings=function(){return this.settings},GraphModel.prototype.setAllMetaData=function(e){for(const t in e)this.setMetaData(t,e[t])},GraphModel.prototype.setMetaData=function(e,t){this.metadata[e]&&JSON.stringify(this.metadata[e])===JSON.stringify(t)||(this.metadata[e]=t,this.emit("metadataChanged",{key:e,data:t}),this.emit("metadataChanged."+e,t))},GraphModel.prototype.getMetaData=function(e){return e?this.metadata[e]:this.metadata},GraphModel.prototype.getVariants=function(){return this.variants||[]},GraphModel.prototype.getVariant=function(e,t){return this.variants.find(n=>n.name===t&&n.typename===e)},GraphModel.prototype.updateVariant=function(e){const t=this.variants.findIndex(n=>n.name===e.name&&n.typename===e.typename);t!==-1&&this.variants.splice(t,1),this.variants.push(e),this.emit("variantUpdated",e)},GraphModel.prototype.updateVariantParameter=function(e,t,n,o,r){const s=this.getVariant(t,e);if(!s){console.log("updateVariantParameter: can't find variant",e,t);return}r?(s.stateParameters.hasOwnProperty(r)||(s.stateParameters[r]={}),o===void 0?delete s.stateParameters[r][n]:s.stateParameters[r][n]=o):o===void 0?delete s.parameters[n]:s.parameters[n]=o,this.emit("variantUpdated",s)},GraphModel.prototype.updateVariantDefaultStateTransition=function(e,t,n,o){const r=this.getVariant(t,e);r&&(r.defaultStateTransitions[o]=n,this.emit("variantUpdated",r))},GraphModel.prototype.updateVariantStateTransition=function(e){const{variantTypeName:t,variantName:n,state:o,parameterName:r,curve:s}=e,a=this.getVariant(t,n);a&&(a.stateTransitions[o]||(a.stateTransitions[o]={}),a.stateTransitions[o][r]=s)},GraphModel.prototype.deleteVariant=function(e,t){const n=this.variants.findIndex(o=>o.name===t&&o.typename===e);n!==-1&&this.variants.splice(n,1)};function createSetter(e){var t=!1;return function(n){n=!!n,n&&t===!1&&e.valueChangedToTrue.call(this),t=n}}const EdgeTriggeredInput=Object.freeze(Object.defineProperty({__proto__:null,createSetter},Symbol.toStringTag,{value:"Module"}));function createNodeConstructor(e){const t=class extends Node{constructor(n,o){super(n,o)}getInspectInfo(){return e.getInspectInfo?.()??void 0}nodeScopeDidInitialize(){return e.nodeScopeDidInitialize?.()??void 0}};return e.prototypeExtensions&&Object.defineProperties(t.prototype,e.prototypeExtensions),Object.defineProperty(t.prototype,"name",{value:e.name}),t}function registerInput(e,t,n,o){if(e.hasOwnProperty(n))throw new Error("Input property "+n+" already registered");!o.set&&!o.valueChangedToTrue&&(o.set=()=>{}),o.set&&(e[n]={set:o.set},["color","textStyle","array"].forEach(s=>{o.type&&(o.type===s||o.type.name===s)&&(e[n].type=s)})),o.setUnitType&&(e[n].setUnitType=o.setUnitType),t.inputs[n]={displayName:o.displayName,editorName:o.editorName,group:o.group,type:o.type,default:o.default,index:o.index,exportToEditor:o.hasOwnProperty("exportToEditor")?o.exportToEditor:!0,inputPriority:o.inputPriority||0,tooltip:o.tooltip,tab:o.tab,popout:o.popout,allowVisualStates:o.allowVisualStates,nodeDoubleClickAction:o.nodeDoubleClickAction},o.valueChangedToTrue&&(t.inputs[n].type={name:"signal",allowConnectionsOnly:!0})}function registerInputs(e,t,n){Object.keys(n).forEach(function(o){registerInput(e,t,o,n[o])})}function registerNumberedInputs(e,t){for(const n of Object.keys(t))registerNumberedInput(e,n,t[n])}function registerNumberedInput(e,t,n){const o=e.registerInputIfNeeded;e.registerInputIfNeeded=function(r){if(o&&o.call(e,r),e.hasInput(r)||!r.startsWith(t))return;const s=Number(r.slice(t.length+1));e.registerInput(r,{type:n.type,set:n.createSetter.call(e,s)})}}function registerOutputsMetadata(e,t){Object.keys(t).forEach(function(n){var o=t[n];e.outputs[n]={displayName:o.displayName,editorName:o.editorName,group:o.group,type:o.type,index:o.index,exportToEditor:o.hasOwnProperty("exportToEditor")?o.exportToEditor:!0}})}function initializeDefaultValues(e,t){Object.keys(t).forEach(n=>{const o=t[n].default;o!==void 0&&(t[n].type.defaultUnit?e[n]={unit:t[n].type.defaultUnit,value:o}:e[n]=o)})}function defineNode(e){if(!e.category)throw new Error("Node must have a category");if(!e.name)throw new Error("Node must have a name");const t={inputs:{},outputs:{},category:e.category,dynamicports:e.dynamicports,exportDynamicPorts:e.exportDynamicPorts,useVariants:e.useVariants,allowChildren:e.allowChildren,allowChildrenWithCategory:e.allowChildrenWithCategory,singleton:e.singleton,connectionPanel:e.connectionPanel,allowAsChild:e.allowAsChild,visualStates:e.visualStates,panels:e.panels,color:e.color,usePortAsLabel:e.usePortAsLabel,portLabelTruncationMode:e.portLabelTruncationMode,name:e.name,displayNodeName:e.displayNodeName||e.displayName,deprecated:e.deprecated,haveComponentPorts:e.haveComponentPorts,version:e.version,module:e.module,docs:e.docs,allowAsExportRoot:e.allowAsExportRoot,nodeDoubleClickAction:e.nodeDoubleClickAction,searchTags:e.searchTags};e._internal=e._internal||{},e.prototypeExtensions=e.methods||e.prototypeExtensions||{},e.inputs=e.inputs||{},e.outputs=e.outputs||{},e.initialize=e.initialize||function(){};let n={};registerInputs(n,t,e.inputs),registerOutputsMetadata(t,e.outputs),Object.keys(e.prototypeExtensions).forEach(function(s){e.prototypeExtensions[s].value||(e.prototypeExtensions[s]={value:e.prototypeExtensions[s]})});const o=createNodeConstructor({name:e.name,getInspectInfo:e.getInspectInfo,nodeScopeDidInitialize:e.nodeScopeDidInitialize,prototypeExtensions:e.prototypeExtensions}),r=function(s,a,u){const l=new o(s,a);return l._inputs=Object.create(n),Object.keys(e.inputs).forEach(function(d){var p=e.inputs[d];p.valueChangedToTrue&&(l._inputs[d]={set:createSetter({valueChangedToTrue:p.valueChangedToTrue})})}),Object.keys(e.outputs).forEach(function(d){var p=e.outputs[d];p.type==="signal"?l.registerOutput(d,{getter(){}}):l.registerOutput(d,p)}),e.numberedInputs&®isterNumberedInputs(l,e.numberedInputs),l.nodeScope=u,initializeDefaultValues(l._inputValues,t.inputs),e.initialize.call(l),l};return r.metadata=t,e.numberedInputs&®isterSetupFunctionForNumberedInputs(r,e.name,e.numberedInputs),r}function registerSetupFunctionForNumberedInputs(e,t,n){const o=Object.keys(n);o.length&&(e.setupNumberedInputDynamicPorts=function(r,s){const a=r.editorConnection;if(!a||!a.isRunningLocally())return;function u(d,p,f){const m=d.component.getConnectionsTo(d.id).map(N=>N.targetPort),v=Object.keys(d.parameters).concat(m).filter(N=>N.startsWith(p+" ")),S=(v.length?1+Math.max(...v.map(N=>Number(N.slice(p.length+1)))):0)+1,C=[];for(let N=0;N<S;N++){const T={name:p+" "+N,displayName:(f.displayPrefix||p)+" "+N,type:f.type,plug:"input",group:f.group};f.hasOwnProperty("index")&&(T.index=f.index+N),C.push(T)}return C}function l(d){const p=o.map(f=>u(d,f,n[f])).flat();a.sendDynamicPorts(d.id,p)}s.on("nodeAdded."+t,d=>{l(d),d.on("parameterUpdated",()=>{l(d)}),d.on("inputConnectionAdded",()=>{l(d)}),d.on("inputConnectionRemoved",()=>{l(d)})})})}function extend(e,t){for(var n in t)if(n==="initialize"&&e.initialize){var o=e.initialize;e.initialize=function(){o.call(this),t.initialize.call(this)}}else t[n]&&t[n].constructor===Object?e[n]=extend(e[n]||{},t[n]):t[n]&&t[n].constructor===Array&&e[n]&&e[n].constructor==Array?e[n]=e[n].concat(t[n]):e[n]=t[n];return e}function difference$1(e,t){const n=new Set(t);return e.filter(o=>!n.has(o))}async function handleEvent(e,t,n){function o(u,l){var d={},p={};l.forEach(function(C){C&&C.plug==="outputs"&&(C.plug="output"),(C.plug==="input"||C.plug==="input/output")&&(d[C.name]=C),(C.plug==="output"||C.plug==="input/output")&&(p[C.name]=C)});var f=Object.keys(u.getInputPorts()),m=difference$1(f,Object.keys(d)),y=difference$1(Object.keys(d),f);u.updateInputPortTypes(d),m.forEach(u.removeInputPortWithName.bind(u)),y.forEach(function(C){u.addInputPort(d[C]),u.parameters&&u.parameters.hasOwnProperty(C)&&r(e.rootComponent.nodeScope,u,C,u.parameters[C])}),u.updateOutputPortTypes(p);var v=Object.keys(u.getOutputPorts()),P=difference$1(v,Object.keys(p)),S=difference$1(Object.keys(p),v);P.forEach(u.removeOutputPortWithName.bind(u)),S.forEach(function(C){u.addOutputPort(p[C])})}function r(u,l,d,p){var f=u.getNodesWithIdRecursive(l.id);f.forEach(function(m){m.queueInput(d,p)})}var s;if(!(n.componentName&&(s=t.getComponentWithName(n.componentName),!s))){n.port&&n.port.plug==="outputs"&&(n.port.plug="output");var a={nodeAdded(u){s.importEditorNodeData(u.model,u.parentId,u.childIndex)},nodeRemoved:async function(u){s.hasNodeWithId(u.model.id)&&await s.removeNodeWithId(u.model.id)},connectionAdded(u){s.addConnection(u.model)},connectionRemoved(u){s.removeConnection(u.model);var l=s.getNodeWithId(u.model.targetId);if(s.getConnectionsToPort(l.id,u.model.targetId).length===0){var d=l.parameters[u.model.targetPort];d===void 0&&(d=e.getDefaultValueForInput(l.type,u.model.targetPort)),r(e.rootComponent.nodeScope,l,u.model.targetPort,d)}},parameterChanged(u){const l=s.getNodeWithId(u.nodeId);if(l===void 0){console.log("parameterChanged: Unknown node id",u);return}if(u.parameters){const d=new Set(Object.keys(u.parameters).concat(Object.keys(u.oldParameters)));for(const p of d)l.setParameter(p,u.parameters[p])}u.parameterName&&l.setParameter(u.parameterName,u.parameterValue,u.state)},nodeAttached(u){s.setNodeParent(s.getNodeWithId(u.nodeId),s.getNodeWithId(u.parentId),u.childIndex)},nodeDetached(u){s.setNodeParent(s.getNodeWithId(u.nodeId),null),s.addRootId(u.nodeId)},componentAdded(u){t.importComponentFromEditorData(u.model)},componentRemoved:async function(u){await t.removeComponentWithName(u.componentName)},rootAdded(u){s.addRootId(u.nodeId)},portAdded(u){var l=s.getNodeWithId(u.nodeId);(u.port.plug==="input"||u.port.plug==="input/output")&&(l.addInputPort(u.port),l.parameters.hasOwnProperty(u.port)&&r(e.rootComponent.nodeScope,l,u.port,l.parameters[u.port])),(u.port.plug==="output"||u.port.plug==="input/output")&&l.addOutputPort(u.port)},portRemoved(u){var l=s.getNodeWithId(u.nodeId);(u.port.plug==="input"||u.port.plug==="input/output")&&l.removeInputPortWithName(u.port.name),(u.port.plug==="output"||u.port.plug==="input/output")&&l.removeOutputPortWithName(u.port.name)},nodePortRenamed(u){(u.port.plug==="input"||u.port.plug==="input/output")&&s.renameInputPortOnNodeWithId(u.nodeId,u.oldName,u.port.name),(u.port.plug==="output"||u.port.plug==="input/output")&&s.renameOutputPortOnNodeWithId(u.nodeId,u.oldName,u.port.name);var l=s.getNodeWithId(u.nodeId);l.type==="Component Inputs"?(s.addInputPort(u.port),t.getNodesWithType(s.name).forEach(function(d){d.component.renameInputPortOnNodeWithId(d.id,u.oldName,u.port.name)}),s.removeInputPortWithName(u.oldName)):l.type==="Component Outputs"&&(s.addOutputPort(u.port),t.getNodesWithType(s.name).forEach(function(d){d.component.renameOutputPortOnNodeWithId(d.id,u.oldName,u.port.name)}),s.removeOutputPortWithName(u.oldName))},componentPortsUpdated(u){o(s,u.ports)},instancePortsChanged(u){if(s.hasNodeWithId(u.nodeId)){var l=s.getNodeWithId(u.nodeId);o(l,u.ports)}},componentRenamed(u){t.renameComponent(u.oldName,u.newName)},settingsChanged(u){t.setSettings(u.settings)},metadataChanged(u){t.setMetaData(u.key,u.data)},componentMetadataChanged(u){const l=t.getComponentWithName(u.componentName);l&&l.setMetadata(u.key,u.data)},variantParametersChanged(u){if(u.variant)t.updateVariant(u.variant);else if(t.updateVariantParameter(u.variantName,u.variantTypeName,u.parameterName,u.parameterValue,u.state),u.parameterValue===void 0){const l=t.getVariant(u.variantTypeName,u.variantName);e.rootComponent.nodeScope.getAllNodesWithVariantRecursive(l).forEach(p=>{p.queueInput(u.parameterName,p.getParameter(u.parameterName))})}},variantDeleted(u){t.deleteVariant(u.variantTypeName,u.variantName)},variantChanged(u){const l=s.getNodeWithId(u.nodeId),d=t.getVariant(l.type,u.variantName);l.setVariant(d)},variantRenamed(u){const l=t.getVariant(u.variantTypeName,u.oldVariantName);l&&(l.name=l.variantName)},defaultStateTransitionChanged(u){s.getNodeWithId(u.nodeId).setDefaultStateTransition(u.curve,u.state)},stateTransitionsChanged(u){const l=s.getNodeWithId(u.nodeId);u.parameterName&&l.setStateTransitionParamter(u.parameterName,u.curve,u.state)},variantDefaultStateTransitionChanged(u){t.updateVariantDefaultStateTransition(u.variantName,u.variantTypeName,u.curve,u.state)},variantStateTransitionsChanged(u){t.updateVariantStateTransition(u)},routerIndexChanged(u){t.routerIndex=u.data}};a.hasOwnProperty(n.type)?(await a[n.type](n),e.scheduleUpdate()):console.log("Unknown event",n)}}async function asyncPool(e,t,n){const o=[],r=[];for(const s of t){const a=Promise.resolve().then(()=>n(s,t));if(o.push(a),e<=t.length){const u=a.then(()=>r.splice(r.indexOf(u),1));r.push(u),r.length>=e&&await Promise.race(r)}}return Promise.all(o)}const ComponentInputs={node:{name:"Component Inputs",shortDesc:"This node is used to define the inputs of a component.",docs:"https://docs.noodl.net/nodes/component-utilities/component-inputs",panels:[{name:"PortEditor",context:["select","connectFrom"],title:"Inputs",plug:"output",type:{name:"*"},canArrangeInGroups:!0},{name:"PropertyEditor",hidden:!0}],getInspectInfo(){return{type:"value",value:this.nodeScope.componentOwner._internal.inputValues}},color:"component",haveComponentPorts:!0,category:"Component Utilities",methods:{registerOutputIfNeeded(e){this.hasOutput(e)||this.registerOutput(e,{getter(){return this.nodeScope.componentOwner._internal.inputValues[e]}})},_updateDependencies(){this.nodeScope.componentOwner.update()}}}},ComponentOutputs={node:{category:"Component Utilities",name:"Component Outputs",shortDesc:"This node is used to define the outputs of a component.",docs:"https://docs.noodl.net/nodes/component-utilities/component-outputs",panels:[{name:"PortEditor",context:["select","connectTo"],title:"Outputs",plug:"input",type:{name:"*"},canArrangeInGroups:!0},{name:"PropertyEditor",hidden:!0}],color:"component",haveComponentPorts:!0,prototypeExtensions:{registerInputIfNeeded(e){this.hasInput(e)||this.registerInput(e,{set(t){this.nodeScope.componentOwner.setOutputFromComponentOutput(e,t)}})}}}};function Model(e,t){this.id=e,this.data=t}const models=Model._models={},proxies={},_modelProxyHandler={get(e,t,n){return typeof e[t]=="function"?e[t].bind(e):t in e?Reflect.get(e,t,n):e.get(t)},set(e,t,n){if(t==="_class")e._class=n;else{if(t==="id")return console.log(`Noodl.Object warning: id is readonly (Id is ${e.id}, trying to set to ${n})`),!0;e.set(t,n)}return!0},ownKeys(e){return Reflect.ownKeys(e.data)},getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e.data,t)}};Model.get=function(e){return e===void 0&&(e=Model.guid()),models[e]||(models[e]=new Model(e,{}),proxies[e]=new Proxy(models[e],_modelProxyHandler)),proxies[e]},Model.create=function(e){var t=e||{},n=Model.get(t.id);for(var o in t)o!=="id"&&n.set(o,t[o]);return n},Model.exists=function(e){return models[e]!==void 0},Model.instanceOf=function(e){return e instanceof Model||e.target instanceof Model};function _randomString(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";for(let o=0;o<e;++o)n+=t[Math.floor((1+Math.random())*65536)%t.length];return n}Model.guid=function e(){return _randomString(10)},Model.prototype.on=function(e,t){this.listeners||(this.listeners={}),this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},Model.prototype.off=function(e,t){if(this.listeners&&this.listeners[e]){var n=this.listeners[e].indexOf(t);n!==-1&&this.listeners[e].splice(n,1)}},Model.prototype.notify=function(e,t){if(this.listeners&&this.listeners[e])for(var n=this.listeners[e].slice(),o=0;o<n.length;o++)n[o](t)},Model.prototype.setAll=function(e){for(var t in e)if(t!=="id"&&this.data[t]!==e[t]){var n=this.data[t];this.data[t]=e[t],this.notify("change",{name:t,value:e[t],old:n})}},Model.prototype.fill=function(e=null){for(const t in this.data){if(t==="id")continue;const n=this.data[t];this.data[t]=e,this.notify("change",{name:t,value:this.data[t],old:n})}},Model.prototype.set=function(e,t,n){if(n&&n.resolve&&e.indexOf(".")!==-1){const s=e.split(".");let a=this;for(let u=0;u<s.length-1;u++){const l=a.get(s[u]);if(Model.instanceOf(l))a=l;else return}a.set(s[s.length-1],t);return}const o=n&&n.forceChange,r=this.data[e];this.data[e]=t,(o||r!==t)&&(!n||!n.silent)&&this.notify("change",{name:e,value:t,old:r})},Model.prototype.getId=function(){return this.id},Model.prototype.get=function(e,t){if(t&&t.resolve&&e.indexOf(".")!==-1){const n=e.split(".");let o=this;for(let r=0;r<n.length-1;r++){const s=o.get(n[r]);if(Model.instanceOf(s))o=s;else return}return o.get(n[n.length-1])}return this.data[e]},Model.prototype.toJSON=function(){return Object.assign({},this.data,{id:this.id})},Model.Scope=function(){this.models={},this.proxies={}},Model.Scope.prototype.get=function(e){return e===void 0&&(e=Model.guid()),this.models[e]||(this.models[e]=new Model(e,{}),this.proxies[e]=new Proxy(this.models[e],_modelProxyHandler)),this.proxies[e]},Model.Scope.prototype.create=function(e){var t=e||{},n=this.get(t.id);for(var o in t)o!=="id"&&n.set(o,t[o]);return n},Model.Scope.prototype.exists=function(e){return this.models[e]!==void 0},Model.Scope.prototype.instanceOf=function(e){return e instanceof Model||e.target instanceof Model},Model.Scope.prototype.guid=function e(){return _randomString(10)},Model.Scope.prototype.reset=function(){this.models={},this.proxies={},delete this._cloudStore};function sendSignalOnInput(e,t){e.queueInput(t,!0),e.queueInput(t,!1)}const RunTasksDefinition={name:"RunTasks",displayNodeName:"Run Tasks",docs:"https://docs.noodl.net/nodes/data/run-tasks",color:"data",category:"Data",initialize(){this._internal.queuedOperations=[],this._internal.state="idle",this._internal.maxRunningTasks=10,this._internal.activeTasks=new Map},inputs:{items:{group:"Data",displayName:"Items",type:"array",set(e){e&&e!==this._internal.items&&(this._internal.items=e)}},stopOnFailure:{group:"General",displayName:"Stop On Failure",type:"boolean",default:!1,set(e){this._internal.stopOnFailure=e}},maxRunningTasks:{group:"General",displayName:"Max Running Tasks",type:"number",default:10,set(e){this._internal.maxRunningTasks=e}},taskTemplate:{type:"component",displayName:"Template",group:"General",set(e){this._internal.template=e}},run:{group:"General",displayName:"Do",type:"signal",valueChangedToTrue(){this.scheduleRun()}},abort:{group:"General",displayName:"Abort",type:"signal",valueChangedToTrue(){this.scheduleAbort()}}},outputs:{success:{type:"signal",group:"Events",displayName:"Success"},failure:{type:"signal",group:"Events",displayName:"Failure"},done:{type:"signal",group:"Events",displayName:"Done"},aborted:{type:"signal",group:"Events",displayName:"Aborted"}},methods:{scheduleRun(){var e=this._internal;e.hasScheduledRun||(e.hasScheduledRun=!0,this.scheduleAfterInputsHaveUpdated(()=>{this._queueOperation(()=>{e.hasScheduledRun=!1,this.run()})}))},scheduleAbort(){var e=this._internal;e.hasScheduledAbort||(e.hasScheduledAbort=!0,this.scheduleAfterInputsHaveUpdated(()=>{this._queueOperation(()=>{e.hasScheduledAbort=!1,this.abort()})}))},async createTaskComponent(e){const t=this._internal,o=(this.nodeScope.modelScope||Model).create(e);var r=await this.nodeScope.createNode(t.template,guid(),{_forEachModel:o,_forEachNode:this});const s=r.isInputConnected.bind(r);r.isInputConnected=u=>u==="Do"?!0:s(u),r.hasInput("Id")&&r.setInputValue("Id",o.getId()),r.hasInput("id")&&r.setInputValue("id",o.getId());for(var a in r._inputs)o.data[a]!==void 0&&r.setInputValue(a,o.data[a]);return r._internal.creatorCallbacks={onOutputChanged:(u,l,d)=>{(d===!1||d===void 0)&&l===!0&&this.itemOutputSignalTriggered(u,o,r)}},r},async startTask(e){const t=this._internal;try{const n=await this.createTaskComponent(e);t.runningTasks++,sendSignalOnInput(n,"Do"),t.activeTasks.set(n.id,n)}catch(n){console.log(n)}},async run(){const e=this._internal;if(this.context.editorConnection&&(e.state!=="idle"?this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"Cannot start when not in idle mode"}):e.template?e.items?this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks"):this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"No items array provided."}):this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"No task template specified."})),e.state==="idle"&&e.template&&e.items){e.state="running",e.numTasks=e.items.length,e.failedTasks=0,e.completedTasks=0,e.queuedTasks=[].concat(e.items),e.runningTasks=0,e.items.length===0&&(this.sendSignalOnOutput("success"),e.state="idle");for(let t=0;t<Math.min(e.maxRunningTasks,e.queuedTasks.length);t++){const n=e.queuedTasks.shift();if(!n)break;this.startTask(n)}}},abort(){const e=this._internal;e.state="aborted"},itemOutputSignalTriggered(e,t,n){const o=this._internal;if(o.state==="idle")return;const r=()=>{if(o.state==="aborted"){this.sendSignalOnOutput("aborted"),o.state="idle";return}if(o.completedTasks===o.numTasks)o.failedTasks===0?this.sendSignalOnOutput("success"):this.sendSignalOnOutput("failure"),this.sendSignalOnOutput("done"),o.state="idle";else if(o.stopOnFailure)if(o.failedTasks===0){o.runningTasks++;const s=o.queuedTasks.shift();s&&this.startTask(s)}else this.sendSignalOnOutput("failure"),this.sendSignalOnOutput("aborted");else{o.runningTasks++;const s=o.queuedTasks.shift();s&&this.startTask(s)}};e==="Success"?(o.completedTasks++,o.runningTasks--,r()):e==="Failure"&&(o.completedTasks++,o.failedTasks++,o.runningTasks--,r()),o.activeTasks.delete(n.id),this.nodeScope.deleteNode(n)},_queueOperation(e){this._internal.queuedOperations.push(e),this._runQueueOperations()},async _runQueueOperations(){if(!this.runningOperations){for(this.runningOperations=!0;this._internal.queuedOperations.length;)await this._internal.queuedOperations.shift()();this.runningOperations=!1}}},_deleteAllTasks(){for(const e of this._internal.activeTasks)this.nodeScope.deleteNode(e);this._internal.activeTasks.clear()},_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this._deleteAllTasks()}},RunTasks={node:RunTasksDefinition},defaultRequestScript=`//Add custom code to setup the request object before the request
|
|
1
|
+
var Runtime=function(exports){"use strict";class CloudFile{constructor({name:t,url:n}){this.name=t,this.url=n}getUrl(){return this.url}getName(){return this.name}toString(){return this.url}}var R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(t,n,o){return Function.prototype.apply.call(t,n,o)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t)};function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}var NumberIsNaN=Number.isNaN||function(t){return t!==t};function EventEmitter(){EventEmitter.init.call(this)}EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get(){return defaultMaxListeners},set(e){if(typeof e!="number"||e<0||NumberIsNaN(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");defaultMaxListeners=e}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||NumberIsNaN(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function _getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function(t){for(var n=[],o=1;o<arguments.length;o++)n.push(arguments[o]);var r=t==="error",s=this._events;if(s!==void 0)r=r&&s.error===void 0;else if(!r)return!1;if(r){var a;if(n.length>0&&(a=n[0]),a instanceof Error)throw a;var u=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw u.context=a,u}var l=s[t];if(l===void 0)return!1;if(typeof l=="function")ReflectApply(l,this,n);else for(var d=l.length,p=arrayClone(l,d),o=0;o<d;++o)ReflectApply(p[o],this,n);return!0};function _addListener(e,t,n,o){var r,s,a;if(checkListener(n),s=e._events,s===void 0?(s=e._events=Object.create(null),e._eventsCount=0):(s.newListener!==void 0&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),a=s[t]),a===void 0)a=s[t]=n,++e._eventsCount;else if(typeof a=="function"?a=s[t]=o?[n,a]:[a,n]:o?a.unshift(n):a.push(n),r=_getMaxListeners(e),r>0&&a.length>r&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,ProcessEmitWarning(u)}return e}EventEmitter.prototype.addListener=function(t,n){return _addListener(this,t,n,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function(t,n){return _addListener(this,t,n,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,n){var o={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=onceWrapper.bind(o);return r.listener=n,o.wrapFn=r,r}EventEmitter.prototype.once=function(t,n){return checkListener(n),this.on(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.prependOnceListener=function(t,n){return checkListener(n),this.prependListener(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.removeListener=function(t,n){var o,r,s,a,u;if(checkListener(n),r=this._events,r===void 0)return this;if(o=r[t],o===void 0)return this;if(o===n||o.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,o.listener||n));else if(typeof o!="function"){for(s=-1,a=o.length-1;a>=0;a--)if(o[a]===n||o[a].listener===n){u=o[a].listener,s=a;break}if(s<0)return this;s===0?o.shift():spliceOne(o,s),o.length===1&&(r[t]=o[0]),r.removeListener!==void 0&&this.emit("removeListener",t,u||n)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function(t){var n,o,r;if(o=this._events,o===void 0)return this;if(o.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):o[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete o[t]),this;if(arguments.length===0){var s=Object.keys(o),a;for(r=0;r<s.length;++r)a=s[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=o[t],typeof n=="function")this.removeListener(t,n);else if(n!==void 0)for(r=n.length-1;r>=0;r--)this.removeListener(t,n[r]);return this};function _listeners(e,t,n){var o=e._events;if(o===void 0)return[];var r=o[t];return r===void 0?[]:typeof r=="function"?n?[r.listener||r]:[r]:n?unwrapListeners(r):arrayClone(r,r.length)}EventEmitter.prototype.listeners=function(t){return _listeners(this,t,!0)},EventEmitter.prototype.rawListeners=function(t){return _listeners(this,t,!1)},EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}EventEmitter.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(e,t){for(var n=new Array(t),o=0;o<t;++o)n[o]=e[o];return n}function spliceOne(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function unwrapListeners(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function once(e,t){return new Promise(function(n,o){function r(a){e.removeListener(t,s),o(a)}function s(){typeof e.removeListener=="function"&&e.removeListener("error",r),n([].slice.call(arguments))}eventTargetAgnosticAddListener(e,t,s,{once:!0}),t!=="error"&&addErrorHandlerIfEventEmitter(e,r,{once:!0})})}function addErrorHandlerIfEventEmitter(e,t,n){typeof e.on=="function"&&eventTargetAgnosticAddListener(e,"error",t,n)}function eventTargetAgnosticAddListener(e,t,n,o){if(typeof e.on=="function")o.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener=="function")e.addEventListener(t,function r(s){o.once&&e.removeEventListener(t,r),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}function NodeRegister(e){this._constructors={},this.context=e}NodeRegister.prototype.register=function(e){var t=e.metadata.name;this._constructors[t]=e},NodeRegister.prototype.createNode=function(e,t,n){if(this._constructors.hasOwnProperty(e)===!1)throw new Error("Unknown node type with name "+e);return this._constructors[e](this.context,t,n)},NodeRegister.prototype.getNodeMetadata=function(e){if(this._constructors.hasOwnProperty(e)===!1)throw new Error("Unknown node type with name "+e);return this._constructors[e].metadata},NodeRegister.prototype.hasNode=function(e){return this._constructors.hasOwnProperty(e)},NodeRegister.prototype.getInputType=function(e,t){const n=this.getNodeMetadata(e);return n.inputs[t]&&n.inputs[t].type};function Timer(e,t){this.duration=t.duration||0,this._isRunning=!1,this._hasCalledOnStart=!1,this.scheduler=e,this.repeatCount=1,this.delay=0;for(var n in t)this[n]=t[n]}Timer.prototype.start=function(){return this._isRunning&&this.stop(),this.scheduler.scheduleTimer(this),this},Timer.prototype.stop=function(){this.scheduler.stopTimer(this),this._hasCalledOnStart=!1,this._isRunning=!1,this._wasStopped=!0},Timer.prototype.isRunning=function(){return this._isRunning},Timer.prototype.durationLeft=function(){return this._durationLeft};function TimerScheduler(e){this.requestFrame=e,this.runningTimers=[],this.newTimers=[]}TimerScheduler.prototype.createTimer=function(e){return new Timer(this,e)},TimerScheduler.prototype.scheduleTimer=function(e){this.newTimers.indexOf(e)===-1&&(e.repeatCount===0&&(e.repeatCount=1e5),this.newTimers.push(e),this.requestFrame())},TimerScheduler.prototype.stopTimer=function(e){var t;e._isRunning?(t=this.runningTimers.indexOf(e),t!==-1&&this.runningTimers.splice(t,1),e.onStop&&!e._wasStopped&&e.onStop()):(t=this.newTimers.indexOf(e),t!==-1&&this.newTimers.splice(t,1))},TimerScheduler.prototype.runTimers=function(e){var t=[],n=[],o=[],r,s=this.runningTimers.length,a;for(r=0;r<s;++r)o[r]=this.runningTimers[r];for(r=0;r<s;++r)if(a=o[r],a&&e>=a._start){a._hasCalledOnStart===!1&&a.onStart&&(a.onStart(),a._hasCalledOnStart=!0);var u;a.duration>0?u=(e-a._start)/(a.duration*a.repeatCount):u=1,a._durationLeft=a.duration*(1-u);var l=u*a.repeatCount-Math.floor(u*a.repeatCount);u>=1&&(l=1),a.onRunning&&a.onRunning(l),u<1&&a._isRunning?t.push(a):a._wasStopped||n.push(a)}else t.push(a);for(this.runningTimers=t,r=0;r<n.length;++r)n[r]._isRunning=!1,n[r]._hasCalledOnStart=!1,n[r].onFinish&&n[r].onFinish();if(this.newTimers.length>0){for(r=0;r<this.newTimers.length;++r)a=this.newTimers[r],a._start=e+a.delay,a._isRunning=!0,a._wasStopped=!1,this.runningTimers.push(a),a.delay===0&&(a.onStart&&(a.onStart(),a._hasCalledOnStart=!0),a.onRunning&&a.onRunning(0));this.newTimers.length=0}},TimerScheduler.prototype.hasPendingTimers=function(){return this.runningTimers.length>0||this.newTimers.length>0};class Variants{constructor({graphModel:t,getNodeScope:n}){this.getNodeScope=n,t&&(this.graphModel=t,t.on("variantUpdated",o=>this.onVariantUpdated(o)))}getVariant(t,n){if(this.graphModel)return this.graphModel.getVariant(t,n)}onVariantUpdated(t){const n=this.getNodeScope();if(!n)return;const r=n.getNodesWithTypeRecursive(t.typename).filter(s=>s.variant?s.variant.name===t.name:s.model&&s.model.variant===t.name);for(const s of r)s.setVariant(t)}}function OutputProperty(e){if(!e.owner)throw new Error("Owner must be set");this.getter=e.getter,this.connections=[],this.owner=e.owner,this.name=e.name,this.onFirstConnectionAdded=e.onFirstConnectionAdded,this.onLastConnectionRemoved=e.onLastConnectionRemoved,this._id=void 0}Object.defineProperties(OutputProperty.prototype,{value:{get(){return this.getter.call(this.owner)}},id:{get(){return this._id||(this._id=this.owner.id+this.name),this._id}},registerConnection:{value(e,t){this.connections.push({node:e,inputPortName:t}),this.connections.length===1&&this.onFirstConnectionAdded&&this.onFirstConnectionAdded.call(this.owner)}},deregisterConnection:{value(e,t){for(var n=0;n<this.connections.length;n++){var o=this.connections[n];if(o.node===e&&o.inputPortName===t){this.connections.splice(n,1);break}}this.connections.length===0&&this.onLastConnectionRemoved&&this.onLastConnectionRemoved.call(this.owner)}},flagDependeesDirty:{value(e){for(var t=0,n=this.connections.length;t<n;t++)this.connections[t].node.flagDirty()}},sendValue:{value(e){this._lastUpdateIteration!==this.owner._updatedAtIteration?(this._lastUpdateIteration=this.owner._updatedAtIteration,this.valuesSendThisIteration=0):this.valuesSendThisIteration++,this.valuesSendThisIteration>500&&(this.owner._cyclicLoop=!0);for(var t=0,n=this.connections.length;t<n;t++){var o=this.connections[t];o.node._setValueFromConnection(o.inputPortName,e)}}},hasConnections:{value(){return this.connections.length>0}}});function Node(e,t){this.id=t,this.context=e,this._dirty=!1,this._inputs={},this._inputValues={},this._outputs={},this._inputConnections={},this._outputList=[],this._isUpdating=!1,this._inputValuesQueue={},this._afterInputsHaveUpdatedCallbacks=[],this._internal={},this._signalsSentThisUpdate={},this._deleted=!1,this._deleteListeners=[],this._isFirstUpdate=!0,this._valuesFromConnections={},this.updateOnDirtyFlagging=!0}Node.prototype.getInputValue=function(e){return this._inputValues[e]},Node.prototype.registerInput=function(e,t){if(this.hasInput(e))throw new Error("Input property "+e+" already registered");if(this._inputs[e]=t,t.type&&t.type.units){const n=t.type.defaultUnit||t.type.units[0];this._inputValues[e]={value:t.default,type:n}}else t.hasOwnProperty("default")&&(this._inputValues[e]=t.default)},Node.prototype.deregisterInput=function(e){if(this.hasInput(e)===!1)throw new Error("Input property "+e+" doesn't exist");delete this._inputs[e],delete this._inputValues[e]},Node.prototype.registerInputs=function(e){for(const t in e)this.registerInput(t,e[t])},Node.prototype.getInput=function(e){if(this.hasInput(e)===!1){console.log("Node "+this.name+": Invalid input property "+e);return}return this._inputs[e]},Node.prototype.hasInput=function(e){return e in this._inputs},Node.prototype.registerInputIfNeeded=function(){},Node.prototype.setInputValue=function(name,value){const input=this.getInput(name);if(!input){console.log("node doesn't have input",name);return}const currentInputValue=this._inputValues[name];if(isNaN(value)===!1&¤tInputValue&¤tInputValue.unit){const e=Object.assign({},currentInputValue);e.value=value,value=e}if(this._inputValues[name]=value,input.type==="color"&&this.context&&this.context.styles)value=this.context.styles.resolveColor(value);else if(input.type==="array"&&typeof value=="string")try{value=eval(value),this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+name)}catch(e){value=[],console.log(e),this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+name,{showGlobally:!0,message:"Invalid array<br>"+e.toString()})}input.set.call(this,value)},Node.prototype.hasOutput=function(e){return e in this._outputs},Node.prototype.registerOutput=function(e,t){if(this.hasOutput(e))throw new Error("Output property "+e+" already registered");const n=new OutputProperty({owner:this,getter:t.get||t.getter,name:e,onFirstConnectionAdded:t.onFirstConnectionAdded,onLastConnectionRemoved:t.onLastConnectionRemoved});this._outputs[e]=n,this._outputList.push(n)},Node.prototype.deregisterOutput=function(e){if(this.hasOutput(e)===!1)throw new Error("Output property "+e+" isn't registered");const t=this._outputs[e];if(t.hasConnections())throw new Error("Output property "+e+" has connections and can't be removed");delete this._outputs[e];var n=this._outputList.indexOf(t);this._outputList.splice(n,1)},Node.prototype.registerOutputs=function(e){for(var t in e)this.registerOutput(t,e[t])},Node.prototype.registerOutputIfNeeded=function(){},Node.prototype.getOutput=function(e){if(this.hasOutput(e)===!1)throw new Error("Node "+this.name+" doesn't have a port named "+e);return this._outputs[e]},Node.prototype.connectInput=function(e,t,n){if(this.hasInput(e)===!1)throw new Error("Invalid connection, input doesn't exist. Trying to connect from "+t.name+" output "+n+" to "+this.name+" input "+e);var o=t.getOutput(n);if(o.registerConnection(this,e),this._inputConnections[e]||(this._inputConnections[e]=[]),this._inputConnections[e].push(o),t._signalsSentThisUpdate[n])this._setValueFromConnection(e,!0),this._setValueFromConnection(e,!1);else{var r=o.value;r!==void 0&&(this._setValueFromConnection(e,r),this.context&&this.context.connectionSentValue(o,o.value))}this.flagDirty()},Node.prototype.removeInputConnection=function(e,t,n){if(!this._inputConnections[e])throw new Error("Node removeInputConnection: Input doesn't exist");const o=this._inputConnections[e];for(let r=0;r<o.length;r++){const s=o[r];if(s.owner.id===t&&s.name===n){o.splice(r,1),s.owner.getOutput(n).deregisterConnection(this,e);break}}o.length===0&&delete this._valuesFromConnections[e]},Node.prototype.isInputConnected=function(e){return this._inputConnections.hasOwnProperty(e)?this._inputConnections[e].some(t=>t.owner.name!=="Component Inputs"?!0:t.owner.nodeScope.componentOwner.isInputConnected(t.name)):!1},Node.prototype.update=function(){if(this._isUpdating||this._dirty===!1)return;this._updatedAtIteration!==this.context.updateIteration&&(this._updatedAtIteration=this.context.updateIteration,this._updateIteration=0,this._cyclicLoop&&(this._cyclicLoop=!1)),this._isUpdating=!0;const e=100;try{for(;this._dirty&&!this._cyclicLoop;){this._updateDependencies(),this._dirty=!1;const t=Object.keys(this._inputValuesQueue);let n=!0;for(;n&&!this._cyclicLoop;){n=!1;for(let r=0;r<t.length;r++){const s=t[r],a=this._inputValuesQueue[s];a.length>0&&(this.setInputValue(s,a.shift()),a.length>0&&(n=!0))}const o=this._afterInputsHaveUpdatedCallbacks;this._afterInputsHaveUpdatedCallbacks=[];for(let r=0;r<o.length;r++)o[r].call(this)}this._updateIteration++,this._updateIteration>=e&&(this._cyclicLoop=!0)}}catch(t){throw this._isUpdating=!1,t}this._cyclicLoop&&(this.context.scheduleNextFrame(()=>{this.context.nodeIsDirty(this)}),this.context.editorConnection&&!this._cyclicWarningSent&&this.context.isWarningTypeEnabled("cyclicLoops")&&(this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"cyclic-loop",{showGlobally:!0,message:"Cyclic loop detected"}),this._cyclicWarningSent=!0,console.log("cycle detected",{id:this.id,name:this.name,component:this.nodeScope.componentOwner.name}))),this._isFirstUpdate=!1,this._isUpdating=!1},Node.prototype._updateDependencies=function(){for(var e in this._inputConnections)for(var t=this._inputConnections[e],n=0;n<t.length;++n)t[n].owner.update()},Node.prototype.flagDirty=function(){this._dirty||(this._dirty=!0,this.updateOnDirtyFlagging&&this._performDirtyUpdate())},Node.prototype._performDirtyUpdate=function(){this.context&&this.context.nodeIsDirty(this);for(var e=0;e<this._outputList.length;++e)this._outputList[e].flagDependeesDirty()},Node.prototype.sendValue=function(e,t){if(this.hasOutput(e)===!1){console.log("Error: Node",this.name,"doesn't have a output named",e);return}if(t===void 0)return;const n=this.getOutput(e);n.sendValue(t),this.context&&this.context.connectionSentValue(n,t)},Node.prototype.flagOutputDirty=function(e){const t=this.getOutput(e);this.sendValue(e,t.value)},Node.prototype.flagAllOutputsDirty=function(){for(const e of this._outputList)this.sendValue(e.name,e.value)},Node.prototype.sendSignalOnOutput=function(e){if(this.hasOutput(e)===!1){console.log("Error: Node",this.name,"doesn't have a output named",e);return}const t=this.getOutput(e);t.sendValue(!0),t.sendValue(!1),this._signalsSentThisUpdate[e]=!0,this.scheduleAfterInputsHaveUpdated(function(){this._signalsSentThisUpdate[e]=!1}),this.context&&this.context.connectionSentSignal(t)},Node.prototype._setValueFromConnection=function(e,t){this._valuesFromConnections[e]=t,this.queueInput(e,t)},Node.prototype._hasInputBeenSetFromAConnection=function(e){return this._valuesFromConnections.hasOwnProperty(e)},Node.prototype.queueInput=function(e,t){if(this._inputValuesQueue[e]||(this._inputValuesQueue[e]=[]),this._isFirstUpdate){const n=this._inputValuesQueue[e][0];n===!0||(n instanceof Object&&n.unit&&!(t instanceof Object)&&(t={value:t,unit:n.unit}),this._inputValuesQueue[e].length=0)}this._inputValuesQueue[e].push(t),this.flagDirty()},Node.prototype.scheduleAfterInputsHaveUpdated=function(e){this._afterInputsHaveUpdatedCallbacks.push(e),this.flagDirty()},Node.prototype.setNodeModel=function(e){this.model=e,e.on("parameterUpdated",this._onNodeModelParameterUpdated,this),e.on("variantUpdated",this._onNodeModelVariantUpdated,this),e.on("inputPortRemoved",t=>{this.hasInput(t.name)&&this.deregisterInput(t.name)},this),e.on("outputPortRemoved",t=>{this.hasOutput(t.name)&&this.deregisterOutput(t.name)},this)},Node.prototype.addDeleteListener=function(e){this._deleteListeners.push(e)},Node.prototype._onNodeDeleted=function(){this.model&&(this.model.removeListenersWithRef(this),this.model=void 0),this._deleted=!0;for(const e of this._deleteListeners)e.call(this)},Node.prototype._onNodeModelParameterUpdated=function(e){if(this.registerInputIfNeeded(e.name),e.value!==void 0)if(e.state){if(!this._getVisualStates){console.log("Node has nos visual states, but got a parameter for state",e.state);return}this._getVisualStates().indexOf(e.state)!==-1&&this.queueInput(e.name,e.value)}else this.queueInput(e.name,e.value);else{let t;const n=this.variant;e.state?n&&n.stateParameters.hasOwnProperty(e.state)&&n.stateParameters[e.state].hasOwnProperty(e.name)?t=n.stateParameters[e.state][e.name]:this.model.parameters.hasOwnProperty(e.name)?t=this.model.parameters[e.name]:n&&n.parameters.hasOwnProperty(e.name)&&(t=n.parameters[e.name]):n&&n.parameters.hasOwnProperty(e.name)&&(t=n.parameters[e.name]),t===void 0&&(t=this.context.getDefaultValueForInput(this.model.type,e.name),this._resetReactVirtualDOM&&this._resetReactVirtualDOM()),this.queueInput(e.name,t)}},Node.prototype._onNodeModelVariantUpdated=function(e){this.setVariant(e)};function guid(){function e(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function NodeScope(e,t){this.context=e,this.nodes={},this.componentOwner=t,this.componentInstanceChildren={}}function verifyData(e,t){t.forEach(function(n){if(!e[n])throw new Error("Missing "+n)})}NodeScope.prototype.addConnection=function(e){try{verifyData(e,["sourceId","sourcePort","targetId","targetPort"])}catch(o){throw new Error("Error in connection: "+o.message)}try{var t=this.getNodeWithId(e.sourceId),n=this.getNodeWithId(e.targetId);n.registerInputIfNeeded(e.targetPort),t.registerOutputIfNeeded(e.sourcePort),n.connectInput(e.targetPort,t,e.sourcePort)}catch(o){console.error(o.message)}},NodeScope.prototype.setNodeParameters=function(e,t){const n=this.context.variants.getVariant(t.type,t.variant);if(n)e.setVariant(n);else{const s=t.parameters;var o=Object.keys(s);if(this.context.nodeRegister.hasNode(e.name)){var r=this.context.nodeRegister.getNodeMetadata(e.name);o.sort(function(a,u){var l=r.inputs[a],d=r.inputs[u];return(d?d.inputPriority:0)-(l?l.inputPriority:0)})}o.forEach(a=>{e.registerInputIfNeeded(a),e.hasInput(a)!==!1&&e.queueInput(a,s[a])})}},NodeScope.prototype.createNodeFromModel=async function(e,t){if(e.type==="Component Children"){if(e.parent){var n=this.getNodeWithId(e.parent.id);this.componentOwner.setChildRoot(n)}return}var o;try{o=await this.createNode(e.type,e.id),o.updateOnDirtyFlagging=t!==!1,o.setNodeModel(e)}catch(r){console.error(r.message),this.context.editorConnection&&this.context.isWarningTypeEnabled("nodescope")&&this.context.editorConnection.sendWarning(this.componentOwner.name,e.id,"nodelibrary-unknown-node",{message:r.message,showGlobally:!0});return}return e.variant&&o.setVariant&&o.setVariant(e.variant),this.setNodeParameters(o,e),e.parent&&this.insertNodeInTree(o,e),o},NodeScope.prototype.insertNodeInTree=function(e,t){var n=this.getNodeWithId(t.parent.id),o=t.parent.children.indexOf(t);if(!n.addChild)throw new Error("Node "+n.id+" of type "+n.constructor.name+" can't have children");n.addChild(e,o)},NodeScope.prototype.getNodeWithId=function(e){if(this.nodes.hasOwnProperty(e)===!1)throw new Error("Unknown node id "+e);return this.nodes[e]},NodeScope.prototype.hasNodeWithId=function(e){return this.nodes.hasOwnProperty(e)},NodeScope.prototype.createPrimitiveNode=function(e,t,n){if(t||(t=guid()),this.nodes.hasOwnProperty(t))throw Error("duplicate id "+t);const o=this.context.nodeRegister.createNode(e,t,this);if(n)for(const r in n)o[r]=n[r];return this.nodes[t]=o,o},NodeScope.prototype.createNode=async function(e,t,n){if(t||(t=guid()),this.nodes.hasOwnProperty(t))throw Error("duplicate id "+t);let o;if(this.context.nodeRegister.hasNode(e)){if(o=this.context.nodeRegister.createNode(e,t,this),n)for(const r in n)o[r]=n[r]}else o=await this.context.createComponentInstanceNode(e,t,this,n),this.componentInstanceChildren[t]=o;return this.nodes[t]=o,o},NodeScope.prototype.getNodesWithIdRecursive=function(e){function t(o,r,s){o.nodes.hasOwnProperty(r)&&s.push(o.nodes[r]);var a=Object.keys(o.nodes).filter(function(u){return o.nodes[u]instanceof ComponentInstanceNode});a.forEach(function(u){t(o.nodes[u].nodeScope,r,s)})}var n=[];return t(this,e,n),n},NodeScope.prototype.getNodesWithType=function(e){var t=this,n=Object.keys(this.nodes).filter(function(o){return t.nodes[o].name===e});return n.map(function(o){return t.nodes[o]})},NodeScope.prototype.getNodesWithTypeRecursive=function(e){var t=this;function n(){o=o.concat(t.getNodesWithType(e));var r=Object.keys(t.nodes).filter(function(s){return t.nodes[s]instanceof ComponentInstanceNode});r.forEach(function(s){var a=t.nodes[s].nodeScope.getNodesWithTypeRecursive(e);o=o.concat(a)})}var o=[];return n(),o},NodeScope.prototype.getAllNodesRecursive=function(){let e=[];return(()=>{e=e.concat(Object.values(this.nodes));var n=Object.keys(this.nodes).filter(o=>this.nodes[o]instanceof ComponentInstanceNode);n.forEach(o=>{var r=this.nodes[o].nodeScope.getAllNodesRecursive();e=e.concat(r)})})(),e},NodeScope.prototype.getAllNodesWithVariantRecursive=function(e){return this.getAllNodesRecursive().filter(n=>n.variant===e)},NodeScope.prototype.onNodeModelRemoved=function(e){var t=this.getNodeWithId(e.id);if(e.parent){var n=this.getNodeWithId(e.parent.id);n.removeChild(t)}t._onNodeDeleted(),delete this.nodes[t.id],delete this.componentInstanceChildren[t.id]},NodeScope.prototype.removeConnection=function(e){var t=this.getNodeWithId(e.targetId);t.removeInputConnection(e.targetPort,e.sourceId,e.sourcePort)},NodeScope.prototype.setComponentModel=async function(e){this.componentModel=e;const t=[];for(const o of e.getAllNodes()){const r=await this.createNodeFromModel(o,!1);r&&t.push(r)}e.getAllConnections().forEach(o=>this.addConnection(o)),t.forEach(o=>o.updateOnDirtyFlagging=!0),t.forEach(o=>{o._dirty&&o._performDirtyUpdate()}),e.on("connectionAdded",o=>this.addConnection(o),this),e.on("connectionRemoved",this.removeConnection,this),e.on("nodeAdded",this.createNodeFromModel,this);var n=this;e.on("nodeParentWillBeRemoved",function(o){if(o.type==="Component Children"){o.parent&&this.componentOwner.setChildRoot(null);return}const r=n.getNodeWithId(o.id);r.parent&&r.parent.removeChild(r)},this),e.on("nodeParentUpdated",function(o){if(o.type==="Component Children"){var r=this.getNodeWithId(o.parent.id);this.componentOwner.setChildRoot(r)}else{var s=n.getNodeWithId(o.id);n.insertNodeInTree(s,o)}},this),e.on("nodeRemoved",function(o){o.type!=="Component Children"&&n.onNodeModelRemoved(o)},this);for(const o in this.nodes){const r=this.nodes[o];r.nodeScopeDidInitialize&&r.nodeScopeDidInitialize()}},NodeScope.prototype.reset=function(){this.componentModel&&(this.componentModel.removeListenersWithRef(this),this.componentModel=void 0),Object.keys(this.nodes).forEach(e=>{this.nodes.hasOwnProperty(e)&&this.deleteNode(this.nodes[e])})},NodeScope.prototype.deleteNode=function(e){if(this.nodes.hasOwnProperty(e.id)===!1){console.error("Node doesn't belong to this scope",e.id,e.name);return}if(e.parent&&e.parent.removeChild(e),e.getChildren&&e.getChildren().forEach(t=>{e.removeChild(t),(t.parentNodeScope||t.nodeScope).deleteNode(t)}),this.componentModel){const t=this.componentModel.getConnectionsFrom(e.id),n=this.componentModel.getConnectionsTo(e.id);t.concat(n).forEach(o=>{this.nodes.hasOwnProperty(o.targetId)&&this.nodes.hasOwnProperty(o.sourceId)&&this.removeConnection(o)})}e._onNodeDeleted(),delete this.nodes[e.id],delete this.componentInstanceChildren[e.id]},NodeScope.prototype.sendEventFromThisScope=function(e,t,n,o,r){if(o)for(var s=this.getNodesWithType("Event Receiver").filter(function(m){return m.getChannelName()===e}),a=0;a<s.length;a++){var u=s[a].handleEvent(t);if(u)return!0}if(n==="parent"&&this.componentOwner.parentNodeScope){const m=this.componentOwner.parent?this.componentOwner.parent.nodeScope:this.componentOwner.parentNodeScope;if(!m)return;m.sendEventFromThisScope(e,t,n,!0)}else if(n==="children"){var l=this.nodes;for(var d in l){var p=l[d].children;p&&p.forEach(m=>{if(m.name&&this.context.hasComponentModelWithName(m.name)){var y=m.nodeScope.sendEventFromThisScope(e,t,n,!0);if(y)return!0}})}}else if(n==="siblings"){let m;if(this.componentOwner.parent?m=this.componentOwner.parent.nodeScope:m=this.componentOwner.parentNodeScope,!m)return;var l=m.nodes;for(var d in l){var p=l[d].children;if(p){var f=p.filter(S=>S.name&&this.context.hasComponentModelWithName(S.name)&&S.nodeScope!==this);f.forEach(S=>{var C=S.nodeScope.sendEventFromThisScope(e,t,null,!0);if(C)return!0})}}}return!1};let componentIdCounter=0;function ComponentInstanceNode(e,t,n){Node.call(this,e,t),this.nodeScope=new NodeScope(e,this),this.parentNodeScope=n,this._internal.childRoot=null,this._internal.componentOutputValues={},this._internal.componentOutputs=[],this._internal.componentInputs=[],this._internal.inputValues={},this._internal.roots=[],this._internal.instanceId="__$ndl_componentInstaceId"+componentIdCounter,this.nodeScope.modelScope=n?n.modelScope:void 0,componentIdCounter++}ComponentInstanceNode.prototype=Object.create(Node.prototype,{setComponentModel:{value:async function(e){this.componentModel=e;var t=this;await this.nodeScope.setComponentModel(e),this._internal.componentInputs=this.nodeScope.getNodesWithType("Component Inputs"),this._internal.componentOutputs=this.nodeScope.getNodesWithType("Component Outputs"),Object.values(e.getInputPorts()).forEach(this.registerComponentInputPort.bind(this)),Object.values(e.getOutputPorts()).forEach(this.registerComponentOutputPort.bind(this));const n=e.roots||[];this._internal.roots=n.map(o=>this.nodeScope.getNodeWithId(o)),e.on("rootAdded",o=>{this._internal.roots.push(this.nodeScope.getNodeWithId(o)),this.forceUpdate()},this),e.on("rootRemoved",function(o){const r=this._internal.roots.findIndex(s=>s.id===o);r!==-1&&this._internal.roots.splice(r,1),this.forceUpdate()},this),e.on("inputPortAdded",this.registerComponentInputPort.bind(this),this),e.on("outputPortAdded",this.registerComponentOutputPort.bind(this),this),e.on("inputPortRemoved",function(o){t.hasInput(o.name)&&t.deregisterInput(o.name)},this),e.on("outputPortRemoved",function(o){this.hasOutput(o.name)&&t.deregisterOutput(o.name)},this),e.on("nodeAdded",function(o){o.type==="Component Inputs"?t._internal.componentInputs.push(t.nodeScope.getNodeWithId(o.id)):o.type==="Component Outputs"&&t._internal.componentOutputs.push(t.nodeScope.getNodeWithId(o.id))},this),e.on("nodeRemoved",function(o){function r(s,a){return s.filter(u=>u.id!==a)}o.type==="Component Inputs"?t._internal.componentInputs=r(t._internal.componentInputs,o.id):o.type==="Component Outputs"&&(t._internal.componentOutputs=r(t._internal.componentOutputs,o.id))},this),e.on("renamed",function(o){t.name=o.newName},this)}},_onNodeDeleted:{value(){this.componentModel&&(this.componentModel.removeListenersWithRef(this),this.componentModel=void 0),this.nodeScope.reset(),Node.prototype._onNodeDeleted.call(this)}},registerComponentInputPort:{value(e){this.registerInput(e.name,{set(t){this._internal.inputValues[e.name]=t,this._internal.componentInputs.forEach(function(n){n.registerOutputIfNeeded(e.name),n.flagOutputDirty(e.name)})}})}},registerComponentOutputPort:{value(e){this.registerOutput(e.name,{getter(){return this._internal.componentOutputValues[e.name]}})}},setOutputFromComponentOutput:{value(e,t){this.hasOutput(e)!==!1&&(this._internal.creatorCallbacks&&this._internal.creatorCallbacks.onOutputChanged&&this._internal.creatorCallbacks.onOutputChanged(e,t,this._internal.componentOutputValues[e]),this._internal.componentOutputValues[e]=t,this.flagOutputDirty(e))}},setChildRoot:{value(e){const t=this._internal.childRoot,n=e;if(this._internal.childRoot=n,this.model&&this.model.children){const o=this.parentNodeScope,r=this.model.children.filter(s=>s.type!=="Component Children").map(s=>o.getNodeWithId(s.id));if(t)for(let s=0;s<r.length;s++)t.isChild(r[s])&&t.removeChild(r[s]);if(n)for(let s=0;s<r.length;s++){const a=r[s],u=a.model.parent.children.indexOf(a.model);this.addChild(a,u)}}}},getChildRootIndex:{value(){if(!this._internal.childRoot||!this._internal.childRoot.model||!this._internal.childRoot.model.children)return 0;for(var e=this._internal.childRoot.model.children,t=0;t<e.length;t++)if(e[t].type==="Component Children")return t;return 0}},getChildRoot:{value(){return this._internal.childRoot?this._internal.childRoot:null}},getRoots:{value(){return this._internal.roots}},triggerDidMount:{value(){this._internal.roots.forEach(e=>{e.triggerDidMount&&e.triggerDidMount()})}},render:{value(){return this._internal.roots.length===0?null:this._internal.roots[0].render()}},setChildIndex:{value(e){this.getRoots().forEach(t=>t.setChildIndex&&t.setChildIndex(e))}},addChild:{value(e,t){this.getChildRoot().addChild(e,t+this.getChildRootIndex())}},removeChild:{value(e){this.getChildRoot().removeChild(e)}},getChildren:{value(e){const t=this.getChildRoot();return t?t.getChildren():[]}},isChild:{value(e){return this.getChildRoot()?this.getChildRoot().isChild(e):!1}},contains:{value(e){return this.getRoots().some(t=>t.contains&&t.contains(e))}},_performDirtyUpdate:{value(){Node.prototype._performDirtyUpdate.call(this);for(var e=this._internal.componentInputs,t=0,n=e.length;t<n;t++)e[t].flagDirty();this._internal.componentOutputs.forEach(function(o){o.flagDirty()})}},getRef:{value(){const e=this._internal.roots[0];return e?e.getRef():void 0}},update:{value(){Node.prototype.update.call(this),this._internal.componentOutputs.forEach(function(e){e.update()})}},forceUpdate:{value(){this.parent&&(this.parent.cachedChildren=void 0,this.parent.forceUpdate())}},getInstanceId:{value(){return this._internal.instanceId}}}),ComponentInstanceNode.prototype.constructor=ComponentInstanceNode;function NodeContext(e){e=e||{},e.runningInEditor=e.hasOwnProperty("runningInEditor")?e.runningInEditor:!1,this._dirtyNodes=[],this.callbacksAfterUpdate=[],this.graphModel=e.graphModel,this.platform=e.platform,this.eventEmitter=new EventEmitter,this.eventEmitter.setMaxListeners(1e6),this.eventSenderEmitter=new EventEmitter,this.eventSenderEmitter.setMaxListeners(1e6),this.globalValues={},this.globalsEventEmitter=new EventEmitter,this.globalsEventEmitter.setMaxListeners(1e6),this.runningInEditor=e.runningInEditor,this.currentFrameTime=0,this.frameNumber=0,this.updateIteration=0,this.nodeRegister=new NodeRegister(this),this.timerScheduler=new TimerScheduler(this.scheduleUpdate.bind(this)),this.componentModels={},this.debugInspectorsEnabled=!1,this.connectionsToPulse={},this.connectionsToPulseChanged=!1,this.debugInspectors={},this.connectionPulsingCallbackScheduled=!1,this.editorConnection=e.editorConnection,this.rootComponent=void 0,this._outputHistory={},this._signalHistory={},this.warningTypes={},this.bundleFetchesInFlight=new Map,this.variants=new Variants({graphModel:this.graphModel,getNodeScope:()=>this.rootComponent?this.rootComponent.nodeScope:null}),this.editorConnection&&(this.editorConnection.on("debugInspectorsUpdated",t=>{this.onDebugInspectorsUpdated(t)}),this.editorConnection.on("getConnectionValue",({clientId:t,connectionId:n})=>{if(this.editorConnection.clientId!==t)return;const o=this._outputHistory[n];this.editorConnection.sendConnectionValue(n,o?o.value:void 0)}))}NodeContext.prototype.setRootComponent=function(e){this.rootComponent=e},NodeContext.prototype.getCurrentTime=function(){return this.platform.getCurrentTime()},NodeContext.prototype.onDebugInspectorsUpdated=function(e){this.debugInspectorsEnabled&&(e=e.map(t=>{if(t.type==="connection"){const n=t.connection;t.id=n.fromId+n.fromProperty}else t.type==="node"&&(t.id=t.nodeId);return t}),this.debugInspectors={},e.forEach(t=>this.debugInspectors[t.id]=t),this.sendDebugInspectorValues())},NodeContext.prototype.updateDirtyNodes=function(){var e,t,n=!0,o=0;for(this.updateIteration++,this.isUpdating=!0;n&&o<10;){var r=this._dirtyNodes;for(this._dirtyNodes=[],e=0,t=r.length;e<t;++e)try{r[e]._deleted||r[e].update()}catch(a){console.error(a,a.stack)}var s=this.callbacksAfterUpdate;for(this.callbacksAfterUpdate=[],e=0,t=s.length;e<t;e++)try{s[e]()}catch(a){console.error(a)}n=this.callbacksAfterUpdate.length>0||this._dirtyNodes.length>0,o++}this.isUpdating=!1},NodeContext.prototype.update=function(){this.frameNumber++,this.updateDirtyNodes(),this.timerScheduler.hasPendingTimers()&&(this.scheduleUpdate(),this.timerScheduler.runTimers(this.currentFrameTime)),this.debugInspectorsEnabled&&this.sendDebugInspectorValues()},NodeContext.prototype.reset=function(){this.eventEmitter.emit("applicationDataReloaded");var e=this.eventEmitter;["frameStart","frameEnd"].forEach(function(t){e.removeAllListeners(t)}),this.globalValues={},this._dirtyNodes.length=0,this.callbacksAfterUpdate.length=0,this.timerScheduler.runningTimers=[],this.timerScheduler.newTimers=[],this.rootComponent=void 0,this.clearDebugInspectors()},NodeContext.prototype.nodeIsDirty=function(e){this._dirtyNodes.push(e),this.scheduleUpdate()},NodeContext.prototype.scheduleUpdate=function(){this.eventEmitter.emit("scheduleUpdate")},NodeContext.prototype.scheduleAfterUpdate=function(e){this.callbacksAfterUpdate.push(e),this.scheduleUpdate()},NodeContext.prototype.scheduleNextFrame=function(e){this.eventEmitter.once("frameStart",e),this.scheduleUpdate()},NodeContext.prototype.setGlobalValue=function(e,t){this.globalValues[e]=t,this.globalsEventEmitter.emit(e)},NodeContext.prototype.getGlobalValue=function(e){return this.globalValues[e]},NodeContext.prototype.registerComponentModel=function(e){if(this.componentModels.hasOwnProperty(e.name))throw new Error("Duplicate component name "+e.name);this.componentModels[e.name]=e;var t=this;e.on("renamed",function(n){delete t.componentModels[n.oldName],t.componentModels[n.newName]=e},this)},NodeContext.prototype.deregisterComponentModel=function(e){this.componentModels.hasOwnProperty(e.name)&&(this.componentModels[e.name].removeListenersWithRef(this),delete this.componentModels[e.name])},NodeContext.prototype.fetchComponentBundle=async function(e){const t=async n=>{let r=`${Noodl.Env.BaseUrl||"/"}noodl_bundles/${n}.json`;const s=await fetch(r);if(s.status===404)throw new Error("Component not found "+n);const a=await s.json();for(const u of a)this.graphModel.hasComponentWithName(u.name)===!1&&await this.graphModel.importComponentFromEditorData(u)};if(this.bundleFetchesInFlight.has(e))await this.bundleFetchesInFlight.get(e);else{const n=t(e);this.bundleFetchesInFlight.set(e,n),await n}},NodeContext.prototype.getComponentModel=async function(e){if(!e)throw new Error("Component instance must have a name");if(this.componentModels.hasOwnProperty(e)===!1){const t=this.graphModel.getBundleContainingComponent(e);if(!t)throw new Error("Can't find component model for "+e);for(const n of this.graphModel.getBundleDependencies(t))this.fetchComponentBundle(n);await this.fetchComponentBundle(t)}return this.componentModels[e]},NodeContext.prototype.hasComponentModelWithName=function(e){return this.componentModels.hasOwnProperty(e)},NodeContext.prototype.createComponentInstanceNode=async function(e,t,n,o){var r=new ComponentInstanceNode(this,t,n);r.name=e;for(const a in o)r[a]=o[a];const s=await this.getComponentModel(e);return await r.setComponentModel(s),r},NodeContext.prototype._formatConnectionValue=function(e){if(typeof e=="object"&&e&&e.constructor&&e.constructor.name==="Node")e="<Node> "+e.name;else if(typeof e=="object"&&typeof window<"u"&&e instanceof HTMLElement)e=`DOM Node <${e.tagName}>`;else{if(typeof e=="string"&&!e.startsWith("[Signal]"))return'"'+e+'"';if(Number.isNaN(e))return"NaN"}return e},NodeContext.prototype.connectionSentValue=function(e,t){if(!this.editorConnection||!this.editorConnection.isConnected()||!this.debugInspectorsEnabled)return;const n=this.getCurrentTime();if(this._outputHistory[e.id]={value:t,timestamp:n},this.connectionsToPulse.hasOwnProperty(e.id)){this.connectionsToPulse[e.id].timestamp=n;return}const o=[];e.connections.forEach(r=>{o.push(e.owner.id+e.name+r.node.id+r.inputPortName)}),this.connectionsToPulse[e.id]={timestamp:n,connections:o},this.connectionsToPulseChanged=!0,this.connectionPulsingCallbackScheduled===!1&&(this.connectionPulsingCallbackScheduled=!0,setTimeout(this.clearOldConnectionPulsing.bind(this),100))},NodeContext.prototype.connectionSentSignal=function(e){const t=e.id;this._signalHistory.hasOwnProperty(t)||(this._signalHistory[t]={count:0}),this._signalHistory[t].count++,this.connectionSentValue(e,"[Signal] Trigger count "+this._signalHistory[t].count)},NodeContext.prototype.clearDebugInspectors=function(){this.debugInspectors={},this.connectionsToPulse={},this.editorConnection.sendPulsingConnections(this.connectionsToPulse)},NodeContext.prototype.clearOldConnectionPulsing=function(){this.connectionPulsingCallbackScheduled=!1;var e=this.getCurrentTime(),t=this,n=Object.keys(this.connectionsToPulse);n.forEach(function(o){var r=t.connectionsToPulse[o];e-r.timestamp>100&&(t.connectionsToPulseChanged=!0,delete t.connectionsToPulse[o])}),this.connectionsToPulseChanged&&(this.connectionsToPulseChanged=!1,this.editorConnection.sendPulsingConnections(this.connectionsToPulse)),Object.keys(this.connectionsToPulse).length>0&&(this.connectionPulsingCallbackScheduled=!0,setTimeout(this.clearOldConnectionPulsing.bind(this),500))},NodeContext.prototype._getDebugInspectorValueForNode=function(e){if(!this.rootComponent)return;const t=this.rootComponent.nodeScope.getNodesWithIdRecursive(e),n=t[t.length-1];if(n&&n.getInspectInfo){const o=n.getInspectInfo();if(o!==void 0)return{type:"node",id:e,value:o}}},NodeContext.prototype.sendDebugInspectorValues=function(){const e=[];for(const t in this.debugInspectors){const n=this.debugInspectors[t];if(n.type==="connection"&&this._outputHistory.hasOwnProperty(t)){const o=this._outputHistory[t].value;e.push({type:"connection",id:t,value:this._formatConnectionValue(o)})}else if(n.type==="node"){const o=this._getDebugInspectorValueForNode(t);o&&e.push(o)}}e.length>0&&this.editorConnection.sendDebugInspectorValues(e),this.connectionsToPulseChanged&&(this.connectionsToPulseChanged=!1,this.editorConnection.sendPulsingConnections(this.connectionsToPulse))},NodeContext.prototype.setDebugInspectorsEnabled=function(e){this.debugInspectorsEnabled=e,this.editorConnection.debugInspectorsEnabled=e,e&&this.sendDebugInspectorValues()},NodeContext.prototype.sendGlobalEventFromEventSender=function(e,t){this.eventSenderEmitter.emit(e,t)},NodeContext.prototype.setPopupCallbacks=function({onShow:e,onClose:t}){this.onShowPopup=e,this.onClosePopup=t},NodeContext.prototype.showPopup=async function(e,t,n){if(!this.onShowPopup)return;const o=this.rootComponent.nodeScope,r=await o.createNode(e);for(const d in t)r.setInputValue(d,t[d]);r.popupParent=n?.senderNode||null;const s=o.createPrimitiveNode("Group");s.setInputValue("flexDirection","node"),s.setInputValue("cssClassName","noodl-popup");const a=this.graphModel.getSettings().bodyScroll;s.setInputValue("position",a?"fixed":"absolute");var u=r.nodeScope.getNodesWithType("NavigationClosePopup");if(u&&u.length>0)for(var l=0;l<u.length;l++)u[l]._setCloseCallback((d,p)=>{this.scheduleNextFrame(()=>{o.hasNodeWithId(s.id)&&(this.onClosePopup(s),o.deleteNode(s),n&&n.onClosePopup&&n.onClosePopup(d,p))})});this.onShowPopup(s),requestAnimationFrame(()=>{s.addChild(r)})},NodeContext.prototype.setWarningTypes=function(e){Object.assign(this.warningTypes,e)},NodeContext.prototype.isWarningTypeEnabled=function(e){return this.warningTypes.hasOwnProperty(e)?!!this.warningTypes[e]:!0},NodeContext.prototype.getDefaultValueForInput=function(e,t){if(this.nodeRegister.hasNode(e)===!1)return;const o=this.nodeRegister.getNodeMetadata(e).inputs[t];if(o)return o.type.defaultUnit?{value:o.default,unit:o.type.defaultUnit}:o.default};function EventSender(){this.listeners={},this.listenersWithRefs={}}EventSender.prototype.on=function(e,t,n){n?(this.listenersWithRefs.hasOwnProperty(e)||(this.listenersWithRefs[e]=new Map),this.listenersWithRefs[e].get(n)||this.listenersWithRefs[e].set(n,[]),this.listenersWithRefs[e].get(n).push(t)):(this.listeners.hasOwnProperty(e)||(this.listeners[e]=[]),this.listeners[e].push(t))},EventSender.prototype.removeListenersWithRef=function(e){Object.keys(this.listenersWithRefs).forEach(t=>{const n=this.listenersWithRefs[t];n.has(e)&&n.delete(e)})},EventSender.prototype.removeAllListeners=function(e){e?(delete this.listeners[e],delete this.listenersWithRefs[e]):(this.listeners={},this.listenersWithRefs={})},EventSender.prototype.emit=async function(e,t){const n=this.listeners[e];if(n)for(let r=0;r<n.length;r++){const s=n[r];await Promise.resolve(s.call(null,t))}const o=this.listenersWithRefs[e];if(o)for(const[r,s]of o)for(const a of s)await Promise.resolve(a.call(r,t))};function Services(){}Services.events=new EventEmitter;class ActiveWarnings{constructor(){this.currentWarnings=new Map}setWarning(t,n,o){if(this.currentWarnings.has(t)){const r=this.currentWarnings.get(t);return r[n]===o?!1:(r[n]=o,!0)}else return this.currentWarnings.set(t,{[n]:o}),!0}clearWarning(t,n){const o=this.currentWarnings.get(t);return!o||!o[n]?!1:(delete o[n],Object.keys(o).length===0&&delete this.currentWarnings.delete(t),!0)}clearWarnings(t){return this.currentWarnings.has(t)===!1?!1:(this.currentWarnings.delete(t),!0)}}function EditorConnection(e){var t=e||{};EventSender.call(this),this.runtimeType=t.runtimeType,this.platform=t.platform,this.ws=t.platform&&t.platform.webSocketClass||(typeof WebSocket<"u"?WebSocket:void 0),this.wsOptions=t.platform&&t.platform.webSocketOptions||void 0,this.reconnectOnClose=!0,this.enableDebugger=!1,this.lastSendTimestamp=0,this.sendQueue=[],this.sendTimer=void 0,this.activeWarnings=new ActiveWarnings}EditorConnection.prototype=Object.create(EventSender.prototype),EditorConnection.prototype.constructor=EditorConnection,EditorConnection.prototype.isRunningLocally=function(){var e=this.platform.isRunningLocally&&this.platform.isRunningLocally()||typeof document<"u"&&(document.location.hostname==="localhost"||document.location.hostname==="127.0.0.1");return e},EditorConnection.prototype.connect=function(e){this.socket=this.wsOptions?new this.ws(e,this.wsOptions):new this.ws(e);var t=this;this.socket.addEventListener("open",function(){t.clientId=guid(),t.socket.send(JSON.stringify({cmd:"register",type:"viewer",clientId:t.clientId})),t.emit("connected")}),this.socket.addEventListener("close",function(n){t.reconnectOnClose&&t.reconnect(e),console.log("Editor connection closed",n.code,n.reason),t.emit("connectionClosed")}),this.socket.addEventListener("error",function(n){console.log("Editor connection error, trying to reconnect")}),this.socket.addEventListener("message",async n=>{const o=typeof n.data=="string"?n.data:await n.data.text(),r=JSON.parse(o);let s;r.cmd==="registered"||(r.cmd==="export"?(s=JSON.parse(r.content),r.type==="full"&&r.target===this.clientId&&t.emit("exportDataFull",s)):r.cmd==="hoverStart"?t.emit("hoverStart",r.content.id):r.cmd==="hoverEnd"?t.emit("hoverEnd",r.content.id):r.cmd==="refresh"?t.emit("reload"):r.cmd==="debugInspectors"?this.debugInspectorsEnabled&&(s=JSON.parse(r.content),t.emit("debugInspectorsUpdated",s.inspectors)):r.cmd==="debuggingEnabled"?t.isRunningLocally()&&(s=JSON.parse(r.content),t.emit("debuggingEnabledChanged",s.enabled)):r.cmd==="getConnectionValue"?t.isRunningLocally()&&(s=JSON.parse(r.content),await t.emit("getConnectionValue",{clientId:s.clientId,connectionId:s.connectionId})):r.cmd==="modelUpdate"?await t.emit("modelUpdate",r.content):r.cmd==="publish"?Services.pubsub.routeMessage(r):r.cmd==="noodlModules"?t.emit("noodlModules",JSON.parse(r.content)):r.cmd==="mqttUpdate"?t.emit("mqttUpdate",r.content):r.cmd==="activeComponentChanged"?t.emit("activeComponentChanged",r.component):console.log("Command not implemented",r))})},EditorConnection.prototype.reconnect=function(e){var t=this;setTimeout(function(){t.connect(e)},2e3)},EditorConnection.prototype.isConnected=function(){return this.socket!==void 0&&this.socket.readyState===this.ws.OPEN};const getCircularReplacer=()=>{const e=new WeakSet;return(t,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n}};EditorConnection.prototype.send=function(e){const t=this.platform.getCurrentTime(),n=t-this.lastSendTimestamp,o=r=>{try{this.socket.send(JSON.stringify(r))}catch(s){if(s.message&&s.message.startsWith("Converting circular"))try{this.socket.send(JSON.stringify(r,getCircularReplacer()))}catch(a){console.log("failed to send message to editor",r,a)}else console.log("failed to send message to editor",r,s)}};n<200||this.sendTimer||!this.isConnected()?(this.sendQueue.push(e),this.sendTimer||(this.sendTimer=setTimeout(()=>{if(this.isConnected()===!1)return;const r=50;for(let s=0;s<this.sendQueue.length;s+=r){const a=this.sendQueue.slice(s,s+r);o(a)}this.sendQueue=[],this.sendTimer=void 0,this.lastSendTimestamp=this.platform.getCurrentTime()},100))):(this.lastSendTimestamp=t,o(e))},EditorConnection.prototype.sendInspectId=function(e){this.send({cmd:"select",type:"viewer",content:JSON.stringify({id:e})})},EditorConnection.prototype.sendSelectComponent=function(e){this.send({cmd:"select",type:"viewer",content:JSON.stringify({componentName:e})})},EditorConnection.prototype.sendPulsingConnections=function(e){var t=[];Object.keys(e).forEach(function(n){var o=e[n];t=t.concat(o.connections)}),this.send({cmd:"connectiondebugpulse",type:"viewer",content:JSON.stringify({connectionsToPulse:t})})},EditorConnection.prototype.sendDebugInspectorValues=function(e){this.send({cmd:"debuginspectorvalues",type:"viewer",content:{inspectors:e}})},EditorConnection.prototype.sendConnectionValue=function(e,t){this.send({cmd:"connectionValue",type:"viewer",content:{connectionId:e,value:t}})};const dynamicPortsHash={};function _detectRename(e,t){if(!(!e||!t)&&e.length===t.length){for(var n={},o=0;o<e.length;o++){if(t.indexOf(e[o])===-1){if(n.before)return;n.before=e[o]}if(e.indexOf(t[o])===-1){if(n.after)return;n.after=t[o]}}return n.before&&n.after?n:void 0}}EditorConnection.prototype.sendDynamicPorts=function(e,t,n){var o=JSON.stringify(t);if(dynamicPortsHash[e]!==o){if(dynamicPortsHash[e]&&t&&n&&n.detectRenamed){var r=Array.isArray(n.detectRenamed)?n.detectRenamed:[n.detectRenamed],s=[];r.forEach(a=>{var u=JSON.parse(dynamicPortsHash[e]),l=[].concat(t);a.prefix&&(u=u.filter(p=>p.name.startsWith(a.prefix)),l=l.filter(p=>p.name.startsWith(a.prefix))),a.plug&&(u=u.filter(p=>p.plug===a.plug),l=l.filter(p=>p.plug===a.plug)),l=l.map(p=>p.name.substring((a.prefix||"").length)),u=u.map(p=>p.name.substring((a.prefix||"").length));var d=_detectRename(u,l);d&&s.push({plug:a.plug,patterns:[(a.prefix||"")+"{{*}}"],before:d.before,after:d.after})}),s.length>0&&(n.renamed=s),delete n.detectRenamed}dynamicPortsHash[e]=o,this.send({cmd:"instanceports",type:"viewer",content:JSON.stringify({nodeid:e,ports:t,options:n})})}},EditorConnection.prototype.sendWarning=function(e,t,n,o){this.activeWarnings.setWarning(t,n,o)&&this.send({cmd:"showwarning",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t,key:n,warning:o})})},EditorConnection.prototype.clearWarning=function(e,t,n){this.activeWarnings.clearWarning(t,n)&&this.send({cmd:"showwarning",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t,key:n,warning:void 0})})},EditorConnection.prototype.clearWarnings=function(e,t){this.activeWarnings.clearWarnings(t)&&this.send({cmd:"clearwarnings",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t})})},EditorConnection.prototype.sendPatches=function(e){this.send({cmd:"patchproject",type:"viewer",content:JSON.stringify(e)})},EditorConnection.prototype.requestFullExport=function(){this.send({cmd:"register",type:"viewer"})},EditorConnection.prototype.requestNoodlModules=function(){this.send({cmd:"getNoodlModules",type:"viewer"})};var serviceRequests={};EditorConnection.prototype.sendServiceRequest=function(e,t){e.token=guid(),e.clientId=this.clientId,serviceRequests[e.token]=t,this.send(e)},EditorConnection.prototype.close=function(){this.reconnectOnClose=!1,this.isConnected()!==!1&&this.socket.close()},EditorConnection.prototype.sendNodeLibrary=function(e){this.send({cmd:"nodelibrary",type:"viewer",runtimeType:this.runtimeType,content:e,clientId:this.clientId})},EditorConnection.prototype.sendComponentMetadata=function(e,t,n){this.send({cmd:"componentMetadata",type:"viewer",content:JSON.stringify({componentName:e,key:t,data:n})})},EditorConnection.prototype.sendProjectMetadata=function(e,t){this.send({cmd:"projectMetadata",type:"viewer",content:JSON.stringify({key:e,data:t})})};function formatDynamicPorts(e){const t=[];for(const n of e.dynamicports)if(n.ports||n.template||n.port||n.channelPort)t.push(n);else if(n.inputs||n.outputs){const o=[];if(n.inputs)for(const s of n.inputs)o.push(formatPort(s,e.inputs[s],"input"));if(n.outputs)for(const s of n.outputs)o.push(formatPort(s,e.outputs[s],"output"));const r={name:n.name||"conditionalports/basic",condition:n.condition,ports:o};t.push(r)}return t}function formatPort(e,t,n){var o={name:e,type:t.type,plug:n};return t.group&&(o.group=t.group),t.displayName&&(o.displayName=t.displayName),t.description&&(o.description=t.description),t.editorName&&(o.editorName=t.editorName),t.default!==void 0&&(o.default=t.default),t.hasOwnProperty("index")&&(o.index=t.index),t.tooltip&&(o.tooltip=t.tooltip),t.tab&&(o.tab=t.tab),t.popout&&(o.popout=t.popout),t.allowVisualStates&&(o.allowVisualStates=t.allowVisualStates),o}function generateNodeLibrary(e){var t={typecasts:[{from:"string",to:["number","boolean","image","color","enum","textStyle","dimension","array","object"]},{from:"boolean",to:["number","string","signal"]},{from:"number",to:["boolean","string","dimension"]},{from:"date",to:["string"]},{from:"signal",to:["boolean","number"]},{from:"image",to:[]},{from:"cloudfile",to:["string","image"]},{from:"color",to:[]},{from:"enum",to:[]},{from:"object",to:[]},{from:"domelement",to:[]},{from:"reference",to:[]},{from:"font",to:[]},{from:"textStyle",to:["string"]},{from:"collection",to:["array"]},{from:"array",to:["collection"]}],dynamicports:[{type:"conditionalports",name:"basic"},{type:"expand",name:"basic"}],colors:{nodes:{component:{base:"#643D8B",baseHighlighted:"#79559b",header:"#4E2877",headerHighlighted:"#643d8b",outline:"#4E2877",outlineHighlighted:"#b58900",text:"#dbd0e4"},visual:{base:"#315272",baseHighlighted:"#4d6784",header:"#173E5D",headerHighlighted:"#315272",outline:"#173E5D",outlineHighlighted:"#b58900",text:"#cfd5de"},data:{base:"#465524",baseHighlighted:"#5b6a37",header:"#314110",headerHighlighted:"#465524",outline:"#314110",outlineHighlighted:"#b58900",text:"#d2d6c5"},javascript:{base:"#7E3660",baseHighlighted:"#944e74",header:"#67214B",headerHighlighted:"#7e3660",outline:"#67214B",outlineHighlighted:"#d57bab",text:"#e4cfd9"},default:{base:"#4C4F59",baseHighlighted:"#62656e",header:"#373B45",headerHighlighted:"#4c4f59",outline:"#373B45",outlineHighlighted:"#b58900",text:"#d3d4d6"}},connections:{signal:{normal:"#006f82",highlighted:"#7ec2cf",pulsing:"#ffffff"},default:{normal:"#875d00",highlighted:"#e5ae32",pulsing:"#ffffff"}}},nodetypes:[{name:"Component Children",shortDesc:"This node is a placeholder for where children of this component will be inserted.",docs:"https://docs.noodl.net/nodes/component-utilities/component-children",color:"component",allowAsChild:!0,category:"Visual",haveComponentChildren:["Visual"]}]},n=Object.keys(e._constructors);n.forEach(function(s){var a=e._constructors[s].metadata,u={name:s,searchTags:a.searchTags};t.nodetypes.push(u),a.version&&(u.version=a.version),a.displayNodeName&&(u.displayNodeName=a.displayNodeName),a.nodeDoubleClickAction&&(u.nodeDoubleClickAction=a.nodeDoubleClickAction),a.shortDesc&&(u.shortDesc=a.shortDesc),a.module&&(u.module=a.module),a.deprecated&&(u.deprecated=!0),a.haveComponentPorts&&(u.haveComponentPorts=!0),a.category==="Visual"&&(u.allowAsChild=!0,u.allowAsExportRoot=!0,u.color="visual"),a.allowAsExportRoot!==void 0&&(u.allowAsExportRoot=a.allowAsExportRoot),a.allowChildren&&(u.allowChildrenWithCategory=["Visual"],u.color="visual"),a.allowChildrenWithCategory&&(u.allowChildrenWithCategory=a.allowChildrenWithCategory),a.singleton&&(u.singleton=!0),a.allowAsChild&&(u.allowAsChild=!0),a.docs&&(u.docs=a.docs),a.shortDocs?u.shortDocs=a.shortDocs:a.docs&&a.docs.indexOf("https://docs.noodl.net")===0&&(u.shortDocs=a.docs.replace("/#","")+"-short.md"),u.category=a.category,a.panels&&(u.panels=a.panels),a.usePortAsLabel&&(u.usePortAsLabel=a.usePortAsLabel,u.portLabelTruncationMode=a.portLabelTruncationMode),a.color&&(u.color=a.color),a.dynamicports&&(u.dynamicports=formatDynamicPorts(a)),a.exportDynamicPorts&&(u.exportDynamicPorts=a.exportDynamicPorts),a.visualStates&&(u.visualStates=a.visualStates),a.useVariants&&(u.useVariants=a.useVariants),a.connectionPanel&&(u.connectionPanel=a.connectionPanel),u.ports=[];var l=u.dynamicports||[],d={},p={};l.filter(m=>m.channelPort!==void 0).forEach(m=>{p[m.channelPort.plug+"/"+m.channelPort.name]=!0}),l.length&&(u.dynamicports=l),Object.keys(a.inputs).forEach(function(m){if(!(d.hasOwnProperty("input/"+m)||p.hasOwnProperty("input/"+m))){var y=a.inputs[m];y.exportToEditor!==!1&&u.ports.push(formatPort(m,y,"input"))}});function f(m,y){var v={name:m,type:y.type,plug:"output"};y.group&&(v.group=y.group),y.displayName&&(v.displayName=y.displayName),y.editorName&&(v.editorName=y.editorName),y.hasOwnProperty("index")&&(v.index=y.index),u.ports.push(v)}Object.keys(a.outputs).forEach(function(m){if(!(d.hasOwnProperty("output/"+m)||p.hasOwnProperty("output/"+m))){var y=a.outputs[m];f(m,y)}})});const o=[{name:"UI Elements",description:"Buttons, inputs, containers, media",type:"visual",subCategories:[{name:"Basic Elements",items:["Group","net.noodl.visual.columns","Text","Image","Video","Circle","net.noodl.visual.icon"]},{name:"UI Controls",items:["net.noodl.controls.button","net.noodl.controls.checkbox","net.noodl.controls.options","net.noodl.controls.radiobutton","Radio Button Group","net.noodl.controls.range","net.noodl.controls.textinput"]}]},{name:"Navigation & Popups",description:"Page routing, navigation, popups",type:"logic",subCategories:[{name:"Navigation",items:["Router","RouterNavigate","PageInputs","net.noodl.externallink","PageStackNavigateToPath"]},{name:"Component Stack",items:["Page Stack","PageStackNavigate","PageStackNavigateBack"]},{name:"Popups",items:["NavigationShowPopup","NavigationClosePopup"]}]},{name:"Logic & Utilities",description:"Logic, events, string manipulation",type:"logic",subCategories:[{name:"General Utils",items:["States","Value Changed","Timer","Color Blend","Number Remapper","Counter","Drag","net.noodl.animatetovalue"]},{name:"Logic",items:["Boolean To String","Switch","And","Or","Condition","Inverter"]},{name:"Events",items:["Event Sender","Event Receiver"]},{name:"String Manipulation",items:["Substring","String Mapper","String Format","Date To String","Unique Id"]},{name:"System",items:["Screen Resolution","Open File Picker"]},{name:"Variables",items:["String","Boolean","Color","Number"]}]},{name:"Component Utilities",description:"Component inputs, outputs & object",type:"component",subCategories:[{name:"",items:["Component Inputs","Component Outputs","Component Children","net.noodl.ComponentObject","net.noodl.ParentComponentObject","net.noodl.SetComponentObjectProperties","net.noodl.SetParentComponentObjectProperties"]}]},{name:"Read & Write Data",description:"Arrays, objects, cloud data",type:"data",subCategories:[{name:"",items:["RunTasks","For Each","For Each Actions","Model2","SetModelProperties","NewModel","Set Variable","Variable2"]},{name:"Array",items:["Collection2","CollectionNew","CollectionRemove","CollectionClear","CollectionInsert","Filter Collection","Map Collection","Static Data"]},{name:"Cloud Data",items:["DbModel2","NewDbModelProperties","FilterDBModels","SetDbModelProperties","DbCollection2","DeleteDbModelProperties","AddDbModelRelation","RemoveDbModelRelation","Cloud File","Upload File","CloudFunction2","DbConfig"]},{name:"User",items:["net.noodl.user.LogIn","net.noodl.user.LogOut","net.noodl.user.SignUp","net.noodl.user.User","net.noodl.user.SetUserProperties","net.noodl.user.VerifyEmail","net.noodl.user.SendEmailVerification","net.noodl.user.ResetPassword","net.noodl.user.RequestPasswordReset"]},{name:"External Data",items:["REST2"]}]},{name:"Custom Code",description:"Custom JavaScript and CSS",type:"javascript",subCategories:[{name:"",items:["Expression","JavaScriptFunction","Javascript2","CSS Definition"]}]},{name:"Cloud Functions",description:"Nodes to be used in cloud functions",type:"data",subCategories:[{name:"",items:["noodl.cloud.request","noodl.cloud.response"]},{name:"Cloud Data",items:["noodl.cloud.aggregate"]}]}];t.nodeIndex={coreNodes:o};const r=[];return n.forEach(s=>{e._constructors[s].metadata.module&&r.push(s)}),r.length&&(t.nodeIndex.moduleNodes=[{name:"",items:r}]),t}function addModuleSettings(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.settings&&o.settings.forEach(function(r){e.ports.push(r)})}}function generateProjectSettings(e,t){const n={dynamicports:[],ports:[]};return addModuleSettings(n,t),n}function NodeModel(e,t){EventSender.call(this),this.id=e,this.type=t,this.inputs=[],this.outputs=[],this.children=[],this.parameters={},this.inputPorts={},this.outputPorts={}}NodeModel.prototype=Object.create(EventSender.prototype),NodeModel.prototype.setParameter=function(e,t,n){n?(this.stateParameters||(this.stateParameters={}),this.stateParameters[n]||(this.stateParameters[n]={}),t===void 0?delete this.stateParameters[n][e]:this.stateParameters[n][e]=t):t===void 0?delete this.parameters[e]:this.parameters[e]=t,this.emit("parameterUpdated",{name:e,value:t,state:n})},NodeModel.prototype.setParameters=function(e){Object.keys(e).forEach(t=>{this.setParameter(t,e[t])})},NodeModel.prototype.setStateParameters=function(e){this.stateParameters=e},NodeModel.prototype.setStateTransitions=function(e){this.stateTransitions=e},NodeModel.prototype.setStateTransitionParamter=function(e,t,n){this.stateTransitions||(this.stateTransitions={}),t?this.stateTransitions[n][e]=t:delete this.stateTransitions[n][e]},NodeModel.prototype.setDefaultStateTransition=function(e,t){this.defaultStateTransitions||(this.defaultStateTransitions={}),this.defaultStateTransitions[t]=e},NodeModel.prototype.addInputPort=function(e){this.inputPorts[e.name]=e,this.emit("inputPortAdded",e)},NodeModel.prototype.getInputPort=function(e){return this.inputPorts[e]},NodeModel.prototype.getInputPorts=function(){return this.inputPorts},NodeModel.prototype.removeInputPortWithName=function(e){if(this.inputPorts.hasOwnProperty(e)){var t=this.inputPorts[e];delete this.inputPorts[e],this.emit("inputPortRemoved",t)}},NodeModel.prototype.updateInputPortTypes=function(e){var t=!1;for(var n in e)this.inputPorts[n]!==void 0&&(this.inputPorts[n].type=e[n].type,t=!0);t&&this.emit("inputPortTypesUpdated")},NodeModel.prototype.addOutputPort=function(e){this.outputPorts[e.name]=e,this.emit("outputPortAdded",e)},NodeModel.prototype.getOutputPort=function(e){return this.outputPorts[e]},NodeModel.prototype.getOutputPorts=function(){return this.outputPorts},NodeModel.prototype.removeOutputPortWithName=function(e){if(this.outputPorts.hasOwnProperty(e)){var t=this.outputPorts[e];delete this.outputPorts[e],this.emit("outputPortRemoved",t)}},NodeModel.prototype.updateOutputPortTypes=function(e){var t=!1;for(var n in e)this.outputPorts[n]!==void 0&&(this.outputPorts[n].type=e[n].type,t=!0);t&&this.emit("outputPortTypesUpdated")},NodeModel.prototype.addChild=function(e,t){e.parent=this,t===void 0?this.children.push(e):this.children.splice(t,0,e),this.emit("childAdded",e)},NodeModel.prototype.removeChild=function(e){e.parent=void 0;var t=this.children.indexOf(e);this.children.splice(t,1),this.emit("childRemoved",e)},NodeModel.prototype.reset=function(){this.removeAllListeners()},NodeModel.prototype.setVariant=function(e){this.variant=e,this.emit("variantUpdated",e)},NodeModel.createFromExportData=function(e){var t=new NodeModel(e.id,e.type);if(e.parameters&&t.setParameters(e.parameters),e.stateParameters&&t.setStateParameters(e.stateParameters),e.stateTransitions&&t.setStateTransitions(e.stateTransitions),e.defaultStateTransitions)for(const n in e.defaultStateTransitions)t.setDefaultStateTransition(e.defaultStateTransitions[n],n);return e.ports&&e.ports.forEach(function(n){n.plug==="outputs"&&(n.plug="output"),(n.plug==="input"||n.plug==="input/output")&&t.addInputPort(n),(n.plug==="output"||n.plug==="input/output")&&t.addOutputPort(n)}),e.variant&&t.setVariant(e.variant),t};function ComponentModel(e){EventSender.call(this),this.name=e,this.nodes=[],this.connections=[],this.roots=[],this.inputPorts={},this.outputPorts={},this.metadata={}}ComponentModel.prototype=Object.create(EventSender.prototype),ComponentModel.prototype.addNode=async function(e){e.component=this,this.nodes[e.id]=e,await this.emit("nodeAdded",e)},ComponentModel.prototype.hasNodeWithId=function(e){return this.getNodeWithId(e)!==void 0},ComponentModel.prototype.getNodeWithId=function(e){return this.nodes[e]},ComponentModel.prototype.getAllNodes=function(){return Object.values(this.nodes)},ComponentModel.prototype.getNodesWithType=function(e){var t=[],n=this;return Object.keys(this.nodes).forEach(function(o){var r=n.nodes[o];r.type===e&&t.push(r)}),t},ComponentModel.prototype.addConnection=function(e){if(this.connections.push(e),this.emit("connectionAdded",e),e.targetId){const t=this.getNodeWithId(e.targetId);t&&t.emit("inputConnectionAdded",e)}},ComponentModel.prototype.removeConnection=function(e){const t=this.connections.findIndex(n=>n.sourceId===e.sourceId&&n.sourcePort===e.sourcePort&&n.targetId===e.targetId&&n.targetPort===e.targetPort);if(t===-1){console.log("Connection doesn't exist",e);return}if(this.connections.splice(t,1),this.emit("connectionRemoved",e),e.targetId){const n=this.getNodeWithId(e.targetId);n&&n.emit("inputConnectionRemoved",e)}},ComponentModel.prototype.getConnectionsFromPort=function(e,t){return this.connections.filter(function(n){return n.sourceId===e&&n.sourcePort===t})},ComponentModel.prototype.getConnectionsToPort=function(e,t){return this.connections.filter(function(n){return n.targetId===e&&n.targetPort===t})},ComponentModel.prototype.getConnectionsFrom=function(e){return this.connections.filter(function(t){return t.sourceId===e})},ComponentModel.prototype.getConnectionsTo=function(e){return this.connections.filter(function(t){return t.targetId===e})},ComponentModel.prototype.addRootId=function(e){this.roots.indexOf(e)===-1&&(this.roots.push(e),this.emit("rootAdded",e))},ComponentModel.prototype.removeRootId=function(e){const t=this.roots.indexOf(e);t!==-1&&(this.roots.splice(t,1),this.emit("rootRemoved",e))},ComponentModel.prototype.getRoots=function(){return this.roots},ComponentModel.prototype.removeNodeWithId=async function(e){const t=this.getNodeWithId(e);if(!t)return console.warn("ERROR: Attempted to remove non-existing node with ID:",e),!1;for(;t.children.length>0;){const o=t.children[0];await this.removeNodeWithId(o.id)||t.children.shift()}const n=this.getConnectionsTo(e).concat(this.getConnectionsFrom(e));for(let o=0;o<n.length;o++)this.removeConnection(n[o]);return this.setNodeParent(t,null),this.roots.indexOf(t.id)!==-1&&this.removeRootId(t.id),await this.emit("nodeRemoved",t),t.removeAllListeners(),delete this.nodes[e],await this.emit("nodeWasRemoved",t),!0},ComponentModel.prototype.getAllConnections=function(){return this.connections},ComponentModel.prototype.getInputPorts=function(){return this.inputPorts},ComponentModel.prototype.getOutputPorts=function(){return this.outputPorts},ComponentModel.prototype.addInputPort=function(e){this.inputPorts[e.name]=e,this.emit("inputPortAdded",e)},ComponentModel.prototype.addOutputPort=function(e){this.outputPorts[e.name]=e,this.emit("outputPortAdded",e)},ComponentModel.prototype.removeOutputPortWithName=function(e){if(this.outputPorts.hasOwnProperty(e)){var t=this.outputPorts[e];delete this.outputPorts[e],this.emit("outputPortRemoved",t)}},ComponentModel.prototype.removeInputPortWithName=function(e){if(this.inputPorts.hasOwnProperty(e)){var t=this.inputPorts[e];delete this.inputPorts[e],this.emit("inputPortRemoved",t)}},ComponentModel.prototype.updateInputPortTypes=function(e){var t=!1;for(var n in e)this.inputPorts[n]!==void 0&&(this.inputPorts[n].type=e[n].type,t=!0);t&&this.emit("inputPortTypesUpdated")},ComponentModel.prototype.updateOutputPortTypes=function(e){var t=!1;for(var n in e)this.outputPorts[n]!==void 0&&(this.outputPorts[n].type=e[n].type,t=!0);t&&this.emit("outputPortTypesUpdated")},ComponentModel.prototype.renameInputPortOnNodeWithId=function(e,t,n){var o=this.getConnectionsToPort(e,t);o.forEach(this.removeConnection.bind(this));var r=this.getNodeWithId(e),s={...r.getInputPort(t)};s&&(r.removeInputPortWithName(t),s.name=n,r.addInputPort(s)),o.forEach(function(a){a.targetPort=n}),o.forEach(this.addConnection.bind(this))},ComponentModel.prototype.renameOutputPortOnNodeWithId=function(e,t,n){var o=this.getConnectionsFromPort(e,t);o.forEach(this.removeConnection.bind(this));var r=this.getNodeWithId(e),s={...r.getOutputPort(t)};r.removeOutputPortWithName(t),s.name=n,r.addOutputPort(s),o.forEach(function(a){a.sourcePort=n}),o.forEach(this.addConnection.bind(this))},ComponentModel.prototype.setNodeParent=function(e,t,n){this.roots.indexOf(e.id)!==-1&&this.removeRootId(e.id),e.parent&&(this.emit("nodeParentWillBeRemoved",e),e.parent.removeChild(e)),e.emit("parentUpdated",t),t&&(t.addChild(e,n),this.emit("nodeParentUpdated",e))},ComponentModel.prototype.importEditorNodeData=async function(e,t,n){var o=NodeModel.createFromExportData(e);if(await this.addNode(o),t&&this.setNodeParent(o,this.getNodeWithId(t),n),e.children)for(let r=0;r<e.children.length;r++){const s=e.children[r];await this.importEditorNodeData(s,o.id,r)}},ComponentModel.prototype.reset=async function(){for(;this.roots.length;)await this.removeNodeWithId(this.roots[0]);for(const e of this.nodes)this.hasNodeWithId(e)&&await this.removeNodeWithId(e);if(this.nodes.length>0)throw new Error("Not all nodes were removed during a reset");if(this.connections.length>0)throw new Error("Not all connections were removed during a reset")},ComponentModel.prototype.rename=function(e){var t=this.name;this.name=e,this.emit("renamed",{oldName:t,newName:e})},ComponentModel.prototype.setMetadata=function(e,t){this.metadata[e]=t},ComponentModel.prototype.getMetadata=function(e){return e?this.metadata[e]:this.metadata},ComponentModel.createFromExportData=async function(e){var t=new ComponentModel(e.name);if(e.metadata)for(const n in e.metadata)t.setMetadata(n,e.metadata[n]);if(e.ports&&e.ports.forEach(function(n){(n.plug==="input"||n.plug==="input/output")&&t.addInputPort(n),(n.plug==="output"||n.plug==="input/output")&&t.addOutputPort(n)}),e.nodes)for(const n of e.nodes)await t.importEditorNodeData(n);return e.connections&&e.connections.forEach(n=>t.addConnection(n)),e.roots&&e.roots.forEach(n=>t.addRootId(n)),t};function GraphModel(){EventSender.call(this),this.components={},this.settings={},this.metadata={}}GraphModel.prototype=Object.create(EventSender.prototype),GraphModel.prototype.importComponentFromEditorData=async function(e){var t=await ComponentModel.createFromExportData(e);this.addComponent(t)},GraphModel.prototype.getBundleContainingComponent=function(e){return this.componentToBundleMap.get(e)},GraphModel.prototype.getBundlesContainingSheet=function(e){const t=new Set;for(const n of this.componentToBundleMap.keys()){const o=n.indexOf("/#")!==0;(o&&e==="Default"||!o&&n.indexOf("/#"+e)===0)&&t.add(this.componentToBundleMap.get(n))}return Array.from(t)},GraphModel.prototype.getBundleDependencies=function(e){const t=new Set,n=o=>{const r=this.componentIndex[o];for(const s of r.dependencies)t.has(s)||(t.add(s),n(s))};return n(e),Array.from(t)},GraphModel.prototype.importEditorData=async function(e){this.componentIndex=e.componentIndex,this.routerIndex=e.routerIndex,this.componentToBundleMap=new Map;for(const t in e.componentIndex){const n=e.componentIndex[t];for(const o of n.components)this.componentToBundleMap.set(o,t)}this.variants=e.variants||[],e.settings&&this.setSettings(e.settings),e.metadata&&this.setAllMetaData(e.metadata);for(const t of e.components)await this.importComponentFromEditorData(t);this.setRootComponentName(e.rootComponent)},GraphModel.prototype.setRootComponentName=function(e){this.rootComponent=e,this.emit("rootComponentNameUpdated",e)},GraphModel.prototype.getNodesWithType=function(e){for(var t=[],n=Object.keys(this.components),o=0;o<n.length;o++){var r=this.components[n[o]];t=t.concat(r.getNodesWithType(e))}return t},GraphModel.prototype.getComponentWithName=function(e){return this.components[e]},GraphModel.prototype.hasComponentWithName=function(e){return!!this.components[e]},GraphModel.prototype.getAllComponents=function(){return Object.keys(this.components).map(e=>this.components[e])},GraphModel.prototype.getAllNodes=function(){for(var e=[],t=Object.keys(this.components),n=0;n<t.length;n++){var o=this.components[t[n]];e=e.concat(o.getAllNodes())}return e},GraphModel.prototype.addComponent=function(e){this.components[e.name]=e,this.getNodesWithType(e.name).forEach(this._addComponentPorts.bind(this)),e.getAllNodes().forEach(this._onNodeAdded.bind(this)),e.on("nodeAdded",this._onNodeAdded.bind(this),this),e.on("nodeRemoved",this._onNodeRemoved.bind(this),this),e.on("nodeWasRemoved",this._onNodeWasRemoved.bind(this),this),this.emit("componentAdded",e)},GraphModel.prototype.removeComponentWithName=async function(e){if(this.components.hasOwnProperty(e)===!1){console.error("GraphModel: Component with name "+e+" not in graph");return}var t=this.components[e];await t.reset(),t.removeAllListeners(),delete this.components[t.name],this.emit("componentRemoved",t)},GraphModel.prototype.renameComponent=function(e,t){if(this.components.hasOwnProperty(e)===!1){console.error("GraphModel: Component with name "+e+" not in graph");return}this.getNodesWithType(e).forEach(function(o){o.type=t});var n=this.components[e];n.rename(t),delete this.components[e],this.components[t]=n,this.emit("componentRenamed",n)},GraphModel.prototype._addComponentPorts=function(e){if(this.components.hasOwnProperty(e.type)){var t=this.components[e.type];const n=t.getInputPorts(),o=t.getOutputPorts();Object.keys(n).forEach(r=>{e.addInputPort(n[r])}),Object.keys(o).forEach(r=>{e.addOutputPort(o[r])})}},GraphModel.prototype._onNodeAdded=function(e){this._addComponentPorts(e),this.emit("nodeAdded",e),this.emit("nodeAdded."+e.type,e)},GraphModel.prototype._onNodeRemoved=function(e){this.emit("nodeRemoved",e),this.emit("nodeRemoved."+e.type,e)},GraphModel.prototype._onNodeWasRemoved=function(e){this.emit("nodeWasRemoved",e),this.emit("nodeWasRemoved."+e.type,e)},GraphModel.prototype.reset=async function(){for(const e of Object.keys(this.components))await this.removeComponentWithName(e);this.setSettings({})},GraphModel.prototype.isEmpty=function(){return Object.keys(this.components).length===0},GraphModel.prototype.setSettings=function(e){this.settings=e,this.emit("projectSettingsChanged",e)},GraphModel.prototype.getSettings=function(){return this.settings},GraphModel.prototype.setAllMetaData=function(e){for(const t in e)this.setMetaData(t,e[t])},GraphModel.prototype.setMetaData=function(e,t){this.metadata[e]&&JSON.stringify(this.metadata[e])===JSON.stringify(t)||(this.metadata[e]=t,this.emit("metadataChanged",{key:e,data:t}),this.emit("metadataChanged."+e,t))},GraphModel.prototype.getMetaData=function(e){return e?this.metadata[e]:this.metadata},GraphModel.prototype.getVariants=function(){return this.variants||[]},GraphModel.prototype.getVariant=function(e,t){return this.variants.find(n=>n.name===t&&n.typename===e)},GraphModel.prototype.updateVariant=function(e){const t=this.variants.findIndex(n=>n.name===e.name&&n.typename===e.typename);t!==-1&&this.variants.splice(t,1),this.variants.push(e),this.emit("variantUpdated",e)},GraphModel.prototype.updateVariantParameter=function(e,t,n,o,r){const s=this.getVariant(t,e);if(!s){console.log("updateVariantParameter: can't find variant",e,t);return}r?(s.stateParameters.hasOwnProperty(r)||(s.stateParameters[r]={}),o===void 0?delete s.stateParameters[r][n]:s.stateParameters[r][n]=o):o===void 0?delete s.parameters[n]:s.parameters[n]=o,this.emit("variantUpdated",s)},GraphModel.prototype.updateVariantDefaultStateTransition=function(e,t,n,o){const r=this.getVariant(t,e);r&&(r.defaultStateTransitions[o]=n,this.emit("variantUpdated",r))},GraphModel.prototype.updateVariantStateTransition=function(e){const{variantTypeName:t,variantName:n,state:o,parameterName:r,curve:s}=e,a=this.getVariant(t,n);a&&(a.stateTransitions[o]||(a.stateTransitions[o]={}),a.stateTransitions[o][r]=s)},GraphModel.prototype.deleteVariant=function(e,t){const n=this.variants.findIndex(o=>o.name===t&&o.typename===e);n!==-1&&this.variants.splice(n,1)};function createSetter(e){var t=!1;return function(n){n=!!n,n&&t===!1&&e.valueChangedToTrue.call(this),t=n}}const EdgeTriggeredInput=Object.freeze(Object.defineProperty({__proto__:null,createSetter},Symbol.toStringTag,{value:"Module"}));function createNodeConstructor(e){const t=class extends Node{constructor(n,o){super(n,o)}getInspectInfo(){return e.getInspectInfo?.call(this)??void 0}nodeScopeDidInitialize(){return e.nodeScopeDidInitialize?.call(this)??void 0}};return e.prototypeExtensions&&Object.defineProperties(t.prototype,e.prototypeExtensions),Object.defineProperty(t.prototype,"name",{value:e.name}),t}function registerInput(e,t,n,o){if(e.hasOwnProperty(n))throw new Error("Input property "+n+" already registered");!o.set&&!o.valueChangedToTrue&&(o.set=()=>{}),o.set&&(e[n]={set:o.set},["color","textStyle","array"].forEach(s=>{o.type&&(o.type===s||o.type.name===s)&&(e[n].type=s)})),o.setUnitType&&(e[n].setUnitType=o.setUnitType),t.inputs[n]={displayName:o.displayName,editorName:o.editorName,group:o.group,type:o.type,default:o.default,index:o.index,exportToEditor:o.hasOwnProperty("exportToEditor")?o.exportToEditor:!0,inputPriority:o.inputPriority||0,tooltip:o.tooltip,tab:o.tab,popout:o.popout,allowVisualStates:o.allowVisualStates,nodeDoubleClickAction:o.nodeDoubleClickAction},o.valueChangedToTrue&&(t.inputs[n].type={name:"signal",allowConnectionsOnly:!0})}function registerInputs(e,t,n){Object.keys(n).forEach(function(o){registerInput(e,t,o,n[o])})}function registerNumberedInputs(e,t){for(const n of Object.keys(t))registerNumberedInput(e,n,t[n])}function registerNumberedInput(e,t,n){const o=e.registerInputIfNeeded;e.registerInputIfNeeded=function(r){if(o&&o.call(e,r),e.hasInput(r)||!r.startsWith(t))return;const s=Number(r.slice(t.length+1));e.registerInput(r,{type:n.type,set:n.createSetter.call(e,s)})}}function registerOutputsMetadata(e,t){Object.keys(t).forEach(function(n){var o=t[n];e.outputs[n]={displayName:o.displayName,editorName:o.editorName,group:o.group,type:o.type,index:o.index,exportToEditor:o.hasOwnProperty("exportToEditor")?o.exportToEditor:!0}})}function initializeDefaultValues(e,t){Object.keys(t).forEach(n=>{const o=t[n].default;o!==void 0&&(t[n].type.defaultUnit?e[n]={unit:t[n].type.defaultUnit,value:o}:e[n]=o)})}function defineNode(e){if(!e.category)throw new Error("Node must have a category");if(!e.name)throw new Error("Node must have a name");const t={inputs:{},outputs:{},category:e.category,dynamicports:e.dynamicports,exportDynamicPorts:e.exportDynamicPorts,useVariants:e.useVariants,allowChildren:e.allowChildren,allowChildrenWithCategory:e.allowChildrenWithCategory,singleton:e.singleton,connectionPanel:e.connectionPanel,allowAsChild:e.allowAsChild,visualStates:e.visualStates,panels:e.panels,color:e.color,usePortAsLabel:e.usePortAsLabel,portLabelTruncationMode:e.portLabelTruncationMode,name:e.name,displayNodeName:e.displayNodeName||e.displayName,deprecated:e.deprecated,haveComponentPorts:e.haveComponentPorts,version:e.version,module:e.module,docs:e.docs,allowAsExportRoot:e.allowAsExportRoot,nodeDoubleClickAction:e.nodeDoubleClickAction,searchTags:e.searchTags};e._internal=e._internal||{},e.prototypeExtensions=e.methods||e.prototypeExtensions||{},e.inputs=e.inputs||{},e.outputs=e.outputs||{},e.initialize=e.initialize||function(){};let n={};registerInputs(n,t,e.inputs),registerOutputsMetadata(t,e.outputs),Object.keys(e.prototypeExtensions).forEach(function(s){e.prototypeExtensions[s].value||(e.prototypeExtensions[s]={value:e.prototypeExtensions[s]})});const o=createNodeConstructor({name:e.name,getInspectInfo:e.getInspectInfo,nodeScopeDidInitialize:e.nodeScopeDidInitialize,prototypeExtensions:e.prototypeExtensions}),r=function(s,a,u){const l=new o(s,a);return l._inputs=Object.create(n),Object.keys(e.inputs).forEach(function(d){var p=e.inputs[d];p.valueChangedToTrue&&(l._inputs[d]={set:createSetter({valueChangedToTrue:p.valueChangedToTrue})})}),Object.keys(e.outputs).forEach(function(d){var p=e.outputs[d];p.type==="signal"?l.registerOutput(d,{getter(){}}):l.registerOutput(d,p)}),e.numberedInputs&®isterNumberedInputs(l,e.numberedInputs),l.nodeScope=u,initializeDefaultValues(l._inputValues,t.inputs),e.initialize.call(l),l};return r.metadata=t,e.numberedInputs&®isterSetupFunctionForNumberedInputs(r,e.name,e.numberedInputs),r}function registerSetupFunctionForNumberedInputs(e,t,n){const o=Object.keys(n);o.length&&(e.setupNumberedInputDynamicPorts=function(r,s){const a=r.editorConnection;if(!a||!a.isRunningLocally())return;function u(d,p,f){const m=d.component.getConnectionsTo(d.id).map(N=>N.targetPort),v=Object.keys(d.parameters).concat(m).filter(N=>N.startsWith(p+" ")),S=(v.length?1+Math.max(...v.map(N=>Number(N.slice(p.length+1)))):0)+1,C=[];for(let N=0;N<S;N++){const T={name:p+" "+N,displayName:(f.displayPrefix||p)+" "+N,type:f.type,plug:"input",group:f.group};f.hasOwnProperty("index")&&(T.index=f.index+N),C.push(T)}return C}function l(d){const p=o.map(f=>u(d,f,n[f])).flat();a.sendDynamicPorts(d.id,p)}s.on("nodeAdded."+t,d=>{l(d),d.on("parameterUpdated",()=>{l(d)}),d.on("inputConnectionAdded",()=>{l(d)}),d.on("inputConnectionRemoved",()=>{l(d)})})})}function extend(e,t){for(var n in t)if(n==="initialize"&&e.initialize){var o=e.initialize;e.initialize=function(){o.call(this),t.initialize.call(this)}}else t[n]&&t[n].constructor===Object?e[n]=extend(e[n]||{},t[n]):t[n]&&t[n].constructor===Array&&e[n]&&e[n].constructor==Array?e[n]=e[n].concat(t[n]):e[n]=t[n];return e}function difference$1(e,t){const n=new Set(t);return e.filter(o=>!n.has(o))}async function handleEvent(e,t,n){function o(u,l){var d={},p={};l.forEach(function(C){C&&C.plug==="outputs"&&(C.plug="output"),(C.plug==="input"||C.plug==="input/output")&&(d[C.name]=C),(C.plug==="output"||C.plug==="input/output")&&(p[C.name]=C)});var f=Object.keys(u.getInputPorts()),m=difference$1(f,Object.keys(d)),y=difference$1(Object.keys(d),f);u.updateInputPortTypes(d),m.forEach(u.removeInputPortWithName.bind(u)),y.forEach(function(C){u.addInputPort(d[C]),u.parameters&&u.parameters.hasOwnProperty(C)&&r(e.rootComponent.nodeScope,u,C,u.parameters[C])}),u.updateOutputPortTypes(p);var v=Object.keys(u.getOutputPorts()),P=difference$1(v,Object.keys(p)),S=difference$1(Object.keys(p),v);P.forEach(u.removeOutputPortWithName.bind(u)),S.forEach(function(C){u.addOutputPort(p[C])})}function r(u,l,d,p){var f=u.getNodesWithIdRecursive(l.id);f.forEach(function(m){m.queueInput(d,p)})}var s;if(!(n.componentName&&(s=t.getComponentWithName(n.componentName),!s))){n.port&&n.port.plug==="outputs"&&(n.port.plug="output");var a={nodeAdded(u){s.importEditorNodeData(u.model,u.parentId,u.childIndex)},nodeRemoved:async function(u){s.hasNodeWithId(u.model.id)&&await s.removeNodeWithId(u.model.id)},connectionAdded(u){s.addConnection(u.model)},connectionRemoved(u){s.removeConnection(u.model);var l=s.getNodeWithId(u.model.targetId);if(s.getConnectionsToPort(l.id,u.model.targetId).length===0){var d=l.parameters[u.model.targetPort];d===void 0&&(d=e.getDefaultValueForInput(l.type,u.model.targetPort)),r(e.rootComponent.nodeScope,l,u.model.targetPort,d)}},parameterChanged(u){const l=s.getNodeWithId(u.nodeId);if(l===void 0){console.log("parameterChanged: Unknown node id",u);return}if(u.parameters){const d=new Set(Object.keys(u.parameters).concat(Object.keys(u.oldParameters)));for(const p of d)l.setParameter(p,u.parameters[p])}u.parameterName&&l.setParameter(u.parameterName,u.parameterValue,u.state)},nodeAttached(u){s.setNodeParent(s.getNodeWithId(u.nodeId),s.getNodeWithId(u.parentId),u.childIndex)},nodeDetached(u){s.setNodeParent(s.getNodeWithId(u.nodeId),null),s.addRootId(u.nodeId)},componentAdded(u){t.importComponentFromEditorData(u.model)},componentRemoved:async function(u){await t.removeComponentWithName(u.componentName)},rootAdded(u){s.addRootId(u.nodeId)},portAdded(u){var l=s.getNodeWithId(u.nodeId);(u.port.plug==="input"||u.port.plug==="input/output")&&(l.addInputPort(u.port),l.parameters.hasOwnProperty(u.port)&&r(e.rootComponent.nodeScope,l,u.port,l.parameters[u.port])),(u.port.plug==="output"||u.port.plug==="input/output")&&l.addOutputPort(u.port)},portRemoved(u){var l=s.getNodeWithId(u.nodeId);(u.port.plug==="input"||u.port.plug==="input/output")&&l.removeInputPortWithName(u.port.name),(u.port.plug==="output"||u.port.plug==="input/output")&&l.removeOutputPortWithName(u.port.name)},nodePortRenamed(u){(u.port.plug==="input"||u.port.plug==="input/output")&&s.renameInputPortOnNodeWithId(u.nodeId,u.oldName,u.port.name),(u.port.plug==="output"||u.port.plug==="input/output")&&s.renameOutputPortOnNodeWithId(u.nodeId,u.oldName,u.port.name);var l=s.getNodeWithId(u.nodeId);l.type==="Component Inputs"?(s.addInputPort(u.port),t.getNodesWithType(s.name).forEach(function(d){d.component.renameInputPortOnNodeWithId(d.id,u.oldName,u.port.name)}),s.removeInputPortWithName(u.oldName)):l.type==="Component Outputs"&&(s.addOutputPort(u.port),t.getNodesWithType(s.name).forEach(function(d){d.component.renameOutputPortOnNodeWithId(d.id,u.oldName,u.port.name)}),s.removeOutputPortWithName(u.oldName))},componentPortsUpdated(u){o(s,u.ports)},instancePortsChanged(u){if(s.hasNodeWithId(u.nodeId)){var l=s.getNodeWithId(u.nodeId);o(l,u.ports)}},componentRenamed(u){t.renameComponent(u.oldName,u.newName)},settingsChanged(u){t.setSettings(u.settings)},metadataChanged(u){t.setMetaData(u.key,u.data)},componentMetadataChanged(u){const l=t.getComponentWithName(u.componentName);l&&l.setMetadata(u.key,u.data)},variantParametersChanged(u){if(u.variant)t.updateVariant(u.variant);else if(t.updateVariantParameter(u.variantName,u.variantTypeName,u.parameterName,u.parameterValue,u.state),u.parameterValue===void 0){const l=t.getVariant(u.variantTypeName,u.variantName);e.rootComponent.nodeScope.getAllNodesWithVariantRecursive(l).forEach(p=>{p.queueInput(u.parameterName,p.getParameter(u.parameterName))})}},variantDeleted(u){t.deleteVariant(u.variantTypeName,u.variantName)},variantChanged(u){const l=s.getNodeWithId(u.nodeId),d=t.getVariant(l.type,u.variantName);l.setVariant(d)},variantRenamed(u){const l=t.getVariant(u.variantTypeName,u.oldVariantName);l&&(l.name=l.variantName)},defaultStateTransitionChanged(u){s.getNodeWithId(u.nodeId).setDefaultStateTransition(u.curve,u.state)},stateTransitionsChanged(u){const l=s.getNodeWithId(u.nodeId);u.parameterName&&l.setStateTransitionParamter(u.parameterName,u.curve,u.state)},variantDefaultStateTransitionChanged(u){t.updateVariantDefaultStateTransition(u.variantName,u.variantTypeName,u.curve,u.state)},variantStateTransitionsChanged(u){t.updateVariantStateTransition(u)},routerIndexChanged(u){t.routerIndex=u.data}};a.hasOwnProperty(n.type)?(await a[n.type](n),e.scheduleUpdate()):console.log("Unknown event",n)}}async function asyncPool(e,t,n){const o=[],r=[];for(const s of t){const a=Promise.resolve().then(()=>n(s,t));if(o.push(a),e<=t.length){const u=a.then(()=>r.splice(r.indexOf(u),1));r.push(u),r.length>=e&&await Promise.race(r)}}return Promise.all(o)}const ComponentInputs={node:{name:"Component Inputs",shortDesc:"This node is used to define the inputs of a component.",docs:"https://docs.noodl.net/nodes/component-utilities/component-inputs",panels:[{name:"PortEditor",context:["select","connectFrom"],title:"Inputs",plug:"output",type:{name:"*"},canArrangeInGroups:!0},{name:"PropertyEditor",hidden:!0}],getInspectInfo(){return{type:"value",value:this.nodeScope.componentOwner._internal.inputValues}},color:"component",haveComponentPorts:!0,category:"Component Utilities",methods:{registerOutputIfNeeded(e){this.hasOutput(e)||this.registerOutput(e,{getter(){return this.nodeScope.componentOwner._internal.inputValues[e]}})},_updateDependencies(){this.nodeScope.componentOwner.update()}}}},ComponentOutputs={node:{category:"Component Utilities",name:"Component Outputs",shortDesc:"This node is used to define the outputs of a component.",docs:"https://docs.noodl.net/nodes/component-utilities/component-outputs",panels:[{name:"PortEditor",context:["select","connectTo"],title:"Outputs",plug:"input",type:{name:"*"},canArrangeInGroups:!0},{name:"PropertyEditor",hidden:!0}],color:"component",haveComponentPorts:!0,prototypeExtensions:{registerInputIfNeeded(e){this.hasInput(e)||this.registerInput(e,{set(t){this.nodeScope.componentOwner.setOutputFromComponentOutput(e,t)}})}}}};function Model(e,t){this.id=e,this.data=t}const models=Model._models={},proxies={},_modelProxyHandler={get(e,t,n){return typeof e[t]=="function"?e[t].bind(e):t in e?Reflect.get(e,t,n):e.get(t)},set(e,t,n){if(t==="_class")e._class=n;else{if(t==="id")return console.log(`Noodl.Object warning: id is readonly (Id is ${e.id}, trying to set to ${n})`),!0;e.set(t,n)}return!0},ownKeys(e){return Reflect.ownKeys(e.data)},getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e.data,t)}};Model.get=function(e){return e===void 0&&(e=Model.guid()),models[e]||(models[e]=new Model(e,{}),proxies[e]=new Proxy(models[e],_modelProxyHandler)),proxies[e]},Model.create=function(e){var t=e||{},n=Model.get(t.id);for(var o in t)o!=="id"&&n.set(o,t[o]);return n},Model.exists=function(e){return models[e]!==void 0},Model.instanceOf=function(e){return e instanceof Model||e.target instanceof Model};function _randomString(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";for(let o=0;o<e;++o)n+=t[Math.floor((1+Math.random())*65536)%t.length];return n}Model.guid=function e(){return _randomString(10)},Model.prototype.on=function(e,t){this.listeners||(this.listeners={}),this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},Model.prototype.off=function(e,t){if(this.listeners&&this.listeners[e]){var n=this.listeners[e].indexOf(t);n!==-1&&this.listeners[e].splice(n,1)}},Model.prototype.notify=function(e,t){if(this.listeners&&this.listeners[e])for(var n=this.listeners[e].slice(),o=0;o<n.length;o++)n[o](t)},Model.prototype.setAll=function(e){for(var t in e)if(t!=="id"&&this.data[t]!==e[t]){var n=this.data[t];this.data[t]=e[t],this.notify("change",{name:t,value:e[t],old:n})}},Model.prototype.fill=function(e=null){for(const t in this.data){if(t==="id")continue;const n=this.data[t];this.data[t]=e,this.notify("change",{name:t,value:this.data[t],old:n})}},Model.prototype.set=function(e,t,n){if(n&&n.resolve&&e.indexOf(".")!==-1){const s=e.split(".");let a=this;for(let u=0;u<s.length-1;u++){const l=a.get(s[u]);if(Model.instanceOf(l))a=l;else return}a.set(s[s.length-1],t);return}const o=n&&n.forceChange,r=this.data[e];this.data[e]=t,(o||r!==t)&&(!n||!n.silent)&&this.notify("change",{name:e,value:t,old:r})},Model.prototype.getId=function(){return this.id},Model.prototype.get=function(e,t){if(t&&t.resolve&&e.indexOf(".")!==-1){const n=e.split(".");let o=this;for(let r=0;r<n.length-1;r++){const s=o.get(n[r]);if(Model.instanceOf(s))o=s;else return}return o.get(n[n.length-1])}return this.data[e]},Model.prototype.toJSON=function(){return Object.assign({},this.data,{id:this.id})},Model.Scope=function(){this.models={},this.proxies={}},Model.Scope.prototype.get=function(e){return e===void 0&&(e=Model.guid()),this.models[e]||(this.models[e]=new Model(e,{}),this.proxies[e]=new Proxy(this.models[e],_modelProxyHandler)),this.proxies[e]},Model.Scope.prototype.create=function(e){var t=e||{},n=this.get(t.id);for(var o in t)o!=="id"&&n.set(o,t[o]);return n},Model.Scope.prototype.exists=function(e){return this.models[e]!==void 0},Model.Scope.prototype.instanceOf=function(e){return e instanceof Model||e.target instanceof Model},Model.Scope.prototype.guid=function e(){return _randomString(10)},Model.Scope.prototype.reset=function(){this.models={},this.proxies={},delete this._cloudStore};function sendSignalOnInput(e,t){e.queueInput(t,!0),e.queueInput(t,!1)}const RunTasksDefinition={name:"RunTasks",displayNodeName:"Run Tasks",docs:"https://docs.noodl.net/nodes/data/run-tasks",color:"data",category:"Data",initialize(){this._internal.queuedOperations=[],this._internal.state="idle",this._internal.maxRunningTasks=10,this._internal.activeTasks=new Map},inputs:{items:{group:"Data",displayName:"Items",type:"array",set(e){e&&e!==this._internal.items&&(this._internal.items=e)}},stopOnFailure:{group:"General",displayName:"Stop On Failure",type:"boolean",default:!1,set(e){this._internal.stopOnFailure=e}},maxRunningTasks:{group:"General",displayName:"Max Running Tasks",type:"number",default:10,set(e){this._internal.maxRunningTasks=e}},taskTemplate:{type:"component",displayName:"Template",group:"General",set(e){this._internal.template=e}},run:{group:"General",displayName:"Do",type:"signal",valueChangedToTrue(){this.scheduleRun()}},abort:{group:"General",displayName:"Abort",type:"signal",valueChangedToTrue(){this.scheduleAbort()}}},outputs:{success:{type:"signal",group:"Events",displayName:"Success"},failure:{type:"signal",group:"Events",displayName:"Failure"},done:{type:"signal",group:"Events",displayName:"Done"},aborted:{type:"signal",group:"Events",displayName:"Aborted"}},methods:{scheduleRun(){var e=this._internal;e.hasScheduledRun||(e.hasScheduledRun=!0,this.scheduleAfterInputsHaveUpdated(()=>{this._queueOperation(()=>{e.hasScheduledRun=!1,this.run()})}))},scheduleAbort(){var e=this._internal;e.hasScheduledAbort||(e.hasScheduledAbort=!0,this.scheduleAfterInputsHaveUpdated(()=>{this._queueOperation(()=>{e.hasScheduledAbort=!1,this.abort()})}))},async createTaskComponent(e){const t=this._internal,o=(this.nodeScope.modelScope||Model).create(e);var r=await this.nodeScope.createNode(t.template,guid(),{_forEachModel:o,_forEachNode:this});const s=r.isInputConnected.bind(r);r.isInputConnected=u=>u==="Do"?!0:s(u),r.hasInput("Id")&&r.setInputValue("Id",o.getId()),r.hasInput("id")&&r.setInputValue("id",o.getId());for(var a in r._inputs)o.data[a]!==void 0&&r.setInputValue(a,o.data[a]);return r._internal.creatorCallbacks={onOutputChanged:(u,l,d)=>{(d===!1||d===void 0)&&l===!0&&this.itemOutputSignalTriggered(u,o,r)}},r},async startTask(e){const t=this._internal;try{const n=await this.createTaskComponent(e);t.runningTasks++,sendSignalOnInput(n,"Do"),t.activeTasks.set(n.id,n)}catch(n){console.log(n)}},async run(){const e=this._internal;if(this.context.editorConnection&&(e.state!=="idle"?this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"Cannot start when not in idle mode"}):e.template?e.items?this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks"):this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"No items array provided."}):this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"No task template specified."})),e.state==="idle"&&e.template&&e.items){e.state="running",e.numTasks=e.items.length,e.failedTasks=0,e.completedTasks=0,e.queuedTasks=[].concat(e.items),e.runningTasks=0,e.items.length===0&&(this.sendSignalOnOutput("success"),e.state="idle");for(let t=0;t<Math.min(e.maxRunningTasks,e.queuedTasks.length);t++){const n=e.queuedTasks.shift();if(!n)break;this.startTask(n)}}},abort(){const e=this._internal;e.state="aborted"},itemOutputSignalTriggered(e,t,n){const o=this._internal;if(o.state==="idle")return;const r=()=>{if(o.state==="aborted"){this.sendSignalOnOutput("aborted"),o.state="idle";return}if(o.completedTasks===o.numTasks)o.failedTasks===0?this.sendSignalOnOutput("success"):this.sendSignalOnOutput("failure"),this.sendSignalOnOutput("done"),o.state="idle";else if(o.stopOnFailure)if(o.failedTasks===0){o.runningTasks++;const s=o.queuedTasks.shift();s&&this.startTask(s)}else this.sendSignalOnOutput("failure"),this.sendSignalOnOutput("aborted");else{o.runningTasks++;const s=o.queuedTasks.shift();s&&this.startTask(s)}};e==="Success"?(o.completedTasks++,o.runningTasks--,r()):e==="Failure"&&(o.completedTasks++,o.failedTasks++,o.runningTasks--,r()),o.activeTasks.delete(n.id),this.nodeScope.deleteNode(n)},_queueOperation(e){this._internal.queuedOperations.push(e),this._runQueueOperations()},async _runQueueOperations(){if(!this.runningOperations){for(this.runningOperations=!0;this._internal.queuedOperations.length;)await this._internal.queuedOperations.shift()();this.runningOperations=!1}}},_deleteAllTasks(){for(const e of this._internal.activeTasks)this.nodeScope.deleteNode(e);this._internal.activeTasks.clear()},_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this._deleteAllTasks()}},RunTasks={node:RunTasksDefinition},defaultRequestScript=`//Add custom code to setup the request object before the request
|
|
2
2
|
//is made.
|
|
3
3
|
//
|
|
4
4
|
//*Request.resource contains the resource path of the request.
|