# Headless engine

> Run the Gantt's scheduling engine without a DOM with createGanttProject, in Node, workers and tests, to schedule, edit, validate and convert projects on a server.

`createGanttProject()` is the scheduling engine of the Gantt without the user interface. It needs no DOM, so it runs in Node, Deno, Bun, web workers and unit tests. Use it to schedule projects on a server, recalculate dates after an API request, validate imports, or generate MS Project files in a background job.

## Create a project

```ts
import { createGanttProject } from '@birchui/gantt';

const project = createGanttProject({
  name: 'Website relaunch',
  projectStart: '2026-12-07',
  timeZone: 'Europe/London',
  calendars: [
    {
      id: 'studio',
      workingHours: [
        { from: '09:00', to: '12:30' },
        { from: '13:30', to: '17:30' },
      ],
      exceptions: [{ start: '2026-12-24', end: '2027-01-01', name: 'Studio closed' }],
    },
  ],
  calendarId: 'studio',
  hoursPerDay: 7.5,
  tasks,
  dependencies,
});

project.updateTask('design', { duration: 10 });

const { taskIds } = project.getCriticalPath();
const finish = project.getProjectRange().end;
const xml = project.toMSProjectXML();
```

The project is scheduled as soon as it is created. It accepts the scheduling options of the widget:

| Option | Description |
| --- | --- |
| `tasks`, `dependencies` | The project data. |
| `calendars`, `calendarId` | Working calendars and the project calendar. |
| `projectStart`, `timeZone`, `hoursPerDay`, `daysPerWeek`, `unlinkedTaskStart` | As in the widget; see [Scheduling](https://docs.birchui.com/gantt/scheduling.md) and [Calendars](https://docs.birchui.com/gantt/calendars.md). |
| `autoSchedule` | `false` stops edits from moving successors until `schedule()`. |
| `historyLimit` | Undo steps kept (default 100). |
| `today` | A fixed "today". |
| `name` | Project name, written to MS Project XML and `toJSON()`. |
| `warn` | `(message) => void` to collect warnings instead of logging them with `console.warn`. |

The headless engine does not check a license, show a watermark or touch `window`.

## Read the schedule

| Member | Description |
| --- | --- |
| `getTask(id)`, `getTasks()` | Scheduled copies of tasks, with `start`, `end`, `wbs`, slack and `isCritical`. See [Scheduled fields](https://docs.birchui.com/gantt/tasks.md#scheduled-fields). |
| `getTaskData(id)` | Your task exactly as stored, without scheduled fields. |
| `getDependencies()`, `getDependency(id)` | Links. |
| `getCriticalPath()`, `getSlack(id)`, `getProjectRange()` | Critical path, slack and project dates. |
| `lastResult` | The `ScheduleResult` of the latest scheduling run: `changed`, `ms`, `cycles`, `conflicts`, `projectStart`, `projectEnd`. |
| `order()`, `parentOf(id)`, `childrenOf(id)`, `hasChildren(id)`, `depthOf(id)`, `wbsOf(id)` | The task tree. |
| `predecessorText(id)` | The predecessor text the grid shows, such as `'1.2SS+2d'`. |

## Edit like a user

The project offers the same operations the Gantt's interface uses, with the same rules:

| Method | Description |
| --- | --- |
| `moveTask(id, start)` | Move a task as a drag does, setting a **start no earlier than** constraint. Returns `false` when nothing changes. |
| `resizeTask(id, end)` | Change the finish as a resize does. |
| `setPercentDone(id, percent)` | Set progress (not on summaries). |
| `editField(id, field, text)` | Apply text as the grid would, for `'name'`, `'start'`, `'end'`, `'duration'`, `'percentDone'` or `'predecessors'`. Returns `{ isApplied, errors }`. |
| `addTask`, `updateTask`, `removeTask`, `indent`, `outdent` | As on the widget. |
| `addDependency`, `updateDependency(id, { type?, lag?, lagUnit? })`, `removeDependency` | Links. `addDependency` returns `undefined` when the link breaks a [rule](https://docs.birchui.com/gantt/dependencies.md#rules-and-validation). |
| `checkDependency(from, to, type)` | The reason a link would be refused, or `null` when it is allowed. |

`editField` makes the headless engine a good back end for bulk edits from spreadsheets or chat commands, because it accepts the same text people type:

```ts
const result = project.editField('content', 'predecessors', '1.2SS+2d, 1.1');
if (!result.isApplied && result.errors.length) throw new Error(result.errors.join('; '));

const problem = project.checkDependency('golive', 'discovery', 'FS');
```

Here `problem` is `'this link would create a dependency loop'`.

## Batch changes

Each edit is one undo step and one scheduling run. Wrap several edits in `transaction(label, fn)` to make them one step that is scheduled once:

```ts
project.transaction('Apply change request CR-118', () => {
  project.updateTask('build', { duration: 12 });
  project.addDependency({ from: 'qa', to: 'golive', type: 'FS', lag: 1 });
  project.moveTask('content', '2026-12-16');
});
```

`undo()`, `redo()`, `canUndo()`, `canRedo()` and `clearHistory()` work as in the widget.

## Events

```ts
project.on('scheduled', ({ changed, ms, conflicts }) => metrics.timing('gantt.schedule', ms));
project.on('cycleDetected', ({ cycles }) => alerting.warn('Dependency loop in project', cycles));
```

`scheduled` fires after every scheduling run with the `ScheduleResult`; `cycleDetected` fires when a full run finds new dependency loops.

## Load and convert

| Method | Description |
| --- | --- |
| `load(tasks, dependencies?)` | Replace the tasks (and links) and reschedule. |
| `configure(partial)` | Change any option, such as calendars or `hoursPerDay`, and reschedule. |
| `schedule()` | Run a full forward and backward pass. |
| `toJSON()`, `fromJSON(data)` | JSON in and out, as on the widget. |
| `toMSProjectXML()`, `fromMSProjectXML(xml)` | MS Project XML in and out. |

A server function that analyses an uploaded MS Project file and returns its finish date and critical path:

```ts
import { createGanttProject } from '@birchui/gantt';

export function analyseProjectFile(xml: string) {
  const warnings: string[] = [];
  const project = createGanttProject({ timeZone: 'Europe/London', warn: (message) => warnings.push(message) });
  try {
    project.fromMSProjectXML(xml);
  } catch {
    return { error: 'The file is not MS Project XML.' };
  }
  const { taskIds } = project.getCriticalPath();
  return {
    finish: project.getProjectRange().end,
    critical: taskIds.map((id) => project.getTask(id)?.name),
    conflicts: project.lastResult?.conflicts ?? [],
    warnings,
  };
}
```

Call it from any HTTP framework with the request body as text.

## Keep server and browser in step

The widget and the headless engine share one engine, so a schedule computed on the server is the same one users see. A common setup:

1. The browser saves edits from `taskChange` and `tasksScheduled` (or `toJSON()`).
2. The server loads the project into `createGanttProject`, applies the change with the same method, and stores `toJSON()`.
3. Other clients reload with `fromJSON`.

## Next steps

- [Performance](https://docs.birchui.com/gantt/performance.md) for timings of large projects.
- [MS Project XML](https://docs.birchui.com/gantt/ms-project.md) for the exchange format.
