---
title: Operations and tasks
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/operations-and-tasks/
updated: 2026-11-16T15:41:15.818Z
---

# Operations and tasks

> Global functions and the $ object of operations and tasks, plus commands, extensions and PROMISIFY().

Operations (`NEWOPERATION()`, `OPERATION()`, `RUN()`) and tasks (`NEWTASK()`, `TASK()`) hold business logic outside of routes. Both receive a `$` object; this page lists its properties and methods, and also commands, extensions and `PROMISIFY()`. The guide [Operations and tasks](../../guides/operations-and-tasks/) explains how to use them with examples; this page is the exact reference.

## API

### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])

Type: `method`

Registers an operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the operation. |
| `fn` | `Function($, value)` | yes |  | The operation. `null` removes it. |
| `repeat` | `Number` | no |  | How many times to run the operation again when it ends with an error. |
| `stop` | `Boolean` | no | `true` | Stops a `RUN()` chain when this operation fails. |
| `binderror` | `Boolean` | no | `false` | In a `RUN()` chain, stores the error output as the response of this operation. |
| `filter` | `String` | no |  | Schema for the query string, used by `$.filter`. |

The function receives `$` and the value. It must end with `$.callback()`, `$.success()`, `$.invalid()` or another method that calls the callback. A boolean in place of `repeat` is read as `stop`, and a string in any optional position is read as `filter`. Calling `NEWOPERATION(name, null)` removes the operation. Put operations in the `/operations/` directory.

Example: An operation
```js
NEWOPERATION('users_count', function($, value) {
	NOSQL('users').count().callback(function(err, count) {
		if (err)
			$.invalid(err);
		else
			$.callback(count);
	});
});
```

Example: Repeat after an error
```js
NEWOPERATION('ping', function($) {
	RESTBuilder.GET('https://example.com/ping').callback($.done());
}, 3);
```

### OPERATION(name, [value], callback, [options], [controller])

Type: `method`

Runs one operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the operation, or a URL of a remote operation. |
| `value` | `Object` | no | `{}` | Value for `$.value`. |
| `callback` | `Function(err, response, options)` | yes |  | Called when the operation ends. |
| `options` | `Object` | no |  | Custom options, available as `$.options`. |
| `controller` | `Controller` | no |  | Controller of the current request, or a `$` object. |

The callback receives `err` (an `ErrorBuilder` or `null`), the response and `options`. When `value` is a function, it is the callback and the value is an empty object. A controller or a `$` object passed as `options` is used as the controller. A missing operation ends with the error `Operation "name" not found.`

The name can also be a URL with an optional expiration, for example `'https://example.com/op.js <5 minutes>'` (`once` and `asap` are accepted too). The file is downloaded, compiled and cached until it expires. It can contain a `NEWOPERATION()` declaration or a module with `exports.install`, `exports.make` or `exports.exec`.

Example: Call an operation
```js
OPERATION('users_count', function(err, response) {
	console.log(err, response);
});
```

Example: From a route
```js
exports.install = function() {
	ROUTE('GET /api/users/count/', count);
};

function count() {
	var self = this;
	OPERATION('users_count', self.query, self.callback(), self);
}
```

### RUN(names, [value], callback, [options], [controller], [response_name])

Type: `method`

Runs several operations one after another.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `names` | `String|Array` | yes |  | Operation names, separated by commas. |
| `value` | `Object` | no | `{}` | Shared value for `$.value`. |
| `callback` | `Function(err, response, $)` | yes |  | Called when the chain ends. |
| `options` | `Object` | no |  | Custom options, available as `$.options`. |
| `controller` | `Controller` | no |  | Controller of the current request. |
| `response_name` | `String` | no |  | Name of the operation whose response is returned alone. |

`names` is a comma-separated string or an array. All operations share one `$` and one `$.value`. The callback receives `err`, the response and the `$` object. The response has one key per operation; with `response_name` it is only the response of that operation. When an operation fails and its `stop` option is `true` (the default), the chain stops. Names that do not exist are skipped. A string in place of `options` or `controller` is read as `response_name`.

Example: Chain two operations
```js
RUN('check, save', { email: 'peter@example.com' }, function(err, response) {
	// response.check, response.save
	console.log(err, response);
});
```

Example: Return one response
```js
function create() {
	var self = this;
	RUN('check, save', self.body, self.callback(), null, self, 'save');
}
```

### EACHOPERATION(fn)

Type: `method`

Calls a function for each registered operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function(name)` | yes |  | Called with the name of each operation. |

The function receives the name of each operation.

Example: List operations
```js
EACHOPERATION(function(name) {
	console.log(name);
});
```

### $.value

Type: `property`

The value passed to the operation.

Returns: `Object`

`$.model` is the same value. In a `RUN()` chain, every operation shares this object, so changes are visible to the next operations.

Example: Read the value
```js
NEWOPERATION('greet', function($) {
	$.callback('Hello ' + $.value.name);
});
```

### $.options

Type: `property`

The options passed to `OPERATION()` or `RUN()`.

Returns: `Object`

An empty object when no options were passed. `OPERATION()` passes it again as the third argument of the callback.

Example: Use options
```js
NEWOPERATION('export', function($) {
	$.callback({ format: $.options.format || 'json' });
});

OPERATION('export', {}, console.log, { format: 'csv' });
```

### $.name

Type: `property`

Name of the running operation.

Returns: `String`

In a `RUN()` chain it changes with each operation.

Example: Log the name
```js
NEWOPERATION('sync', function($) {
	console.log('Running', $.name);
	$.success();
});
```

### $.error

Type: `property`

The `ErrorBuilder` of the operation.

Returns: `ErrorBuilder`

`$.invalid()` pushes errors here. In a `RUN()` chain, each operation gets a new `ErrorBuilder`.

Example: Push several errors
```js
NEWOPERATION('validate', function($) {
	!$.value.name && $.error.push('name');
	!$.value.email && $.error.push('email');
	$.callback();
});
```

### $.controller

Type: `property`

The controller passed to the operation, or `undefined`.

Returns: `Controller`

`$.client` is the same value. Request properties of `$` read from this controller.

Example: Check for a controller
```js
NEWOPERATION('whoami', function($) {
	if ($.controller)
		$.callback($.user);
	else
		$.invalid('401');
});
```

### $.user

Type: `property`

The user of the current request.

Returns: `Object`

Read from the controller, or `null` without a controller. The other request properties work the same way: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` and `$.test`.

Example: Use the user and the query
```js
NEWOPERATION('my_orders', function($) {
	NOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);
});
```

### $.filter

Type: `property`

The query string converted by the `filter` schema of the operation.

Returns: `Object`

The schema is the `filter` argument of `NEWOPERATION()`, for example `'page:Number,q:String'`. Without a schema it returns the raw query. Without a controller it returns an empty object.

Example: Typed query
```js
NEWOPERATION('products', function($) {
	var filter = $.filter;
	$.callback({ page: filter.page, q: filter.q });
}, 'page:Number,q:String');
```

### $.callback([value])

Type: `method`

Ends the operation and returns a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no |  | The response, or an error. |

Returns: `$`

An `Error` or an `ErrorBuilder` with errors is pushed to `$.error`. You can also call it as `$.callback(err, value)`. When the operation has errors and `repeat` left, it runs again instead.

Example: Return a value
```js
NEWOPERATION('now', function($) {
	$.callback(NOW);
});
```

Example: Pass it as a callback
```js
NEWOPERATION('users', function($) {
	NOSQL('users').find().callback($.callback);
});
```

### $.success([success], [value])

Type: `method`

Ends the operation with a success object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `success` | `Boolean` | no | `true` | The success flag. |
| `value` | `Object` | no |  | A value added as `value`. |

Returns: `$`

Returns `{ success: true }` to the callback. `$.success(value)` adds `value`. `$.success(false)` sets `success` to `false`. In a `RUN()` chain, empty keys are left out.

Example: Return the new id
```js
NEWOPERATION('contact_save', function($) {
	var id = UID();
	$.value.id = id;
	NOSQL('contacts').insert($.value).callback(function() {
		$.success(id);
	});
});
```

### $.invalid([name], [error], [path], [index])

Type: `method`

Ends the operation with an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Error` | no |  | Error name, error message or `Error`. |
| `error` | `String` | no |  | Error message. |
| `path` | `String` | no |  | Path of the field. |
| `index` | `Number` | no |  | Index of the item in an array. |

Returns: `$|Function`

The arguments go to `$.error.push()`. Without arguments it returns a function `function(err)` that you can pass as a callback.

Example: Return an error
```js
NEWOPERATION('login', function($) {
	if (!$.value.email) {
		$.invalid('email', 'Email is required');
		return;
	}
	$.success();
});
```

### $.done([arg])

Type: `method`

Returns a callback that ends the operation with a success object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `arg` | `Boolean|Object` | no |  | `true` adds the response; another value is added as it is. |

Returns: `Function(err, response)`

The returned function `function(err, response)` pushes `err` and calls back, or calls back with `{ success: true }`. With `arg` set to `true`, the response is added as `value`; any other `arg` is added instead of the response.

Example: Return the inserted record
```js
NEWOPERATION('save', function($) {
	NOSQL('contacts').insert($.value).callback($.done(true));
});
```

### $.successful(callback)

Type: `method`

Returns a callback that handles errors for you.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function(a, b, c)` | yes |  | Called when there is no error. |

Returns: `Function(err, a, b, c)`

The returned function `function(err, a, b, c)` calls `$.invalid(err)` when there is an error, otherwise it calls `callback(a, b, c)` with `$` as `this`.

Example: Skip error checks
```js
NEWOPERATION('count', function($) {
	NOSQL('users').count().callback($.successful(function(count) {
		$.callback({ count: count });
	}));
});
```

### $.redirect(url)

Type: `method`

Ends the operation with a redirect.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | Target URL. |

Returns: `$`

When the operation was called with `controller.callback()`, the controller redirects to `url`.

Example: Redirect after logout
```js
NEWOPERATION('logout', function($) {
	$.cookie('session', null);
	$.redirect('/');
});
```

### $.noop([nocustomresponse])

Type: `method`

Ends the operation without calling the callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `nocustomresponse` | `Boolean` | no | `false` | `true` does not call `controller.custom()`. |

Returns: `$`

Use it when the operation answers the request itself. By default it also calls `controller.custom()`, so the framework does not send another response; `true` skips that call.

Example: Answer the request yourself
```js
NEWOPERATION('ping', function($) {
	$.controller.plain('pong');
	$.noop(true);
});
```

### $.cookie(name, [value], [expire], [options])

Type: `method`

Reads or writes a cookie of the current request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Cookie name. |
| `value` | `String` | no |  | New value, or `null` to remove it. |
| `expire` | `String|Date` | no |  | Expiration, for example `'1 day'`. |
| `options` | `Object` | no |  | Cookie options. |

Returns: `String|$`

With only `name` it returns the cookie value. `null` as `value` removes the cookie. Needs a controller.

Example: Write a cookie
```js
NEWOPERATION('remember', function($) {
	$.cookie('lang', $.value.lang, '1 year');
	$.success();
});
```

### $.variables(str, [data])

Type: `method`

Replaces `{key}` placeholders in a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `str` | `String` | yes |  | Text with placeholders. |
| `data` | `Object` | no |  | Values for `{data.key}`. |

Returns: `String`

Supported keys start with `user.`, `data.`, `model.` or `value.`, `query.` and `params.`. Unknown keys are kept. Single or double braces work. It exists on the `$` of operations and tasks.

Example: Build a message
```js
NEWOPERATION('notify', function($) {
	var text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });
	$.callback(text);
});
```

### $.audit([message], [type])

Type: `method`

Writes an audit log entry for the operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | no |  | Audit message. |
| `type` | `String` | no |  | Type of the entry. |

Returns: `$`

Calls `AUDIT($, message, type)` with data from the user, the request and the value. It exists on the `$` of operations and tasks.

Example: Audit a change
```js
NEWOPERATION('remove', function($) {
	$.audit('Removed product ' + $.value.id);
	$.success();
});
```

### $.response

Type: `property`

Results of the previous operations in a `RUN()` chain.

Returns: `Object`

An object with one key per operation that has already ended. Only set inside `RUN()`.

Example: Use a previous result
```js
NEWOPERATION('invoice', function($) {
	var order = $.response.order;
	$.callback({ total: order.value.price });
});
```

### $.meta

Type: `property`

Information about a `RUN()` chain.

Returns: `Object`

`$.meta.items` is the list of names, `$.meta.current` the running operation, `$.meta.prev` the previous one and `$.meta.index` the index of the running operation. Only set inside `RUN()`.

Example: Check the previous operation
```js
NEWOPERATION('save', function($) {
	if ($.meta.prev !== 'check') {
		$.invalid('check');
		return;
	}
	$.success();
});
```

### $.repeated

Type: `property`

How many times the running operation was repeated in a `RUN()` chain.

Returns: `Number`

Starts at `0` for each operation and grows each time the `repeat` option runs it again. Only set inside `RUN()`.

Example: Give up early
```js
NEWOPERATION('fetch', function($) {
	if ($.repeated > 1)
		console.log('Second retry');
	RESTBuilder.GET('https://example.com/data').callback($.callback);
}, 3);
```

### NEWTASK(name, fn)

Type: `method`

Declares a task with named steps.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the task. |
| `fn` | `Function(push)` | yes |  | Declares the steps with `push(step, fn($, value))`. `null` removes the task. |

`fn` receives `push(step, fn)`. Each step receives `$` and the value, and `this` is `$`. `NEWTASK(name, null)` removes the task. Put tasks in the `/tasks/` directory.

Example: A task with two steps
```js
NEWTASK('signup', function(push) {

	push('check', function($, value) {
		if (!value.email) {
			$.invalid('email');
			return;
		}
		$.next('save');
	});

	push('save', function($, value) {
		NOSQL('users').insert(value).callback($.done());
	});

});
```

### TASK(name, step, callback, [options], [value])

Type: `method`

Creates a task and starts it at a step.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the task, or `'name/step'`. |
| `step` | `String` | yes |  | The first step. |
| `callback` | `Function(err, response)` | yes |  | Called when the task ends. |
| `options` | `Controller|Object` | no |  | Controller or `$` object, or the value. |
| `value` | `Object` | no | `{}` | Value for `$.value`. |

Returns: `TaskBuilder` The task, `$`.

`name` and `step` can be one string `'name/step'`; then the arguments are `TASK('name/step', callback, [options], [value])`. A controller or the `$` of a schema, operation or task as `options` shares its request and its errors; any other `options` is used as the value. The step starts on the next tick, so you can add steps with `$.push()` first. Without a step, start it with `$.exec()`.

The name can also be a URL with an optional expiration, for example `'https://example.com/task.js <1 hour>'`. The file is downloaded and cached until it expires.

Example: Run a task
```js
TASK('signup', 'check', function(err, response) {
	console.log(err, response);
}, { email: 'peter@example.com' });
```

Example: From a schema action, with "name/step"
```js
TASK('signup/check', $.callback, $, $.model);
```

### $.next(step, [step2], [...])

Type: `method`

Runs the next step of the task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | yes |  | Name of the step. More names are tried in order. |

Returns: `$`

Runs the first step in the list that exists, first in steps added with `$.push()` and then in the task declaration. When none exists, the task ends. Does nothing after the task ended.

Example: Go to the next step
```js
push('check', function($, value) {
	$.next(value.paid ? 'ship' : 'pay');
});
```

### $.next2([step])

Type: `method`

Returns a callback that goes to the next step.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | no |  | Name of the next step. |

Returns: `Function(err)`

The returned function `function(err)` calls `$.invalid(err)` on an error, otherwise it runs `step`, or ends the task when `step` is empty.

Example: Continue after a write
```js
push('save', function($, value) {
	NOSQL('orders').insert(value).callback($.next2('notify'));
});
```

### $.end([data])

Type: `method`

Ends the task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no | `$.value` | The response. |

Returns: `$`

Calls the task callback with the errors (or `null`) and `data`, or `$.value` when `data` is empty.

Example: End with the value
```js
push('price', function($, value) {
	value.total = value.price * value.count;
	$.end();
});
```

### $.end2([send_value])

Type: `method`

Returns a callback that ends the task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `send_value` | `Boolean` | no | `false` | `true` returns the data of the callback. |

Returns: `Function(err, data)`

The returned function `function(err, data)` calls `$.invalid(err)` on an error, otherwise it ends the task with `data` when `send_value` is `true`, or with `$.value`.

Example: End with the result
```js
push('load', function($, value) {
	NOSQL('orders').one().where('id', value.id).callback($.end2(true));
});
```

### $.success([data])

Type: `method`

Ends the task with a success object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | A value added as `value`. |

Returns: `$`

Ends the task with `{ success: true }`, plus `value` when `data` is set.

Example: End with success
```js
push('notify', function($, value) {
	MAIL(value.email, 'Order', '=?/mails/order', value);
	$.success(value.id);
});
```

### $.done([send_value])

Type: `method`

Returns a callback that ends the task with a success object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `send_value` | `Boolean` | no | `false` | `true` adds the data of the callback as `value`. |

Returns: `Function(err, data)`

The returned function `function(err, data)` calls `$.invalid(err)` on an error, otherwise it ends the task with `{ success: true }`, plus `value: data` when `send_value` is `true`.

Example: Save and finish
```js
push('save', function($, value) {
	NOSQL('orders').insert(value).callback($.done(true));
});
```

### $.invalid(err, [msg])

Type: `method`

Ends the task with an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `String|Error` | yes |  | Error name or `Error`. |
| `msg` | `String` | no |  | Error message. |

Returns: `$`

Pushes the error to `$.error` and ends the task. Does nothing after the task ended.

Example: Stop the task
```js
push('check', function($, value) {
	if (!value.items.length)
		$.invalid('items', 'The order is empty');
	else
		$.next('save');
});
```

### $.push(step, fn)

Type: `method`

Adds a step to this task only.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | yes |  | Name of the step. |
| `fn` | `Function($, value)` | yes |  | The step. |

Returns: `$`

The step is used before a step of the same name in the task declaration. Call it on the task that `TASK()` returns, before the first step runs.

Example: Override a step
```js
var task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });
task.push('save', function($, value) {
	$.success();
});
```

### $.exec(step, [callback])

Type: `method`

Starts the task at a step.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | yes |  | The first step. |
| `callback` | `Function(err, response)` | no |  | Called when the task ends. |

Returns: `$`

Sets the callback when given and runs `step`. Use it with a task created by `TASK(name)` without a step.

Example: Start later
```js
var task = TASK('signup');
task.value = { email: 'peter@example.com' };
task.exec('check', console.log);
```

### $.callback(fn)

Type: `method`

Sets the callback of the task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function(err, response)` | yes |  | The callback. |

Returns: `$`

`fn` is called once when the task ends, with the errors (or `null`) and the response.

Example: Set the callback
```js
var task = TASK('signup');
task.callback(function(err, response) {
	console.log(err, response);
});
task.exec('check');
```

### $.value

Type: `property`

The value shared by all steps of the task.

Returns: `Object`

`$.model` is the same value. Steps also receive it as the second argument. It is an empty object when no value was passed.

Example: Change the value
```js
push('price', function($) {
	$.value.price = 100;
	$.next('save');
});
```

### $.current

Type: `property`

Name of the running step.

Returns: `String`

`$.prev` holds the previous step and `$.name` the name of the task. The request properties (`$.user`, `$.query`, `$.params`, `$.body` and others) read from the controller, like in operations.

Example: Log the step
```js
push('save', function($) {
	console.log($.name, $.prev, '->', $.current);
	$.success();
});
```

### PROMISIFY(fn, [a], [b])

Type: `method` · Since: `0.0.97`

Wraps a function with a callback in a Promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | A function whose last argument is `callback(err, response)`. |
| `a` | `Object` | no |  | First argument for `fn`. |
| `b` | `Object` | no |  | Second argument for `fn`. |

Returns: `Promise`

Calls `fn` with the given arguments and a callback `function(err, response)` as the last argument. The promise resolves with `response` or rejects with `err`. Empty arguments are not passed.

Example: Await a callback
```js
async function count() {
	var self = this;
	try {
		var response = await PROMISIFY(OPERATION, 'users_count');
		self.json(response);
	} catch (err) {
		self.invalid(err);
	}
}
```

Example: Read a file
```js
var body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');
```

### NEWCOMMAND(name, fn)

Type: `method`

Adds a handler for a command.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the command. |
| `fn` | `Function(a, b, c, d)` | yes |  | The handler. `null` removes all handlers. |

A command can have several handlers; each call adds one. `NEWCOMMAND(name, null)` removes all handlers of the command. Run it with `CMD()`.

Example: A command
```js
NEWCOMMAND('clear_prices', function(category) {
	MAIN.prices && delete MAIN.prices[category];
});
```

### CMD(name, [a], [b], [c], [d])

Type: `method`

Runs all handlers of a command.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the command. |
| `a` | `Object` | no |  | First argument. |
| `b` | `Object` | no |  | Second argument. |
| `c` | `Object` | no |  | Third argument. |
| `d` | `Object` | no |  | Fourth argument. |

Passes up to four arguments to each handler. Does nothing when the command has no handler. Built-in commands include `clear_viewscache`, `clear_smtpcache` and `refresh_tms`.

Example: Run a command
```js
CMD('clear_prices', 'books');
CMD('clear_viewscache');
```

### CMD2(name, [a], [b], [c], [d])

Type: `method`

Returns a function that runs a command.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the command. |
| `a` | `Object` | no |  | First argument. |
| `b` | `Object` | no |  | Second argument. |
| `c` | `Object` | no |  | Third argument. |
| `d` | `Object` | no |  | Fourth argument. |

Returns: `Function`

The returned function runs all handlers with the given arguments. When the command has no handler, it returns `NOOP`.

Example: Run a command later
```js
setTimeout(CMD2('clear_viewscache'), 5000);
```

### NEWEXTENSION(code, [callback], [extend])

Type: `method`

Installs an extension from source code or a URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `String` | yes |  | Source code, or a URL. |
| `callback` | `Function(err, module)` | no |  | Called when the extension is installed. |
| `extend` | `Function(module)` | no |  | Called with the module before it is installed. |

`code` is JavaScript that sets `exports`, or a URL to download it from. Optional exports: `id`, `name`, `install(next)`, `make()`, `done()` and `uninstall()`. Without `id` the id is a hash of `name` or the code. An extension with the same id is removed first. The code can also be HTML with a `<script total>` block and `<file name="...">` blocks; `exports.files` then maps each file name to a temporary path. The added `remove()` method uninstalls the extension. Files in the `/extensions/` directory are installed when the app starts.

Example: Install from a string
```js
var code = 'exports.name = \'Hello\';\nexports.make = function() {\n\tROUTE(\'GET /hello/\', function() { this.plain(\'Hello\'); });\n};';

NEWEXTENSION(code, function(err, module) {
	console.log(err, module.id);
});
```

Example: Install from a URL
```js
NEWEXTENSION('https://example.com/extension.js', function(err, module) {
	err && console.error(err);
});
```

### WORKFLOW(declaration, [tasks])

Type: `method`

Creates a small in-memory state machine: named steps that move to each other with `$.next()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `declaration` | `Function` | yes |  | `function($)` that adds the steps. |
| `tasks` | `Object` | no | `{}` | Steps as `{ name: function($, value) }`. |

Returns: `Object` The workflow `$`.

`WORKFLOW()` returns a `$` object and passes it to `declaration($)`, where you add steps with `$.push(name, fn)`. Each step is `function($, value)`. It is a local helper, not a registered task: nothing is stored or named globally.

| Member | What it does |
| --- | --- |
| `$.push(name, fn)` | Adds the step `fn($, value)` |
| `$.next(name, [value])` | Runs the step `name` with `value`; `$.trigger()` is an alias. An unknown name destroys the workflow |
| `$.next2(name)` | Returns `function(value)` that runs `$.next(name, value)`, for callbacks |
| `$.invalid(err)` | Calls `$.error(err, $)` when you set it, then destroys the workflow |
| `$.current`, `$.prev` | The name of the current and of the previous step |
| `$.tasks` | The steps, as an object |
| `$.clone()` | A new workflow with the same steps |
| `$.destroy()` | Ends it; later calls of `$.next()` do nothing |

`declaration` can be `null` when you pass the steps as `tasks`.

Example: Steps in order
```js
var flow = WORKFLOW(function($) {

	$.error = function(err) {
		console.log('Error:', err);
	};

	$.push('load', function($, id) {
		NOSQL('orders').one().where('id', id).callback(function(err, order) {
			if (order)
				$.next('send', order);
			else
				$.invalid('error-orders-404');
		});
	});

	$.push('send', function($, order) {
		MAIL(order.email, 'Your order', 'mails/order', order);
		$.destroy();
	});

});

flow.next('load', '123');
```
