@connectv/core
Version:
agent-based reactive programming library for typescript/javascript
82 lines • 2.92 kB
JavaScript
import control from '../pin/control';
import pack from '../pin/pack';
import filter from '../pin/filter';
import map from '../pin/map';
import { OutputNotInSignature } from './errors/signature-mismatch.error';
import { InsufficientInputs } from './errors/insufficient-input.error';
import { Agent } from './agent';
/**
*
* Represents a [node](https://connective.dev/docs/node).
*
*/
export class Node extends Agent {
/**
*
* @param signature the [signature](https://connective.dev/docs/agent#signature) of the node.
*
*/
constructor(signature) {
super(signature);
this._control_required = true;
this._control = control();
this._res =
pack(this.inputs, this.control.to(map(() => this._control_required = false)))
.to(filter(() => !this._control_required))
.to(map((all, callback, error, context) => {
if (this._control.connected)
this._control_required = true;
if (signature.required && signature.required.some(label => !(all && all[0] && label in all[0])))
error(new InsufficientInputs(signature.required.filter(label => !(all && all[0] && label in all[0]))));
else {
this.run(all[0], (out, data) => {
if (!this.signature.outputs.includes(out)) {
error(new OutputNotInSignature(out, this.signature));
}
else {
callback({ out, data });
}
}, error, context);
}
}));
}
/**
*
* A node waits for its `.control` before each execution, if any pins are
* connected to `.control`.
*
*/
get control() { return this._control; }
createOutput(label) {
this.checkOutput(label);
return this._res
.to(filter((res) => res.out == label))
.to(map((res) => res.data));
}
createEntries() { return (this.signature.inputs || []).map(i => this.in(i)); }
createExits() { return this.signature.outputs.map(o => this.out(o)); }
clear() {
this.control.clear();
return super.clear();
}
}
class _CodeNode extends Node {
constructor(signature, _run) {
super(signature);
this._run = _run;
}
run(inputs, output, error, context) { this._run.apply(this, [inputs, output, error, context]); }
;
}
/**
*
* Creates a [node](https://connective.dev/docs/node).
* [Checkout the docs](https://connective.dev/docs/node) for examples and further information.
*
* @param signature the signature of the node
* @param run the execution function of the node
*
*/
export function node(signature, run) { return () => new _CodeNode(signature, run); }
export default node;
//# sourceMappingURL=node.js.map