Spanish Total.js
English
Documentation For AI agents
Contents

Plugins and components

The plugin definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() with its Component, Instance and Message objects, NPMINSTALL(), REQUIRE() and IMPORT().

.md GitHub
On this page

Properties of a plugin index.js, the plugin files, PLUGINS, COMPONENTATOR(), server components compiled with NEWCOMPONENT() (the component, its instances and messages) and the loaders NPMINSTALL(), REQUIRE() and IMPORT(). For an introduction with examples read the guide Plugins and components.

API

type

plugins/{id}/index.js

A folder in plugins/ with an index.js file, loaded at start.

Every folder in plugins/ with an index.js file is a plugin; the folder name is the plugin id. A folder without index.js is skipped with all its subfolders, and so are folders whose name contains -bk or _bk. Total.js requires index.js, stores its exports in PLUGINS[id], sets exports.id when missing and calls exports.install(). A config file in the folder is merged into CONF. The subfolders controllers/, actions/, schemas/, models/, definitions/, extensions/ and middleware/ are loaded like the folders of the application. An index.flow file is loaded as a FlowStream.

A minimal plugin
// plugins/contacts/index.js
exports.name = 'Contacts';
exports.icon = 'ti ti-address-book';
exports.permissions = ['contacts'];

exports.install = function() {
	ROUTE('+API    ?    contacts_list    --> Contacts/list');
};
delegate

exports.install = function() {}

Called once when the plugin is loaded.

Register routes, events and other definitions of the plugin here. It runs during the loading of the application, in the same pass as the files of controllers/, definitions/ and the other folders, so use ON('ready') when you need everything to be loaded first.

Routes and a ready handler
exports.install = function() {
	ROUTE('+GET /admin/contacts/', function($) {
		$.view('#contacts/views/index');
	});
	ON('ready', function() {
		// all plugins are loaded
	});
};
property

exports.id

The id of the plugin.

Returns String

When index.js does not define it, Total.js sets it to the name of the plugin folder. PLUGINS uses the folder name as the key in both cases.

property

exports.name

A human readable name of the plugin.

Returns String

Total.js writes it, with the id and the permissions, to the source map of the application in debug mode. Your UI can read it from PLUGINS to build a menu.

Name
exports.name = 'Orders';
property

exports.permissions

The permissions the plugin defines.

Returns Array

An array of strings or of objects with an id property (and anything else you need, such as name). The ids are written, joined with commas, to the source map in debug mode. Read the array from PLUGINS to offer the permissions in a user editor and check them with the permissions option of your actions (see Authorization).

Permissions
exports.permissions = [
	{ id: 'orders', name: 'Orders' },
	{ id: 'orders_remove', name: 'Remove orders' }
];
property

exports.icon, exports.visible, exports.position, ...

Your own properties of a plugin.

Total.js does not read any other property of index.js. Properties such as icon, position or visible are a convention for your administration UI, which reads them from PLUGINS.

Menu data
exports.icon = 'ti ti-truck';
exports.position = 5;
exports.visible = function(user) {
	return user.sa || user.permissions.includes('orders');
};
property

PLUGINS

All loaded plugins by id.

Returns Object id: exports

An object whose keys are plugin ids and whose values are the exports of their index.js. It is filled during the loading of the application.

List plugins
ON('ready', function() {
	for (var id in PLUGINS)
		console.log(id, PLUGINS[id].name);
});
config

plugins/{id}/config

since 0.0.16 Configuration file of a plugin.

A config file in the folder of a plugin is read before the scripts of the application and the plugins run, after the main config. It has the same format as the main file and its keys are merged into CONF; a key that is also in the main file is overwritten.

Defaults of a plugin
shop_currency    : EUR
shop_pagesize    : 20
type

plugins/{id}/index.flow

since 0.0.19 A FlowStream loaded with the plugin.

An index.flow file (a FlowStream export in JSON) in the folder of a plugin is read and started after the files of the application and the index.js of the plugin, before the other files of the plugin; the instance is created asynchronously and is stored in PLUGINS[id].flowstream once it is ready. The FlowStream gets the plugin id as id, the translated plugin name (or the id) as name and the plugin folder as directory. The instance is stored in PLUGINS[id].flowstream; errors are logged as Plugin.<id>.flowstream. See FlowStream.

property

PLUGINS[id].flowstream

since 0.0.19 The FlowStream instance loaded from index.flow.

Returns FlowStream

Set when the index.flow file of the plugin has been loaded.

method

PATH.plugins([path])

Returns a path in the plugins folder.
ParameterTypeDescription
path? String A relative path such as "shop/data.json"

Returns String Absolute path

Without an argument it returns the absolute path of plugins/; with a path it joins it. With a path, the plugins folder is created when it does not exist.

Read a file of a plugin
var filename = PATH.plugins('shop/data/countries.json');
F.Fs.readFile(filename, 'utf8', function(err, data) {
	// ...
});
type

controller.view('#{id}/path')

Renders a view from a plugin folder.

A view name that starts with # is relative to plugins/: #shop/views/index renders plugins/shop/views/index.html. The same prefix works in TEMPLATE('#shop/templates/order.html'), which adds .html when the name does not contain it.

A view of a plugin
exports.install = function() {
	ROUTE('+GET /admin/shop/', function($) {
		$.view('#shop/views/index');
	});
};
method

COMPONENTATOR(name, components, [removeprev], [attrs])

Downloads a bundle of UI components from Componentator.
ParameterTypeDescription
name String Name of the bundle; used in the file name and as the key in REPO
components String Comma separated component names
removeprev? Boolean Delete older bundles with the same name Default: true
attrs? String Extra URL-encoded fields sent with the download request Default: ''

Downloads one minified file with the listed jComponent components from https://componentator.com/download/ into public/ui-<name>-<hash>.min.js (public/ui-<hash>.min.js with removeprev set to false). The hash is computed from components, and the file is downloaded only when it does not exist. With removeprev (default), older ui-<name>-* files are deleted. The URL of the bundle is stored in REPO[name]. Errors are logged. When removeprev is a string, it is taken as attrs.

A UI bundle
// definitions/ui.js
COMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);
In the layout
<script src="@{REPO.ui}"></script>
event

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

Emitted before COMPONENTATOR() builds the file name.
ParameterTypeDescription
meta Object { name, components }

meta contains name and components. You can change both, for example to add a component to every bundle; the new values are used for the file name, REPO and the download.

Add a component everywhere
ON('componentator', function(meta) {
	meta.components += ',errorhandler';
});
method

NEWCOMPONENT(html, [callback])

Compiles a server component.
ParameterTypeDescription
html String File name, HTML or URL
callback? Function function(err, component)

Returns Promise<Component> When callback is not set

html is the name of a file in components/ (without .html), the HTML content itself (anything containing <), or an https:// URL that is downloaded first. The server code must be in a <script total> or <script node> block; without it you get the error "Invalid component content". The code runs with exports (the component) and require (REQUIRE()). Packages in exports.npm are installed, schemas of inputs and outputs are compiled and exports.install() is called. Returns a Promise without a callback.

From the components folder
NEWCOMPONENT('uppercase', function(err, com) {
	if (err) {
		console.error(err);
		return;
	}
	var instance = com.create();
});
Inline
var html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\'output\', msg.data * 2); };</script>';
var com = await NEWCOMPONENT(html);
type

components/{name}.html

The format of a server component.

An HTML file with these parts: <script total> or <script node> (server code, required), <settings>, <style>, <script>, <body>, <readme>, <schema> and <template>. The server code is removed from the result; the other parts are available in component.ui (settings, css, js, html, readme, schema, template).

A complete file
<script total>

	exports.name = 'Counter';
	exports.config = { step: 1 };
	exports.inputs = [{ id: 'input', name: 'Value' }];
	exports.outputs = [{ id: 'output', name: 'Sum' }];

	exports.make = function(instance, config) {
		var sum = 0;
		instance.message = function(msg) {
			sum += config.step;
			msg.send('output', sum);
		};
	};

</script>

<readme>
Counts incoming messages.
</readme>

<settings>
<div>Step of the counter</div>
</settings>
class

Component

A compiled server component.

The object returned by NEWCOMPONENT(). Its properties come from exports of the server code (name, config, inputs, outputs, npm, make, ...) plus ui, instances, variables, secrets and debugger.

delegate

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

Sets up a new instance.
ParameterTypeDescription
instance Instance The new instance
config Object Its configuration
status Object The second argument of create()

Called by component.create() with the instance as this and as the first argument. Assign instance.message (and other handlers such as instance.close, instance.configure or instance.service) here.

Handlers
exports.make = function(instance, config) {
	instance.message = function(msg) {
		msg.send('output', msg.data);
	};
	instance.configure = function() {
		// config has changed
	};
};
property

exports.config

Default configuration of instances.

Returns Object

Each instance gets a clone of this object, extended with the options passed to component.create().

property

exports.inputs / exports.outputs

Inputs and outputs of the component.

Returns Array

Arrays of { id, name, schema }. A schema (a schema string such as 'name:String, age:Number') is compiled into a JSON schema. For inputs it is applied in instance.input(): the cleaned data replaces msg.data and errors are in msg.error.

With a schema
exports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];
exports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];

exports.make = function(instance) {
	instance.message = function(msg) {
		if (msg.error)
			msg.send('error', msg.error.toString());
		else
			msg.send('ok', msg.data);
	};
};
property

exports.npm

NPM packages the component needs.

Returns String[]

An array of package names (optionally name@version). NEWCOMPONENT() installs them with NPMINSTALL() before install() runs; the compilation fails with the npm error when one cannot be installed.

Dependencies
exports.npm = ['mqtt'];

exports.make = function(instance, config) {
	var mqtt = require('mqtt');
	// ...
};
delegate

exports.install = function(component) {}

Called once after the component is compiled.

Runs with the component as this and as the argument, after NPM packages are installed and schemas are compiled.

delegate

exports.onextend = function(instance) {}

Extends each new instance before make().

Called in component.create() after the configuration is set and before make().

delegate

exports.oncreate = function(instance) {}

Called after an instance is created.

Runs asynchronously (in setImmediate) after make().

delegate

exports.onremove = function(instance) {}

Called when an instance is removed.

Called by instance.remove() after the close and destroy handlers of the instance.

property

component.ui

The UI parts of the component file.

Returns Object

An object with readme, settings, css, js, html, schema and template (only the parts found in the file).

property

component.instances

All instances of the component.

Returns Instance[]

create() adds an instance and instance.remove() removes it.

property

component.debugger

Prints status, debug, error and output messages to the console.

Returns Boolean

true by default. Set it to false to keep the console quiet, or replace component.output, component.status, component.debug, component.throw or component.dashboard with your own functions.

delegate

component.output = function(instance, msg) {}

Receives every message sent to an output.
ParameterTypeDescription
instance Instance The sender
msg Message msg.output and msg.data

Called for each msg.send() of any instance. The default prints the output and the data when debugger is on. Replace it to connect instances or to process results. component.status(instance, value), component.debug(instance, value), component.throw(instance, err) and component.dashboard(instance, value) receive the calls of the instance methods with the same name.

Collect results
var com = await NEWCOMPONENT('uppercase');
com.output = function(instance, msg) {
	console.log(instance.id, msg.output, msg.data);
};
method

component.create([options], [status])

Creates an instance.
ParameterTypeDescription
options? Object Configuration of the instance
status? Object Passed to make() as the third argument

Returns Instance

The instance gets a random id, a clone of component.config extended with options, and is added to component.instances. Then onextend(), make() and (asynchronously) oncreate() are called.

Two instances
var a = com.create({ prefix: 'A: ' });
var b = com.create({ prefix: 'B: ' });
method

component.service(counter)

Calls instance.service(counter) on all instances.
ParameterTypeDescription
counter Number Any value passed to the instances

Total.js does not call it for you. Call it from ON('service') when your instances need a periodic tick.

Every minute
ON('service', function(counter) {
	com.service(counter);
});
class

Instance

An instance of a server component.

Returned by component.create(). Properties: id, config, module (the component) and cache (an empty object for your data). Handlers you can assign in make(): message, message_<input>, configure, close, destroy and service.

delegate

instance.message = function(msg) {}

Handles data that comes to an input.
ParameterTypeDescription
msg Message The incoming message

Called by instance.input(). msg.input is the input id and msg.data the data. A handler named instance.message_<input> is called too, after message. Without instance.message the input is ignored.

Per input
exports.make = function(instance) {
	instance.message = NOOP;
	instance.message_reset = function(msg) {
		// only for input "reset"
	};
};
method

instance.input(input, data, [callback])

Sends data to an input of the instance.
ParameterTypeDescription
input String Input id
data Object The data
callback? Function function(msg)

Creates a message, validates the data with the schema of the input (if any) and calls instance.message(msg) and instance.message_<input>(msg). The callback is called with the message each time it is sent to an output with msg.send().

Call and read the result
instance.input('input', 'hello', function(msg) {
	console.log(msg.output, msg.data);
});
method

instance.send(output, data)

since 0.0.17 Sends new data to an output.
ParameterTypeDescription
output String Output id
data Object The data

Creates a new message with data and sends it to output; it ends in instance.output(msg) and so in component.output(). Use it for data the instance produces on its own (a timer, a socket).

A timer
exports.make = function(instance) {
	var timer = setInterval(() => instance.send('output', new Date()), 5000);
	instance.close = () => clearInterval(timer);
};
method

instance.status(value) / debug(value) / throw(err) / dashboard(value)

Reports a state of the instance.
ParameterTypeDescription
value Object Any value

Each method calls the component method with the same name (component.status(instance, value) and so on). By default they print to the console when component.debugger is on.

Report
instance.status({ connected: true });
instance.throw(new Error('Connection refused'));
method

instance.activity(key, name, value)

since 0.0.19 Reports an activity of the instance.
ParameterTypeDescription
key String Identifier of the activity
name String Label
value Object For example a progress

Calls component.activity(instance, { key, name, value }), which prints ACTIVITY to the console when component.debugger is on. Replace component.activity to process it.

method

instance.reconfigure(options)

Changes the configuration of an instance.
ParameterTypeDescription
options Object New values

Copies the keys of options to instance.config and calls instance.configure(config) when it is defined.

Change a value
instance.reconfigure({ prefix: '>> ' });
method

instance.remove()

Removes the instance.

Calls instance.close(true) and instance.destroy() when defined, then component.onremove(instance), and removes the instance from component.instances.

Remove
instance.remove();
method

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

Replaces {key} placeholders in a string.
ParameterTypeDescription
str String|Object Template
data? Object Values
encoding? String|Function Encoding of the values

Returns String|Object

Each {key} (or {{key}}) is taken from component.variables, then component.secrets, then data (nested keys with dots work). Without data the instance itself is used. encoding can be 'url' (or 'urlencoded'), 'json', 'querify' or a function(value, key). Dates are formatted. An object as str replaces its string values. msg.replace() works the same way.

A URL
com.variables.api = 'https://api.example.com';
var url = instance.replace('{api}/users/{id}/', { id: 15 });
class

Message

Data that flows through a component instance.

Created by instance.input() and instance.send(). Properties: data, input, output, error (an ErrorBuilder when the input schema failed, null when it passed, undefined for an input without a schema), from and instance (the instance), repo and vars (empty objects for your data).

method

msg.send(output, [data])

Sends the message to an output.
ParameterTypeDescription
output String Output id
data? Object New data

Sets msg.output and, when data is given, msg.data. Then it calls the callback of instance.input() and instance.output(msg). Nothing happens after msg.end().

Forward
instance.message = function(msg) {
	msg.send('output', { received: msg.data });
};
method

msg.end() / msg.destroy()

Releases the message.

Clears data, vars, repo and the instance, so later msg.send() calls do nothing.

method

NPMINSTALL(name, [callback])

Installs an NPM package.
ParameterTypeDescription
name String Package name, optionally with @version
callback? Function function(err)

Returns Promise When callback is not set

Runs npm install <name> in CONF.$nodemodules (created when missing). When the package folder already contains a package.json (with the same version for name@version), nothing is installed. When the process runs as user 33 (www-data), CONF.$npmcache is used as the npm cache. Without a callback it returns a Promise. See Configuration for both keys.

Install and load
NPMINSTALL('qrcode@1.5.4', function(err) {
	if (err) {
		console.error(err);
		return;
	}
	var QR = REQUIRE('qrcode');
});
method

REQUIRE(name)

Loads a Node.js or NPM module.
ParameterTypeDescription
name String Module name

Returns Object The module

Names with the node: prefix and Node.js built-in modules (fs, path, crypto, ...) are loaded directly. Other names are loaded with require() and, when that fails, from CONF.$nodemodules, so packages installed with NPMINSTALL() are found. It throws when the module cannot be loaded.

Load
var Fs = REQUIRE('fs');
var mqtt = REQUIRE('mqtt');
method

IMPORT(url, [callback])

Downloads and loads a remote JavaScript module.
ParameterTypeDescription
url String URL of a .js file
callback? Function function(err, module, response)

Returns Promise When callback is not set

The file is downloaded into the temporary folder and required. Further calls with the same URL in the same process return the loaded module without downloading. An answer with the status 400 or more gives the error The address answered with the status <status> and nothing is loaded. A file that is not a valid module gives the error of require(), for example a SyntaxError. The callback receives (err, module, response); without it a Promise resolves with the module.

Promise
var helpers = await IMPORT('https://cdn.example.com/helpers.js');
helpers.hello();
Made in Europe