Spanish Total.js
English
Documentation For AI agents
Contents

FlowStream

The Flow global, running FlowStreams, components, instances, messages and the flow5 command.

.md GitHub
On this page

Methods, properties and events of the Flow global, of a running FlowStream (Flow.instances[id]), of component definitions, component instances and messages, plus the flow5 command. For an introduction with examples read the guide FlowStream.

API

class

Flow / FlowStream

The global object of the FlowStream engine.

Flow and FlowStream are the same object. It loads flows, keeps them in Flow.instances and emits the events load, save and remove. The running flows are objects described here as flowstream.

List running flows
for (var id in Flow.instances)
	console.log(id, Flow.instances[id].stats);
method

Flow.load(schema, [callback])

Starts a FlowStream from its schema.
ParameterTypeDescription
schema Object The FlowStream schema
callback? Function function(err, flowstream)

Missing keys get defaults: a random id, name = id, empty components, design, sources and variables. When a FlowStream with the same id is running, it is reloaded with the new schema instead. The callback runs when the components and the design are loaded. See FlowStream for the keys of the schema.

Load a file
var schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();
Flow.load(schema, function(err, flowstream) {
	err && console.error(err);
});
Run in a worker thread
Flow.load({ id: 'import', worker: 'worker', components: {}, design: {} });
method

Flow.init([directory], [callback])

Loads all .flow files of a directory.
ParameterTypeDescription
directory? String Directory with .flow files Default: PATH.root('flowstreams')
callback? Function Called when all files are loaded

Reads every *.flow file (a JSON schema) of the directory and loads it with Flow.load(). Files with -bk or _bk in the name are skipped. The directory defaults to /flowstreams/ in the app root. The framework calls it once at start, so you only need it for other directories. The index.flow file of a plugin is loaded with the plugin.

Another directory
Flow.init(PATH.root('data/flows'), function() {
	console.log('Loaded:', Object.keys(Flow.instances));
});
method

Flow.reload(schema, [restart])

Applies a new schema to a running FlowStream.
ParameterTypeDescription
schema Object The new schema
restart? Boolean Restart the worker Default: false

Returns Boolean true when the FlowStream exists

The schema must have the id of a running FlowStream. The components and the design are replaced in place and removed components are unregistered. With restart (workers only) the worker is ended and started again with its current schema; the new schema is not applied. Returns false when no FlowStream has this id.

method

Flow.remove(id)

Stops and removes a FlowStream.
ParameterTypeDescription
id String FlowStream id

Closes all instances, ends the worker, removes the FlowStream from Flow.instances and emits remove.

Remove
Flow.remove('orders');
method

Flow.restart(id)

Restarts a FlowStream that runs in a worker.
ParameterTypeDescription
id String FlowStream id

Returns Boolean true when found

Ends the worker thread or the child process; it is started again automatically with the current schema after a second. Returns true when the FlowStream exists (otherwise undefined). A FlowStream in the main process is ended and not started again.

method

Flow.socket(id, websocket, [verify], [check])

Connects the Total.js Flow editor to a FlowStream.
ParameterTypeDescription
id String FlowStream id
websocket WebSocket The WebSocket of the route
verify? Function function(client, next)
check? Function function(client, message) returns true or an error

Pass the WebSocket object of a SOCKET route. verify(client, next) can accept a new client before it gets the flow (call next()), and check(client, message) can block single commands: return true to allow, or an error text. An unknown id closes the WebSocket.

Route for the editor
exports.install = function() {
	ROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {
		$.autodestroy();
		Flow.socket($.params.id, $, null, function(client, msg) {
			return client.user.sa ? true : 'Only for admins';
		});
	});
};
method

Flow.notify($, id)

Passes an HTTP request to the notify delegate of an instance.
ParameterTypeDescription
$ Controller The controller of the route
id String flowid-instanceid

id is flowid-instanceid (more - parts become params). The notify delegate of the instance gets { id, method, headers, query, body, url, ip, params }, and the editor gets the same object. Then the response redirects to ?REDIRECT=url, sends a small page that closes the window (for browsers) or a success JSON.

Routes
ROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));
ROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));
In a component
instance.notify = function(data) {
	instance.send('output', data.body);
};
method

Flow.test(name, source, [config], init)

Loads one component in a test flow.
ParameterTypeDescription
name String Component id
source String Source of the component
config? Object Configuration of the instance Default: {}
init Function function(test)

Creates a flow with the component (instance id component) and a helper instance connected to all its inputs and outputs. init(test) gets the Test object:

MemberUse
test.send(input, data)Sends data to an input of the component (alias input)
test.message = function($, data)Receives what the component sends to its outputs
test.status = function(status)Receives the status of the component
test.debug = function(...)Receives instance.debug() calls
test.configure = function(config)Called after a reconfiguration
test.trigger(data)Runs the trigger delegate
test.reconfigure(config)Changes the configuration
test.variables(obj)Sets the variables
test.assert(ok, text), test.ok(text), test.fail(text)Print the result; fail throws

An error in the flow ends the process.

Test
var source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');
Flow.test('uppercase', source, { field: 'name' }, function(test) {
	test.message = function($, data) {
		test.assert(data.name === 'PETER');
	};
	test.send('input', { name: 'Peter' });
});
property

Flow.instances

The running FlowStreams by id.

Returns Object

An object: FlowStream id → flowstream object. Flow.db holds the last schema of each FlowStream (updated on every save).

Get one
var flowstream = Flow.instances.orders;
event

Flow.on('load', function(flowstream, schema) {})

A FlowStream is loaded.
ParameterTypeDescription
flowstream Object The running FlowStream
schema Object The schema

Emitted after Flow.load() has loaded the components and the design.

event

Flow.on('save', function(schema) {})

The schema of a FlowStream has changed.
ParameterTypeDescription
schema Object The whole schema

Emitted about 5 seconds after a change in the editor or a call of instance.save(). The schema contains id, name, components, design, variables, sources, paused and the other keys. Store it yourself, for example in a .flow file. Flows with readonly: true are not saved.

Save to a file
Flow.on('save', function(schema) {
	F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP);
});
event

Flow.on('remove', function(schema) {})

A FlowStream was removed.
ParameterTypeDescription
schema Object The schema

Emitted by Flow.remove() with the last schema of the removed FlowStream.

event

Flow.on('stats', function(id, stats) {})

Counters of a FlowStream that runs in a worker.
ParameterTypeDescription
id String FlowStream id
stats Object Counters

Emitted every 15 seconds for each FlowStream in a worker thread or child process. stats has paused, messages, pending, memory, minutes, errors, mm and pid.

event

ON('flowstream', function(flowstream) {})

since 0.0.16 A FlowStream has started.
ParameterTypeDescription
flowstream Object The running FlowStream

Global framework event emitted when a FlowStream is created, also after the automatic restart of a worker.

Log
ON('flowstream', function(flowstream) {
	console.log('FlowStream', flowstream.id);
});
event

ON('flowstream_error', function(meta) {})

An error occurred in a FlowStream.
ParameterTypeDescription
meta Object Error details

Errors are printed to the console and emitted as this global event. meta has id and name (of the FlowStream), error, source, instanceid and componentid.

Audit errors
ON('flowstream_error', function(meta) {
	console.log(meta.name, meta.componentid, meta.error);
});
type

{ id, name, components, design, variables, ... }

The object that describes a FlowStream.

components maps a component id to its source code. design maps an instance id to { component, config, connections, x, y, note, tab }; connections maps an output id to an array of { id, index } (target instance and its input). Further keys: variables, sources (TMS), worker, memory (with worker: the heap limit of the worker thread or the child process in MB), proxypath, cloning, paused, readonly, import, initscript, env, directory and asfiles (true compiles the components into files in /tmp/). Descriptive keys like icon, color, author, version and readme are shown in the editor.

Two connected instances
{
	"id": "demo",
	"name": "Demo",
	"components": { "uppercase": "<script total>...</script>", "print": "<script total>...</script>" },
	"design": {
		"a1": { "component": "uppercase", "config": { "field": "name" }, "connections": { "output": [{ "id": "b1", "index": "input" }] } },
		"b1": { "component": "print", "config": {} }
	},
	"variables": {}
}
config

schema.proxytimeout

since 0.0.18 Timeout of the proxy of a worker with proxypath.

Returns Number

Milliseconds for the timeout of the proxy that forwards requests under proxypath to the worker. It is applied when the schema is loaded again into the running FlowStream (Flow.load() with the same id or Flow.reload()).

Reload with a timeout
Flow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });
property

flowstream.stats

Counters of the FlowStream.

Returns Object

messages (total), pending, memory (bytes), minutes (uptime), errors (the number of the last errors, at most 10), mm (messages in the last minute) and paused. For a flow in the main process, online is the number of connected editors. For a worker the values arrive every 15 seconds.

method

flowstream.trigger(id, [data])

Runs the trigger delegate of instances.
ParameterTypeDescription
id String Instance id, @componentid or #name
data? Object Passed to the delegate

Returns Object The flowstream

Calls instance.trigger(data) of the instance id, of all instances of a component (@componentid) or of a component name (#name). Nothing runs while the flow is paused.

Start all timers
Flow.instances.orders.trigger('@timer');
method

flowstream.send(id, data, [callback])

Sends data into an instance and waits for the result.
ParameterTypeDescription
id String Target, optionally with /input
data Object Payload
callback? Function function(err, response)

Creates a new message with data and passes it to the message delegate of the instance (id, @componentid or #name; the first match). Add /inputid to set $.input. The callback runs when the message and all its clones are ended, with { error, repo, data, count, cloned, duration, meta: { id, component } }.

Call a flow from an API
NEWACTION('Orders/process', {
	action: function($, model) {
		Flow.instances.orders.send('@order/input', model, function(err, response) {
			if (err)
				$.invalid(err);
			else
				$.callback(response.data);
		});
	}
});
method

flowstream.exec(opt, [callback])

Sends a message to all matching instances.
ParameterTypeDescription
opt Object Options
callback? Function function(err, response)

Like send(), but for every matching instance. opt.id is the target (id, @componentid or #name), opt.data the payload, opt.vars and opt.repo the $.vars and $.repo, opt.timeout a timeout in ms (the message ends with error 408). opt.uid and opt.ref come back in the response. The callback runs for each target (for a flow in a worker only for the first one), or with 404 when nothing matches.

Exec with a timeout
Flow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {
	console.log(response.uid, response.data);
});
method

flowstream.pause([is])

Pauses or resumes the FlowStream.
ParameterTypeDescription
is? Boolean true pauses, false resumes

Returns Object The flowstream

A paused flow does not deliver messages. Without the argument the state is toggled. The pause delegate of each instance is called.

method

flowstream.variables(obj)

Replaces the variables of the FlowStream.
ParameterTypeDescription
obj Object New variables

Returns Object The flowstream

Calls the variables delegate of each instance (and vary('variables') for a flow in the main process), sends the variables to the editor and saves the flow.

Rotate a token
Flow.instances.orders.variables({ token: newtoken });
method

flowstream.reconfigure(id, config)

Changes the configuration of an instance.
ParameterTypeDescription
id String Instance id
config Object Values to merge

Returns Object The flowstream

The values are merged into instance.config, the configure delegate is called, the editor is updated and the flow is saved.

method

flowstream.export(callback)

Reads the current schema.
ParameterTypeDescription
callback Function function(err, schema)

The callback gets the whole schema, the same object as the save event.

Backup
Flow.instances.orders.export(function(err, schema) {
	F.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP);
});
method

flowstream.restart()

Restarts a FlowStream that runs in a worker.

Closes the editor connections and ends the worker; it starts again automatically with the current schema.

method

flowstream.remove()

Removes the FlowStream.

The same as Flow.remove(flowstream.id).

method

flowstream.edit([url])

since 0.0.16 Connects the FlowStream to a remote editing proxy.
ParameterTypeDescription
url? String Proxy WebSocket URL Default: 'wss://flow.totaljs.com/{0}/'

Returns WebSocketClient The client

Opens a WebSocket client to the URL ({0} is replaced by the FlowStream id) and lets the editor work through it, so the application does not need a public WebSocket route. A previous connection is closed. Returns the WebSocket client.

Remote editing
Flow.instances.orders.edit();
type

exports.* in <script total>

The definition of a FlowStream component.

The server part of the component sets properties of exports:

PropertyMeaning
name, icon, color, group, version, authorShown in the editor
typeFor example input, output or config; these appear in io() listings
inputs, outputsArrays of { id, name }
configDefault configuration of new instances
npmNPM packages installed before registering
permissions, metaCustom data passed to the editor
makefunction(instance, config) for each instance
install, uninstallfunction(component) when the component is registered and removed
callfunction(data, callback) called by the editor with @componentid

The other parts of the file: <settings> (the configuration form), <body>, <style>, <script> (editor code), <readme>, <template> and <schema>.

Minimal component
<script total>
	exports.name = 'Print';
	exports.inputs = [{ id: 'input', name: 'Input' }];
	exports.make = function(instance) {
		instance.message = function($) {
			console.log($.data);
			$.end();
		};
	};
</script>
method

exports.make = function(instance, config) {}

Creates an instance of the component.
ParameterTypeDescription
instance Object The instance
config Object Its configuration

Runs for each instance placed on the canvas, and again when the component code changes. config is instance.config. Assign the delegates of the instance here.

Interval
exports.make = function(instance, config) {
	var timer;
	instance.configure = function() {
		clearInterval(timer);
		timer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);
	};
	instance.close = () => clearInterval(timer);
	instance.configure();
};
property

exports.inputs / exports.outputs

The inputs and outputs of a component.

Returns Array

Arrays of { id, name }. The id is what $.input contains and what $.send(id) and instance.send(id) use. An instance can override them with its own inputs / outputs.

Two outputs
exports.inputs = [{ id: 'input', name: 'Input' }];
exports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }];
type

instance

One placed instance of a component.

The first argument of exports.make(). Properties: id, component (component id), config, cache, main (the flow engine), module (the component), env, stats (pending, input, output, duration, destroyed), instances (all instances of the flow) and components.

Delegates you can assign: message($), message_INPUTID($), configure(config), close(), init() (after the first load), refresh() (after each change of the design), trigger(data), notify(data), call(data, callback), service(minutes) (every minute), pause(is), variables(obj), secrets(obj) and vary(type).

delegate

instance.message = function($) {}

Receives a message on an input.
ParameterTypeDescription
$ Message The message

$.input is the input id. instance.message_INPUTID receives messages of one input only; when both exist, both are called. A message that is not sent further must be ended with $.end().

Route by input
instance.message = function($) {
	if ($.input === 'reset') {
		count = 0;
		$.end();
	} else {
		count++;
		$.send('output', { count: count });
	}
};
delegate

instance.configure = function(config) {}

The configuration has changed.
ParameterTypeDescription
config Object The configuration

Called after a change in the editor or a call of reconfigure(). instance.config already contains the new values.

delegate

instance.close = function() {}

The instance is being removed.

Called when the instance is removed from the design, the component is unregistered or the flow ends. Clear timers and close connections here.

method

instance.send(output, [data])

Starts a new message from an output or from all outputs.
ParameterTypeDescription
output String Output id, or null for all outputs
data? Object Payload

Returns Number Count of sent messages

Sends data to every instance connected to the output. With output null it sends to all outputs. For the second and next connection the data are cloned (unless cloning: false). Returns the number of sent messages; 0 when nothing is connected or the flow is paused.

From a timer
setInterval(() => instance.send('output', { ts: NOW }), 1000);
All outputs
instance.send(null, { ts: NOW });
method

instance.newmessage([data])

Creates a message without sending it.
ParameterTypeDescription
data? Object Payload

Returns Message A new message

The message belongs to the instance; set $.repo, listen to end and then call $.send(output).

Wait for the end
var msg = instance.newmessage({ id: 1 });
msg.on('end', function($) {
	console.log('Done', $.data);
});
msg.send('output');
method

instance.status([data], [delay])

Sets the status shown under the instance.
ParameterTypeDescription
data? Object Any JSON value
delay? Number Throttle in ms

The status is sent to the editor and emitted as status on instance.main. With delay (ms) many calls are merged into one update. Without arguments the last status is sent again.

Counter
instance.status({ count: count }, 1000);
method

instance.dashboard([data])

Sends data to the dashboard of the editor.
ParameterTypeDescription
data? Object Any JSON value

The data are kept and sent to the editor; without arguments the last data are sent again.

method

instance.throw(error)

Reports an error of the instance.
ParameterTypeDescription
error Error|String The error

The error is added to the last 10 errors of the flow (instance.main.errors), shown in the editor, printed to the console and emitted as ON('flowstream_error'). $.throw(error) does the same and sets $.error.

In a callback
RESTBuilder.GET(config.url).callback(function(err, response) {
	if (err) {
		instance.throw(err);
		$.end();
	} else
		$.send('output', response);
});
method

instance.debug(a, [b], [c], [d])

Emits a debug event.

Emits debug on instance.main with the instance and the arguments. Flow.test() passes it to test.debug.

method

instance.save([redraw])

Saves the instance after a change from code.
ParameterTypeDescription
redraw? Boolean Redraw the instance in the editor Default: true

Use it after you change instance.config, x, y, note, inputs or outputs in the code. The flow is saved (the save event follows after about 5 seconds) and, unless redraw is false, the editor redraws the instance.

Remember a value
instance.config.lastid = $.data.id;
instance.save();
Without redraw
instance.config.counter++;
instance.save(false);
method

instance.reconfigure(config)

Changes the configuration of this instance.
ParameterTypeDescription
config Object Values to merge

The same as flowstream.reconfigure(instance.id, config) called from the component.

method

instance.replace(text, [data], [encoding])

Replaces {variables} in a text.
ParameterTypeDescription
text String|Object Text with placeholders
data? Object Extra values
encoding? String|Function Encoding of the values

Returns String The text

A {name} (or {{name}}) takes the value from the variables of the flow, the global variables, the secrets, {hostname} (origin plus proxypath) or the data object (nested keys with dots). encoding can be url, json, querify or a function(value, key). An object replaces each string value. In a message use $.variables() (alias $.replace()), where data defaults to the message.

URL
var url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');
property

instance.cache

An in-memory object for runtime data of the instance.

Returns Object

A plain object in memory, kept by the flow for the instance id: when the instance is initialized again (for example when its component is updated), it gets the same object back. It is not saved, so it is empty after a restart.

Last value
instance.message = function($) {
	instance.cache.last = $.data;
	$.send('output');
};
property

instance.repo

since 0.0.17 Persistent data of the instance stored in the design.

Returns Object

An object saved in the schema together with the instance. It survives a reload and a restart, and the editor keeps it unchanged when it saves the design. Call instance.save() after a change.

Keep a cursor
instance.repo.lastid = $.data.id;
instance.save();
method

instance.activity(key, name, [progress])

since 0.0.19 Reports a running activity of the instance.
ParameterTypeDescription
key String Activity id
name String Description
progress? Number Percent

Creates or updates the activity key, shows it in the editor and emits activity on instance.main with (instance, key, name, progress). An empty name or progress 100 removes it. Activities of instances removed from the design are dropped.

Progress
instance.activity('sync', 'Synchronizing', 40);
// ...
instance.activity('sync', 'Synchronizing', 100);
property

instance.main

The flow engine of the instance.

Returns FlowStream

Useful members: variables, secrets, stats (with online, the number of connected editors), errors, paused, env, activities, find(id) (an instance), instances() (ready instances), send('ID__OUTPUT', data), trigger('ID__INPUT', data) (sends a new message to an input), pause(is), save() and restart() (restarts the worker of the flow; in the main process it asks the Total.js process manager to restart the application). It emits status, debug, activity, message, end and reset events.

Send to another instance
instance.main.trigger('b1__input', { id: 1 });
event

instance.main.on('reset', function() {})

The errors of the flow were reset.

Emitted by the flow engine when the editor sends the reset command: the last errors of the flow (instance.main.errors) are cleared first, then the event runs without arguments. In a flow that runs in a worker it is emitted inside the worker. The engine stays when an instance is created again, so remove the listener in instance.close.

Reset a counter
exports.make = function(instance) {

	instance.cache.count = 0;

	var onreset = function() {
		instance.cache.count = 0;
		instance.status({ count: 0 });
	};

	instance.main.on('reset', onreset);

	instance.close = function() {
		instance.main.off('reset', onreset);
	};

};
class

$

A message travelling through the flow.

Properties: data, repo (shared by all clones), vars, input, output, from/fromid, to/toid (instances), instance, main, id, count, duration, error, controller, and from the controller user, body, query, params, headers, ip, language.

Methods: send(), end() (alias destroy()), rewrite(data), clone(), variables(), timeout(), status(), dashboard(), debug(), throw() and on(name, fn). Events: end (the message and all clones are ended), timeout and message.

method

$.send(output, [data], [clone], [check])

Sends the message to an output or to all outputs.
ParameterTypeDescription
output String Output id, or null for all outputs
data? Object New payload
clone? Boolean Clone the data Default: the `cloning` of the flow
check? Function function(from, to, output, input) returns a Boolean

Returns Number Count of targets

Sends a clone of the message to every instance connected to the output. With output null it sends to all outputs: an output without a ready target is skipped, the other outputs still get the message, and the message ends once, when all its clones end. data replaces the payload; clone (default: the cloning of the flow) deep-copies object data for each target. check(from, to, output, input) is called for each target of a named output (from and to are instances); return false to skip the target. Returns the number of targets; with 0 the message ends.

Pass on
instance.message = function($) {
	$.data.checked = true;
	$.send('output');
};
Skip some targets
$.send('output', null, null, function(from, to, output, input) {
	return to.component !== 'debug';
});
All outputs
instance.message = function($) {
	$.send(null);
};
method

$.end()

Ends the message.

Call it when the message is not sent further. When the message and all its clones are ended, its end event fires (and the callback of flowstream.send()).

Stop here
instance.message = function($) {
	save($.data);
	$.end();
};
method

$.timeout([callback], time)

Sets a timeout for the next instances.
ParameterTypeDescription
callback? Function function($)
time Number Milliseconds

Returns Message

Each clone sent after this call must be processed within time ms; otherwise it ends with $.error = 408 and the callback runs. $.totaltimeout([callback], time) limits the whole message instead.

Timeout
$.timeout(function($) {
	instance.throw('Timeout');
}, 5000);
$.send('output');
command

flow5 [path or URL ...] [port]

Runs FlowStream schemas from the command line.

Loads each JSON file (one schema, or an object with several schemas) or HTTPS URL, starts an HTTP server on the port (default 8000) with the route SOCKET /flowstreams/{id}/ and the /notify/{id}/ routes, and prints the editor link for each flow. Changes from the editor are written back to the local files. Without arguments it prints help.

Two flows on port 8001
flow5 orders.json import.json 8001
Made in Europe