# Headless formula engine

> Run the spreadsheet's formula engine without a DOM, in Node or a worker, to recalculate models on a server, validate submissions and test workbooks.

`createFormulaEngine()` is the formula engine behind the spreadsheet component, without any user interface. It runs in Node, in workers and in tests, with the same functions, dynamic arrays and recalculation, and it reads and writes the same [workbook JSON](https://docs.birchui.com/spreadsheet/sheets.md#the-workbook-json).

Use it to:

- recalculate a pricing or quoting model on the server, so the price a customer sees is computed by the model your team maintains in a spreadsheet;
- re-check figures submitted from a browser before saving them;
- batch-process workbooks, for example converting [xlsx files](https://docs.birchui.com/spreadsheet/xlsx.md) and refreshing their results;
- test the formulas of a model in your CI.

## A first engine

```ts
import { createFormulaEngine } from '@birchui/spreadsheet';

const engine = createFormulaEngine({ sheets: ['Commission'] });

engine.setRange('Commission', 'A1', [
  ['Rep', 'Sales', 'Rate'],
  ['Maya Patel', 182000, '=IF(B2>150000, 7%, 5%)'],
  ['Liam Chen', 96500, '=IF(B3>150000, 7%, 5%)'],
]);
engine.setCell('Commission', 'D2', '=SUMPRODUCT(B2:B3, C2:C3)');

engine.getValue('Commission', 'D2');
```

`getValue` returns `17565`. Values are recalculated automatically after every change, and only the formulas that depend on it are evaluated.

## Recalculating a pricing model on a server

Design the model in the spreadsheet component, save it with `toJSON()`, and load it on the server. Each request sets the inputs and reads the outputs:

```ts title="server/pricing.ts"
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { createFormulaEngine, isCellError, type WorkbookJSON } from '@birchui/spreadsheet';

const model = JSON.parse(await readFile('models/pricing-2026.json', 'utf8')) as WorkbookJSON;

const engine = createFormulaEngine();
engine.fromJSON(model);

function quote(plan: string, seats: number, months: number) {
  engine.batch(() => {
    engine.setCell('Quote', 'B1', plan);
    engine.setCell('Quote', 'B2', seats);
    engine.setCell('Quote', 'B3', months);
  });
  const [[billableSeats], [listPrice], [discount], [total]] = engine.getRange('Quote', 'B5:B8');
  if (isCellError(total)) throw new Error(`Pricing model returned ${total.code}`);
  return { plan, billableSeats, listPrice, discount, total };
}

createServer(async (request, response) => {
  const url = new URL(request.url ?? '/', 'http://localhost');
  const result = quote(url.searchParams.get('plan') ?? 'Starter', Number(url.searchParams.get('seats') ?? 1), 12);
  response.setHeader('Content-Type', 'application/json');
  response.end(JSON.stringify(result));
}).listen(3000);
```

The model behind it has a `Prices` sheet with a price table and volume discounts, and a `Quote` sheet that does the maths:

| Cell | Content |
| --- | --- |
| `Quote!B1`, `B2`, `B3` | The inputs: plan, seats and billing months. |
| `Quote!B5` | `=MAX(B2, XLOOKUP(B1, Prices!A2:A4, Prices!C2:C4))`, the billable seats after the plan's minimum. |
| `Quote!B6` | `=B5 * XLOOKUP(B1, Prices!A2:A4, Prices!B2:B4) * B3`, the list price. |
| `Quote!B7` | `=XLOOKUP(B5, Prices!E2:E4, Prices!F2:F4, 0, -1)`, the volume discount for the seat count. |
| `Quote!B8` | `=ROUND(B6 * (1 - B7), 2)`, the total. |

With a Business plan at $29 per seat and a minimum of 5 seats, and Enterprise at $49 per seat with a 10% discount from 50 seats, `quote('Business', 10, 12)` returns a total of 3480 and `quote('Enterprise', 120, 12)` a list price of 70560 and a total of 63504.

`batch()` applies the three inputs together and recalculates once. Node runs one request at a time on the engine, so sharing one instance is safe. If requests may run concurrently in workers, give each worker its own engine, or create a fresh engine per request with `fromJSON()`.

## Options

**`FormulaEngineOptions`** (interface from `@birchui/spreadsheet`, full reference: https://docs.birchui.com/api/spreadsheet.md)

```ts
interface FormulaEngineOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `sheets?` | `string[]` |  |
| `dynamicArrays?` | `boolean` |  |
| `iterative?` | `boolean` |  |
| `maxIterations?` | `number` |  |
| `maxChange?` | `number` |  |
| `now?` | `() => Date` |  |
| `random?` | `() => number` |  |
| `resolveImage?` | `(request: ImageRequest) => string \| undefined` |  |
| `functions?` | `CustomFunctionSet` |  |

| Option | Default | Effect |
| --- | --- | --- |
| `sheets` | `['Sheet1']` | Sheet names to create. Ignored once you call `fromJSON()`. |
| `dynamicArrays` | `true` | `false` turns spilling off and uses implicit intersection, like older Excel versions. |
| `iterative`, `maxIterations`, `maxChange` | off, 100, 0.001 | [Iterative calculation](https://docs.birchui.com/spreadsheet/formulas.md#circular-references) for circular models. |
| `now` | the system clock | The time used by `NOW` and `TODAY`. |
| `random` | `Math.random` | The random source for `RAND`, `RANDBETWEEN` and `RANDARRAY`, for reproducible results in tests. |
| `functions` | none | [Custom functions](https://docs.birchui.com/spreadsheet/formulas.md#custom-functions) to register, as a map or an array of definitions. |

```ts
const engine = createFormulaEngine({
  now: () => new Date(2026, 11, 31),
  random: () => 0.5,
});
```

## API

**`FormulaEngine`** (interface from `@birchui/spreadsheet`, full reference: https://docs.birchui.com/api/spreadsheet.md)

```ts
interface FormulaEngine
```

| Property | Type | Description |
| --- | --- | --- |
| `readonly sheetNames` | `readonly string[]` |  |
| `readonly evaluationCount` | `number` |  |
| `readonly pendingAsync` | `number` |  |
| `addSheet` | `(name?: string, index?: number) => string` |  |
| `removeSheet` | `(name: string) => void` |  |
| `renameSheet` | `(from: string, to: string) => void` |  |
| `moveSheet` | `(name: string, index: number) => void` |  |
| `setCell` | `(sheet: string, address: string, input: CellInput) => void` |  |
| `setFormula` | `(sheet: string, address: string, formula: string) => void` |  |
| `getValue` | `(sheet: string, address: string) => CellValue` |  |
| `getFormula` | `(sheet: string, address: string) => string \| undefined` |  |
| `getRange` | `(sheet: string, range: string) => CellValue[][]` |  |
| `setRange` | `(sheet: string, topLeft: string, rows: CellInput[][]) => void` |  |
| `clearRange` | `(sheet: string, range: string) => void` |  |
| `insertRows` | `(sheet: string, row: number, count?: number) => void` |  |
| `deleteRows` | `(sheet: string, row: number, count?: number) => void` |  |
| `insertColumns` | `(sheet: string, column: number \| string, count?: number) => void` |  |
| `deleteColumns` | `(sheet: string, column: number \| string, count?: number) => void` |  |
| `insertCells` | `(sheet: string, range: string, shift?: 'right' \| 'down') => void` |  |
| `deleteCells` | `(sheet: string, range: string, shift?: 'left' \| 'up') => void` |  |
| `sortRange` | `(sheet: string, range: string, keys: { column: number \| string; descending?: boolean }[]) => void` |  |
| `defineName` | `(name: string, formula: string, sheet?: string) => void` |  |
| `removeName` | `(name: string, sheet?: string) => boolean` |  |
| `addTable` | `(sheet: string, range: string, options?: CreateTableOptions) => string` |  |
| `removeTable` | `(name: string) => void` |  |
| `getTables` | `(sheet?: string) => TableJSON[]` |  |
| `addDataTable` | `(sheet: string, table: DataTableJSON) => void` |  |
| `removeDataTable` | `(sheet: string, range: string, options?: RemoveDataTableOptions) => boolean` |  |
| `getDataTables` | `(sheet?: string) => DataTableInfo[]` |  |
| `evaluate` | `(formula: string, context?: { sheet?: string; address?: string }) => CellValue \| CellValue[][]` |  |
| `validateFormula` | `(formula: string) => string \| undefined` |  |
| `copyFormula` | `(formula: string, from: string, to: string) => string` |  |
| `recalculate` | `() => RecalculatedEvent` |  |
| `batch` | `<T>(fn: () => T) => T` |  |
| `on` | `<K extends keyof FormulaEngineEvents>(event: K, listener: (payload: FormulaEngineEvents[K]) => void) => () => void` |  |
| `toJSON` | `() => WorkbookJSON` |  |
| `fromJSON` | `(json: WorkbookJSON) => void` |  |
| `applyOperation` | `(operation: SheetOperation) => boolean` |  |
| `insertPivotTable` | `(sheet: string, pivot: PivotTableJSON) => void` |  |
| `removePivotTable` | `(name: string) => boolean` |  |
| `getPivotTables` | `(sheet?: string) => PivotTableJSON[]` |  |
| `refreshPivotTables` | `() => number` |  |
| `registerFunction` | `(name: string, impl: CustomFunctionImpl, options?: CustomFunctionOptions) => void` |  |
| `unregisterFunction` | `(name: string) => boolean` |  |
| `listFunctions` | `() => FunctionInfo[]` |  |
| `whenCalculated` | `() => Promise<void>` |  |

### Cells

| Method | Purpose |
| --- | --- |
| `setCell(sheet, address, input)` | Sets a cell. Strings are interpreted like typed input, so `'=A1*2'` is a formula, `'7%'` the number 0.07 and `'2026-03-15'` a date serial. A `Date` becomes a serial and `null` clears the cell. |
| `setFormula(sheet, address, formula)` | Always stores a formula. |
| `setRange(sheet, topLeft, rows)` | Sets a block of cells from a 2D array, with one recalculation. |
| `getValue(sheet, address)`, `getRange(sheet, range)` | Read results. `getRange` with whole columns, such as `A:C`, stops at the last used row. |
| `getFormula(sheet, address)` | The formula of a cell, or `undefined`. |
| `clearRange(sheet, range)` | Clears values and formulas. |

Unknown sheets and invalid addresses throw an `Error`.

### Structure

`insertRows(sheet, row, count?)` and `deleteRows()` take 1-based row numbers; `insertColumns(sheet, column, count?)` and `deleteColumns()` take a letter or a 1-based number. References adjust as in the component. `sortRange(sheet, range, keys)` sorts by one or more keys, such as `[{ column: 'C', descending: true }, { column: 'A' }]`. `addSheet()`, `removeSheet()`, `renameSheet()` and `moveSheet()` manage sheets, and `sheetNames` lists them.

### Formulas without cells

| Method | Purpose |
| --- | --- |
| `evaluate(formula, context?)` | Evaluates a formula without storing it, optionally as if it were in `{ sheet, address }`. Returns a value, or a 2D array for array results. |
| `validateFormula(formula)` | `undefined` if the formula parses, otherwise a message such as "Expected , or )". Useful for checking user-entered formulas before saving. |
| `copyFormula(formula, from, to)` | The formula as it would read after copying from one cell to another: `copyFormula('=A1+$B$1', 'C1', 'D3')` is `=B3+$B$1`. |
| `defineName(name, formula, sheet?)`, `removeName(name, sheet?)` | [Defined names](https://docs.birchui.com/spreadsheet/formulas.md#defined-names), including `LAMBDA` functions. |
| `registerFunction(name, impl, options?)`, `unregisterFunction(name)` | Add or remove a [custom function](https://docs.birchui.com/spreadsheet/formulas.md#custom-functions) on this engine. Cells that call it recalculate. |
| `listFunctions()` | The built-in functions plus this engine's custom ones, which have `category: 'custom'`. |

```ts
engine.evaluate('=SUM(Prices!B2:B4)');
engine.evaluate('=SEQUENCE(2, 3)');
```

These return `90` and `[[1, 2, 3], [4, 5, 6]]`.

### Custom functions

```ts
const engine = createFormulaEngine({
  functions: { NET_OF_TAX: (amount, rate) => Number(amount) / (1 + Number(rate)) },
});
engine.registerFunction('FX_RATE', async (currency) => rates.get(String(currency)), { async: true });

engine.setFormula('Sheet1', 'B1', '=NET_OF_TAX(1200, 0.2) * FX_RATE("EUR")');
engine.getValue('Sheet1', 'B1');
await engine.whenCalculated();
engine.getValue('Sheet1', 'B1');
```

The first read returns the `#BUSY!` error, the second the number. Registration is per engine: a second engine does not see `NET_OF_TAX`. The rules for names, arguments, results, async caching and errors are the same as in the component and are described under [Custom functions](https://docs.birchui.com/spreadsheet/formulas.md#custom-functions). `evaluate()` returns `#BUSY!` for a formula whose async result is not cached yet; it does not wait.

### Recalculation and events

| Member | Purpose |
| --- | --- |
| `batch(fn)` | Runs `fn` and recalculates once at the end, however many cells it changed. Returns what `fn` returns. |
| `recalculate()` | Recalculates every formula, for example after changing what `now` returns, and calls async custom functions again instead of reusing their cached results. Returns `{ changedCount, evaluated, ms }`. |
| `evaluationCount` | The total number of formula evaluations so far, handy in performance tests. |
| `on('recalculated', listener)` | Called after each recalculation with `{ changedCount, evaluated, ms }`. |
| `on('circularReference', listener)` | Called with the `cells` involved when a circular reference is found. Those cells show 0. |
| `whenCalculated()` | A promise that resolves when no async custom function is outstanding. It resolves at once when none is. |
| `pendingAsync` | The number of async custom function calls that have not settled. |
| `on('functionError', listener)` | Called with `{ name, sheet, address, message, error }` when a custom function throws or its promise rejects. The cell shows `#VALUE!`. With no listener the error is logged with `console.error`. |
| `on('asyncResolved', listener)` | Called with `{ pending }` after an async custom function settled and its dependants were recalculated. |

### Pivot tables

| Method | Description |
| --- | --- |
| `insertPivotTable(sheet, definition)` | Adds a [pivot table](https://docs.birchui.com/spreadsheet/pivot-tables.md) from a `PivotTableJSON` and writes its cells. The definition needs a `name`. |
| `refreshPivotTables()` | Calculates every pivot table again from the current values and rewrites its cells. Returns the number of pivot tables written. The engine does not refresh them by itself. |
| `getPivotTables(sheet?)` | The definitions, with the `range` each one last wrote to. |
| `removePivotTable(name)` | Removes a pivot table and clears its cells. Returns `false` when there is none with that name. |

Pivot tables in a workbook you load are calculated when they have no `range` yet. Layouts, column subtotals and label, value and date filters work as in the component; a date filter by period uses the `now` option. [`GETPIVOTDATA`](https://docs.birchui.com/spreadsheet/pivot-tables.md#getpivotdata) reads a pivot value in a formula and is calculated from the current source data, so it does not wait for `refreshPivotTables()`.

### Data tables

| Method | Description |
| --- | --- |
| `addDataTable(sheet, { range, rowInputCell?, columnInputCell? })` | Adds a [data table](https://docs.birchui.com/spreadsheet/data-tools.md#data-tables) and fills its result cells. Throws a `DataTableError` for a definition that cannot work. |
| `removeDataTable(sheet, range, options?)` | Removes the data tables that touch `range` and clears their results, or keeps them with `{ keepValues: true }`. Returns `false` when there is none. |
| `getDataTables(sheet?)` | The definitions, each with its `sheet`. |

The results are refreshed as part of every recalculation that touched the table's input values, its formulas or their precedents, and they count towards `changedCount`. A write into a result cell is not rejected: the table puts its result back in the same recalculation.

### Saving and loading

`toJSON()` returns a `WorkbookJSON` with every sheet, value, formula and name; `fromJSON(json)` loads one, including the files the component saves. The engine keeps styles, layout and rules in the JSON it loads and writes them back out, but does not use them in calculations.

`applyOperation(operation)` applies one [collaboration operation](https://docs.birchui.com/spreadsheet/collaboration.md#operations) as the component would, which is how a server keeps the current workbook. It returns `false` when the operation does not fit the workbook, such as an edit on a sheet that does not exist, and throws a `TypeError` for a malformed one.

## Testing a model

```ts title="test/pricing-model.test.ts"
import { readFile } from 'node:fs/promises';
import { describe, expect, it } from 'vitest';
import { createFormulaEngine, type WorkbookJSON } from '@birchui/spreadsheet';

const model = JSON.parse(await readFile('models/pricing-2026.json', 'utf8')) as WorkbookJSON;

describe('pricing model', () => {
  it('applies the 10% volume discount from 50 seats', () => {
    const engine = createFormulaEngine();
    engine.fromJSON(model);
    engine.setRange('Quote', 'B1', [['Enterprise'], [120], [12]]);
    expect(engine.getValue('Quote', 'B8')).toBe(63504);
  });
});
```

## Licensing

The headless engine does not check a license key and never shows a watermark, because it has no user interface. Using it in production is covered by your Spreadsheet license, like the component. The [xlsx conversion functions](https://docs.birchui.com/spreadsheet/xlsx.md#without-the-component) take a `licenseKey` that they pass to the Excel Engine.
