Skip to content
Spools
Documentation
On this page

Modules

A module is a feature set that plugs into a Spool: a package, or a folder of your own, written only with the framework's public APIs. Time tracking, field visits, approvals: each can be a module that any Spool lists, instead of code one app keeps to itself. The framework never learns a module's nouns.

A module can bring:

Part What it is
Config Objects of its own (with fields, views, actions), fields and actions on objects others define, roles, guides, automations
Server code Hooks, handlers, run-target kinds, integrations, marketing networks, an email transport, a role or scope source
Private tables Tables that are not CRM objects: no page, no search, not reachable by the assistant
Settings modules.<name> in crm.config.json, checked with the module's own schema
Browser half Panels on record pages and Home, and links in the sidebar
Pages and endpoints Route options and handlers the app mounts with a small route file each, as it does the framework's

The example used on this page is examples/modules/approvals: records of an object the app chooses are sent for approval, and someone approves or rejects each request.

Use a module#

List its server half in src/spool.server.ts, in the order you want its hooks to run:

ts
import { approvals } from '@acme/spools-approvals'export default defineSpool({  crm,  extensions,  modules: [approvals],  auth: clerk(),  database: postgres(),})

Give it its settings in crm.config.json, under its name:

json
"modules": {  "approvals": { "object": "deals" }}

List its browser half in src/spool.ui.ts, in the same order, and make sure your src/routes/__root.tsx puts SpoolUiProvider around the document. A new Spool's does; one made before modules adds it (Upgrading):

ts
// src/spool.ui.tsimport { approvalsUi } from '@acme/spools-approvals/ui'import { defineSpoolUi } from '@swirls/spools/ui/slots'export const ui = defineSpoolUi({ modules: [approvalsUi] })
tsx
// src/routes/__root.tsx<AuthClientProvider clients={authClients} id={brand?.auth}>  <SpoolUiProvider ui={ui}>    <html lang="en">...</html>  </SpoolUiProvider></AuthClientProvider>

Then:

sh
bun run crm:gen      # the schema now has the module's objects, fields and tablesbunx spools modules  # what each module adds, and the route files it needsbun run db:push      # if DATABASE_URL is set

spools modules exits 1 until every page and endpoint the modules have is mounted, and prints each missing file. For the example:

tsx
// src/routes/_crm/approvals.tsximport { approvalsPage } from '@acme/spools-approvals/pages'import { createFileRoute } from '@tanstack/react-router'export const Route = createFileRoute('/_crm/approvals')(approvalsPage)

How the parts are put together#

defineSpool puts the modules and the app together when the server starts, and spools gen does the same, so the schema and the server always agree.

  • Order. Modules are taken in the order modules lists them, then the app. A module's objects come after the app's in the sidebar; its automations run before the app's.

  • Nothing is defined twice. Two contributors may not define the same object, field of one object, action of one object, role, guide, handler, run-target kind, integration, marketing network, table or route. The Spool refuses to start, and spools gen refuses to write, with a message that names both:

    text
    objects.memos is defined by module "notes" and by module "memos". Only one of them can be used

    A module may not replace a built-in run-target kind (swirls, campaign, local). The email transport, the role source, the scope source, files.location and marketing.canManage are one contributor's each.

  • The app wins only where it says so. When the app defines what a module defines, the app's is used only if overrides in defineSpool names it. Anything else is refused:

    ts
    defineSpool({  crm,  modules: [approvals],  overrides: ['objects.approvalRequests', 'handlers.approvalsApprove'],  ...})
    Path The app's replaces
    objects.<key> The module's object: the app's keys over the module's, fields by key
    objects.<key>.fields.<field> A field a module adds to the app's object: the module's is left out
    objects.<key>.sections.<section> A section a module adds to the app's object: the module's is left out
    roles.<key>, guides.<key> The module's role or guide
    handlers.<name>, runTargets.<kind>, integrations.<id> The module's code of that name
    marketing.posts.<key>, marketing.ads.<key> The module's network
    email, roles, scopes, files.location, marketing.canManage The module's

    The compiler knows which paths a module's fixed config gives, and refuses one it doesn't. A path that names nothing is refused when the Spool is defined, so a typo can't hide a clash. Two modules that define the same thing can't be reconciled by the app: one of them has to go.

  • The whole is checked. The config with every module's part in it is checked against the contract, as crm.config.json alone was: a module's relation may point at the app's object, and the app's role may hide a module's object.

  • Record rules, role access and live updates come along. A module's objects carry unique, lock, appendOnly and signals, its fields (its own, and those it adds to others' objects) immutable, readonly, audit and untrusted, and its roles access (Record rules, Roles). It may add uniqueness rules to an object it doesn't own, over its fields or the object's own, with extend.<object>.unique: a rule of a name another contributor's rule on that object has is refused, naming both (objects.<object>.unique.<name>). assistant: { deny: [...] } adds objects to those the tool API never reaches, beside the app's. spools rules checks the composed config's rules, and spools modules lists what each module adds of them.

  • Record page sections come along too. A module's own objects carry their sections, and a module adds sections to an object it doesn't own with extend.<object>.sections, after the object's own, in the order the modules are listed. A section may name any contributor's fields of the object, and is checked on the composed config: a field in two sections, whoever added them, is refused. A section key another contributor uses on that object is refused, naming both (objects.<object>.sections.<key>); the app keeps its own by naming that path in overrides. A role's record entry, the app's or a module's, may name any of them.

Hooks compose#

Every contributor's hooks run, modules in the order listed, then the app's.

  • beforeCreate, beforeUpdate, beforeDelete run one after the other. Each before* value hook is handed the values the one before it returned. A hook that throws refuses the change: nothing is written or removed, the hooks after it don't run, and staff see its message.
  • afterCreate, afterUpdate, afterDelete all run, even when one before them throws. The change stays either way. If any threw, the first failure is reported as it would be with one hook ("Saved, but a step after it failed"), and the config's automations don't run.

The rules for record scopes and for work bound to one record are the same for a module's hooks as for the app's (Hooks and record scopes): they run with the access of whoever caused the change, role access included, and reach further only through asSystem.

Write a module#

A module has a server half and, if it shows anything, a browser half. Keep them in separate files: the server half must never reach the browser bundle, and the browser half never the server's code.

text
approvals/  settings.ts              defineModuleSettings: modules.approvals in crm.config.json  tables.ts                moduleTable: its private tables  approvals.server.ts      defineModule: config, extensions, tables, routes  approvals.functions.ts   server functions its page and panels call (crmHandler)  api.ts                   endpoint handlers (apiRoute)  pages.tsx                page route options  ui.tsx                   defineModuleUi: panels and sidebar links

Name the server half *.server.ts: TanStack Start refuses to let browser code import a file named so, which keeps it out of the browser bundle even by mistake. The app imports it only from src/spool.server.ts. Server functions go in a *.functions.ts file that exports nothing else, as the framework's do: the browser half imports them, and the compiler keeps their bodies on the server.

The server half#

ts
import { createRecord, moduleTables, updateRecord } from '@swirls/spools/extensions'import { defineModule } from '@swirls/spools/module'import { settings } from './settings'import { Decisions } from './tables'export const approvals = defineModule({  name: 'approvals', // camelCase: its settings key and the start of its tables' names  label: 'Approvals',  settings,  tables: [Decisions],  // A fixed part of the config is `config: { ... }`. This one depends on the settings.  configure: ({ object }) => ({    objects: { approvalRequests: { label: 'Approval request' /* fields, views, actions */ } },    extend: {      // A field and an action on the object the app chose. Its key must be new there.      [object]: {        fields: {          approval: { type: 'select', options: [{ value: 'pending' }, { value: 'approved' }] },        },        actions: [{ id: 'requestApproval', label: 'Request approval', run: 'approval:request' }],      },    },    roles: { approver: { label: 'Approver' } },    automations: [      { on: 'approvalRequests.updated', when: { status: ['approved'] }, run: 'approval:settle' },    ],  }),  extensions: {    handlers: { approvalsApprove: async (ctx) => ({ message: 'Approved' }) },    runTargets: { approval: { run: async (name, ctx) => ({ message: 'Done' }) } },    hooks: { beforeCreate: ({ objectKey, values }) => values },  },  routes: [    {      kind: 'page',      path: '/_crm/approvals',      file: 'src/routes/_crm/approvals.tsx',      from: '@acme/spools-approvals/pages',      export: 'approvalsPage',    },  ],})

extensions is the same contract as src/app/extensions.ts (Extending), and the module's code calls the framework through @swirls/spools/extensions, as the app's does. Handler names and run-target kinds are shared by every contributor, so name them after the module (approvalsApprove).

Settings#

ts
import { z } from 'zod'import { defineModuleSettings } from '@swirls/spools/module'export const settings = defineModuleSettings('approvals', z.object({ object: z.string() }))

They are checked when the Spool is defined, and spools gen puts their JSON Schema under modules.approvals in crm.config.schema.json, so an editor checks them too. Server code reads them with settings.read(), typed by the schema. Settings stay on the server: the browser's copy of the config doesn't have them.

Private tables#

ts
import { moduleTable, table } from '@swirls/spools/module'export const Decisions = moduleTable('approvals', {  model: 'Decision',  name: 'decisions',  columns: {    id: table.id(),    createdAt: table.createdAt(),    requestId: table.text(),    decision: table.text(),    decidedBy: table.optional(table.text()),  },  indexes: [['requestId']],})

It is kept as approvals_decisions (model ApprovalsDecision): the module's name comes first, so two modules can't collide, and a clash with any other table is refused. It is described as the system tables are (Database), goes into the schema with them, and is made by PGlite as the server starts. It is not a CRM object: no page, no hooks or automations, no search, and the assistant's tools can't reach it.

The module reads and writes it with moduleTables, which go through the store, so they work on every database with no SQL:

ts
import { moduleTables } from '@swirls/spools/extensions'await moduleTables.insert(Decisions, {  requestId,  decision: 'approved',  decidedBy: actor?.id ?? null,})const decisions = await moduleTables.find(Decisions, {  where: { requestId },  order: [{ by: 'createdAt', dir: 'asc' }],})

find, first, count, insert, update and remove take only a module's table, and only while the Spool uses that module. A private table has no record scope: in a Spool with record scopes it is shared, as an adapter's tables are. Under a grant made for one record it is reachable, as a connection's token is: it holds no record.

Record rules, role access and change signals are about CRM records, and a private table holds none: no unique rule, lock or audit of the config reaches it (give it a unique of its own, as a system table has), no role's access narrows it, and writing to it touches no change mark. Its own unique index refuses a row as the database does, not as a Conflict.

The browser half#

tsx
import { defineModuleUi } from '@swirls/spools/ui/slots'export const approvalsUi = defineModuleUi({  name: 'approvals',  sidebar: [    {      key: 'queue',      label: 'Approvals',      to: '/approvals',      icon: CheckCircle,      object: 'approvalRequests',    },  ],  home: [    { key: 'waiting', title: 'Waiting for approval', object: 'approvalRequests', Panel: Waiting },  ],  record: [    {      key: 'decisions',      title: 'Approval',      when: ({ objectKey, config }) =>        Object.hasOwn(config.objects[objectKey]?.fields ?? {}, 'approval'),      Panel: Decisions,    },  ],})
Slot Where The component gets
sidebar After the built-in pages, or where ui.nav puts it (a link: label, to, icon)
home On Home, after the counts config
record On a record's page, under its details, for the objects named in objects or that when accepts (every object without either) objectKey, record, config

A sidebar link or a Home panel that names an object is left out for someone whose roles all hide that object or whose role access denies it, and for everyone when the Spool has no such object (the module's server half isn't in src/spool.server.ts). A record's panels go with the record's page: a role that only hides the object from its sidebar still opens the record and sees them, and a role denied the object finds no page. Leaving an entry out is tidiness, not the rule: the module's server functions read through @swirls/spools/extensions, where role access and record scopes are enforced. The app can add entries of its own beside its modules': defineSpoolUi({ modules: [...], home: [...] }). A panel that throws shows a line saying so instead of breaking the page.

Panels get their data from the module's own server functions, written as the app's are (Pages and endpoints of your own):

ts
export const waitingFn = createServerFn({ method: 'GET' }).handler(  crmHandler('approvals.waiting', async () =>    listRecords({ objectKey: 'approvalRequests', where: { status: 'pending' } }),  ),)

Pages and endpoints#

A module exports route options and handlers as the framework's pages/* and api/* do, and lists each in routes with the file the app mounts it with. A page's path may not be an object's list (/_crm/<objectKey>), and two modules can't claim one path or file.

Checks#

What Where it is refused
Two contributors define one thing defineSpool (server start) and spools gen
Settings the module's schema refuses defineSpool and spools gen
Settings for a module that isn't listed defineSpool and spools gen
Settings for a module that takes none defineSpool and spools gen
A module's page where an object's list is, or two modules claiming one path or file defineSpool and spools gen
An override that names nothing defineSpool, and the compiler for a fixed config
A table of another module in tables defineModule
A route file that is missing spools modules (exit 1); spools gen warns