Background work and services
Core's events
A module hears a committed change by listing core's event in the manifest part on, with the subscribe capability. A handler gets the event, with its data in event.data:
| Event | event.data |
|---|---|
entries.entry.saved, .published, .unpublished, .deleted (to the trash) | { collection, entry }: the entry at the version the event is about, or entry: null once that version is purged. The entry's id is event.subject.id. Pages are a collection of the website module, so these cover pages too. |
media.file.uploaded | { filename, mime, media }; media is null once the item is gone |
paths.addresses.moved | { moves, live }: where published entries with an address moved, and the paths that are live now (see Where entries live) |
packages.module.switched | { plugin, enabled, redirectItemsTo, itemPaths }: a module was switched on or off, and where the admin sent its item pages while it is off. A module never hears its own switch-off. |
team.member.email-changed | { from, to } (lower case; the member is event.subject.id). For a module whose own records hold the address. Experimental, full view only: there is no webhook view, because addresses are personal data. |
packages.module.settings-changed | { plugin, changed }: the names of the settings that changed, never their values |
capabilities: { subscribe: {} },
on: {
'packages.module.settings-changed': async (ctx, event) => {
const { plugin, changed } = event.data
if (plugin === 'appointments' && changed.includes('reminderHours')) await replanReminders(ctx)
}
}
event.data is typed for these events, so a handler reads it without a cast: EventPayloads from @shadestack/module-sdk/server names each event's data, and EventPayload<'paths.addresses.moved'> gives one. Written as an object, an entry names its delivery ({ handler, delivery: 'durable' }) for its data to be typed. Another module's event reads as unknown, unless that module adds its events to EventPayloads:
declare module '@shadestack/module-sdk/server' {
interface EventPayloads {
'shop.order.paid': { order: string, totalCents: number }
}
}
The types say what SHADE delivers; nothing checks them at delivery.
How handlers run:
- On the worker, after the change. The event is written with the change; each handler runs later on the worker, retried with backoff when it throws. A change that rolls back is never heard. A request that stops after its commit is still heard.
- As the module itself. A handler acts as the module's own actor, with its
uses, never with the rights of the editor who caused the event. List what a handler does inuses: a handler that asks for a rebuild needsrebuild.request. - While the module is off its deliveries wait, and it hears them once it is on again.
- A handler that keeps failing shows on the Errors screen's failed deliveries, where an admin sends it again, and on the module's health card. Tests run deliveries with
runQueuedJobs(ctx)from the testing entry.
errors.error.reported is written right after an error is stored in the error log, without being waited for. Its data is { group, occurrence: 'new' | 'reopened' | 'repeat' }: the group (ErrorGroup from @shadestack/core/schema) with its latest sample, already scrubbed of addresses and query strings. It is for a module that forwards errors to a server the client chose, which should keep site errors (source: 'site') back unless the client turned them on. A handler that fails is only logged, never recorded again, so a broken forwarder cannot feed itself. The event is heard immediately only: in on, give it as { handler, delivery: 'immediate', repair }. Untrusted modules never hear it. For the usual case, use errorForwarding below.
Forwarding errors: errorForwarding
The manifest part errorForwarding fits with SHADE's own error reporting: a trusted module answers per error whether it sent it.
errorForwarding: {
async forward(ctx, error) {
// error: ReportedError — groupId, source, module, name, message, stack, requestId, version, reported, occurrence
const project = routeFor(error.source) // the module's own routing rules
if (!project) return 'declined' // leave it to SHADE's own sending
await ctx.fetch(project.envelopeUrl, { method: 'POST', body: envelopeOf(error) })
return 'sent'
}
}
- The rule. SHADE calls
forwardfirst, with a 5 second limit, when the module is on and loaded.'sent'ends it, and so does'kept': the module's own settings keep the error in the instance (for example a sample rate leaves it out), and SHADE sends nothing either.'declined', a throw or a timeout makes SHADE send the error itself toSHADE_ERROR_REPORTING_DSN, when set. With the module off or failed to load, SHADE sends it. An error goes once. With no DSN, a declined error goes nowhere. - What you get. A
ReportedError(@shadestack/module-sdk/server): the group's scrubbed fields and its id.error.reported === 'browser'means a browser wrote the text. SHADE callsforwardfor those only when the operator setSHADE_ERROR_REPORTING_SITE=true; a module may narrow that with a setting of its own. To hide more before text leaves, callscrub(text, max, { strict: true })(experimental, same entry): it applies SHADE's scrubbing and also hides IBANs ([iban]), UUIDs ([id]) and long numbers such as phone, citizen and customer numbers ([number:<digits>]), and keeps dates, times and Unix timestamps readable. - Who may. One trusted module per instance: two with the part are refused at load, and an untrusted module cannot have it. It has no capability of its own; declare
networkfor the hosts it calls, and send withmoduleFetch(ctx, …). A host the client picks cannot be listed in the manifest:network: { hosts: [], fromSettings: ['server'] }allows the origin of that setting's current value (an address without a key in it, so a DSN cannot be that setting).shade-plugin-error-forwardingis the example. A failure is logged, never recorded again.
Schedules
A schedule (ModuleSchedule) is a short name, when it runs, and run(ctx, signal). It runs by an interval or by a cron expression:
export default defineModule({
name: 'reports',
// …
capabilities: { schedule: {} },
schedules: [
// Every 15 minutes, at :00, :15, :30 and :45 on every instance.
{ name: 'sync', intervalMs: 15 * 60_000, run: ctx => syncOrders(ctx) },
// 03:00 every night in Amsterdam, whatever the site's time zone.
{ name: 'nightly-report', cron: '0 3 * * *', timeZone: 'Europe/Amsterdam', run: ctx => writeReport(ctx) },
// 08:30 on weekdays, in the site's time zone (Settings → Site → Time zone).
{ name: 'morning-digest', cron: '30 8 * * mon-fri', run: (ctx, signal) => sendDigest(ctx, signal) },
// The first day of every quarter, at 06:00 in the site's time zone.
{ name: 'quarterly', cron: '0 6 1 jan,apr,jul,oct *', run: ctx => closeQuarter(ctx) }
]
})
intervalMs: a whole number of milliseconds. The schedule is due at the multiples of its interval since 1970, the same moments on every instance: an hourly one at the top of each hour.cron: five fields: minute (0–59), hour (0–23), day of month (1–31), month (1–12 orjan–dec) and day of week (0–7, 0 and 7 both Sunday, orsun–sat). Each field is*, a value, a range (8-18), a step after*or a range (*/15,8-18/2) or a list of those (1,15). As in every cron, when both day of month and day of week are limited, either matching is enough. Six or seven fields, aliases such as@daily, andL,W,#and?are refused when the module loads, with what is wrong. So is an expression that never runs (0 0 31 2 *).timeZone(cron only): an IANA name such asEurope/AmsterdamorUTC. Without one the schedule runs in the site's time zone and follows a change of that setting from its next due time on. An unknown time zone is refused at load.- Give
intervalMsorcron, not both.
The nights the clocks change. A cron schedule runs by the wall clock of its time zone. In Europe/Amsterdam the clocks jump from 02:00 to 03:00 on the last Sunday of March and go back from 03:00 to 02:00 on the last Sunday of October:
| Schedule | Spring night (02:00 → 03:00) | Autumn night (03:00 → 02:00) |
|---|---|---|
30 2 * * * | 02:30 doesn't exist: runs at 03:00 | 02:30 happens twice: runs once, the first time |
0 4 * * * | 04:00 as always | 04:00 as always |
*/15 * * * * | 02:00–02:45 don't exist: one run at 03:00, then 03:15… | 02:00–02:45 run in the first hour only; the next run is 03:00 winter time |
A schedule that runs every hour or more often pauses for the hour the clocks go back; use intervalMs for work that must keep its pace through that night. A UTC schedule never meets a clock change.
Schedules run on the worker container role (never admin or public), one run at a time across every worker container, each run one transaction, with via: 'cli' and the module's own actor: they may do what the manifest's uses lists and nothing more. A due time is skipped while the previous run goes on, and a missed one (no worker running) is not caught up. signal aborts when the run's Redis lease is lost and another worker may take over: the run's transaction is then rolled back, so stop early and keep the work idempotent. See The worker container role.
Schedules are the schedule capability. An untrusted module's run in its sandbox, at most 5 and never more often than every 15 minutes (Untrusted modules). Declared optional, they skip their ticks while an admin leaves it off. Each schedule is a line of the capability, with its interval or its expression and time zone (nightly-report (cron 0 3 * * * in Europe/Amsterdam)), so an update that changes either asks the admin again (Capabilities).
Hearing events: on
A trusted module hears core's events and other modules' in the manifest part on, by their full names: core's events above, and what another module declares in emits. A loyalty module giving points for a paid order:
export default defineModule({
name: 'points',
// …
capabilities: { subscribe: {} },
on: {
'commerce.order.paid': async (ctx, event) => {
// event: { id, name: 'commerce.order.paid', source: 'commerce', subject, at, causedBy, requestId, data: { … } }
}
}
})
- Each event it hears is a line of its consent (
hears commerce.order.paid): a new one asks again. - It runs on the worker after the sender's change commits, as this module's own actor, retried with backoff (five more tries, from 30 seconds). After those it is on the Errors screen's failed deliveries and counts on its health card.
{ handler, delivery: 'immediate', repair }runs it right after the commit instead, at most once and without a database, for something cheap whose lossrepairsays how to put right.- A module hears at most 50 events, and never its own.
- A listener is always optional: while the sender is off or not installed it hears nothing. A module that cannot work without the sender says so with
requires. - It reaches nothing of the sender's beyond the event: no tables, settings or context.
Publishing events
A trusted module says what happened once, for other modules and for webhooks, by declaring its events in the manifest part emits and emitting them in the transaction of the change they are about (experimental while the event bus is built):
import * as z from 'zod'
import { defineModule, emit, inTransaction } from '@shadestack/module-sdk/server'
export default defineModule({
name: 'commerce',
// …
emits: {
'order.paid': {
description: 'An order was paid',
data: z.object({ order: z.string(), total: z.number(), email: z.string() }),
// What webhooks send: a public shape, or `true` for the data as it is. Left out: not sent to webhooks.
external: z.object({ order: z.string(), total: z.number() })
}
}
})
await inTransaction(ctx, tx => emit(tx, 'order.paid', { type: 'order', id: order.id }, { order: order.number, total, email }))
- It is emitted as
<plugin>.<name>(commerce.order.paid), with an id, who caused it, the request and when. It exists exactly when the change commits. - It is refused outside a transaction, for an event the module doesn't declare, for data that doesn't fit
dataor is over 64 KB (refer to what is large by its id), and as the ninth in a chain of events that subscribers emit while handling one another's (a loop). personal: truesays its external shape holds personal data. Events are found and deleted with a person they name (Privacy).- An event goes to webhooks while the module has the
webhookscapability, in its external shape. - Each event that reaches a durable subscriber counts toward the instance's queued-jobs limit, as a job does: at the limit,
emitis refused (CONFLICT).
Jobs
A job is work done later, once, on the worker, as the module's own actor: an invoice sent to a bookkeeping package after an order, a reminder at a set time. Trusted modules only, with the queue capability:
export default defineModule({
name: 'invoices',
// …
capabilities: {
queue: { queues: { send: { retries: 4, backoffMs: 60_000, concurrency: 2 } }, data: { purpose: 'Invoices to send', personal: 'none' } }
},
jobs: [{
name: 'send',
run: async (ctx, { orderId }: { orderId: string }, { attempt, signal }) => { /* throws to be tried again */ },
giveUp: async (ctx, { orderId }, error) => { /* say where it failed */ }
}]
})
// In the change's transaction (`withDb(ctx, tx)`), so it exists exactly when the change commits:
await enqueueJob(ctx, 'send', { orderId }, { runAt: inAnHour, key: `order:${orderId}` })
await cancelModuleJob(ctx, 'send', `order:${orderId}`)
runAtwaits until then;keykeeps one waiting job per key (the same key again replaces it).cancelModuleJobtakes back a job that waits, including one that waits for its next try. A try running at that moment still ends. A replaced job is skipped the same way.- A try fails by throwing. It is tried again after
backoffMs, doubling to an hour,retriestimes. ThengiveUpruns, and the job is in the error log and on the module's health card. A try longer thantimeoutMs(default 30 s, at most 55 s) counts as failed: itssignalaborts. A try that stopped the worker (out of memory, a crash) counts too, so a job that does that every time ends ingiveUp. - While the module is switched off its jobs wait, kept and counted toward the queued-jobs limit, and run when it is on again. They are never given up for that.
- A job may run twice (a worker that died):
runmust be idempotent. - Uninstalling the module removes its jobs that had not finished.
Finishing work as the team member who started it
A job runs as the module, with what its uses lists. Work a team member starts and a job finishes later, such as the rows of an import, should be done with the member's rights instead. A trusted module starts a member run in its session route and acts as the member from its job (experimental):
// In the session route, for the team member signed in there with the cookie (FORBIDDEN on any other context: a token's
// call, a job, a schedule, another module's request).
const run = await startMemberRun(ctx)
await enqueueJob(ctx, 'batch', { importId, run })
// In the job, for each step: the member as they are now, with their role now.
const as = await actAsTeamMember(ctx, run) // FORBIDDEN once they are no longer active
await createEntry(as, slug, { data, note: 'Imported' })
// When the work is done.
await endMemberRun(ctx, run)
- Call
actAsTeamMemberagain for each step: a role changed meanwhile counts at once, so a step is refused exactly as the member's own save would be. - A run is refused for a module that didn't start it, after
endMemberRun, and for an untrusted module. A module's runs go when it is uninstalled, a member's when the member is deleted. - In a test,
sessionRouteContext(moduleContext(ctx, name))(testing entry) is the context a session route gets.
Data migrations
A data migration is work on the module's stored data done once, on the worker, a batch at a time: for example filling a column a new migration added from the old one, before a later version stops reading the old one. Admins see them as background tasks. Trusted modules only; an untrusted module with dataMigrations is refused. It needs no capability.
import { defineModule, type ModuleDataMigration } from '@shadestack/module-sdk/server'
const prices: ModuleDataMigration = {
version: 1,
run: async (ctx, { cursor, signal }) => {
const after = typeof cursor === 'number' ? cursor : 0
// One batch: up to 500 rows after the last one done, in id order.
const done = await fillPrices(ctx.db, after, 500)
return { cursor: done.lastId, done: done.count < 500, processed: done.count, total: await countProducts(ctx.db) }
}
}
export default defineModule({
name: 'shop',
// …
dataMigrations: { prices }
})
- When it runs. The worker queues the migration at start when it finds one it has not run, or a higher
version. A higher version runs again from the beginning; the same version never runs twice. Each batch runs as the module's own actor. - One batch, one transaction.
ctx.dbis a transaction that also saves the migration's progress: what a batch writes and thecursorit answers are kept together or not at all. A batch cut off leaves nothing, and the next try starts from the last cursor. The cursor is any JSON value,nullfor the first batch. - The answer.
{ cursor, done, processed, total? }: where the next batch starts, whether the migration is done, how many rows this batch did, and how many there are (shown as "120 of 400 rows done"). Anything else fails the batch. - Pace. One batch of any migration at a time per worker, and one batch of a migration at a time on the whole instance.
pauseMs(0–60000, default 1000) waits between batches; the next one then starts within about 5 seconds. Keep a batch well under its 55 second limit. - Stopping.
signalaborts when the worker stops. Whatever the batch did is rolled back, and it runs again on the next worker. - Failing. A batch that throws is tried again after 30 seconds, doubling, 4 more times. Then the migration is failed, with its error, until an admin retries it under Settings → Background tasks, where admins also pause and resume it. While the module is off, its migrations wait without using up tries.
- Uninstalling the module forgets its migrations: installed again, they run again.
- Before removing what a migration copied. The version that stops reading the old column (and drops it in its schema migration) names the migration it needs done in
contractAfter:export default defineModule({ name: 'shop', version: '2.0.0', // … contractAfter: { prices: 1 } })shade-module buildsigns it into the package. Installing that version is refused whilepricesis not done at version 1 or later, so the installed version keeps running and copying; the admin sees which background task to wait for. The API also leaves the module out at start while it is not done (a development folder). A first install has no data to wait for, so nothing is checked. Name only the module's own migrations, and keep the migration in the manifest until every instance has run it. Experimental in 0.1.
kv
A module keeps its own keys and counters with moduleKv(ctx) (get, set with an optional ttlMs, delete, list, an atomic increment, and forAccount(id) for an account's keys), once it declares the kv capability with what it keeps: capabilities: { kv: { data: { purpose, personal, retention? }, maxKeys?, maxValueBytes? } }. Untrusted modules have the same through shade.kv. See kv.
Cache
A trusted module keeps values it can rebuild (a read model, an answer from an outside service) in its own cache with moduleCache(ctx), once it declares the cache capability: capabilities: { cache: {} }, optionally with maxKeys (default 1000, at most 10 000) and maxValueBytes (default 64 KB, at most 1 MB). The cache is in Redis, so every container sees the same values. It holds nothing that must survive (keep that in kv).
import { moduleCache } from '@shadestack/module-sdk/server'
const cache = moduleCache(ctx)
const menu = await cache.wrap(`menu:${locale}`, () => readMenu(ctx, locale), {
ttlMs: 10 * 60 * 1000,
tags: ['collection:menus', 'site']
})
get(key),set(key, value, { ttlMs, tags }),delete(key),clearTag(tag)andwrap(key, read, { ttlMs, tags }).wrapgives the cached value, or runsreadand keeps what it gives (nulltoo); prefer it togetandset.- Keys and the module's own tags are its own: another module can neither read nor clear them.
- Every value expires: an hour by default, a day at most (
ttlMsfrom 1000). Values are JSON. A value overmaxValueBytesis refused byset(VALIDATION);wrapgives it but does not keep it. PastmaxKeysvalues the oldest written goes. - Tags say what a value depends on, at most 20 per value. SHADE clears its content tags when that content changes, in every container at once:
Tag Cleared when collection:<slug>an entry of the collection is saved, published, unpublished, moved to the trash or restored (a version restored too) entry:<slug>:<id>that entry is saved, published, unpublished, moved to the trash or restored mediaa media item is uploaded, changed, replaced, cropped, moved to the trash or restored sitethe site settings change
Any other tag is the module's own:clearTag('prices')after it changed what the tagged values came from. Clearing a content tag yourself is refused. Tag a value with everything it reads: a value that misses a tag is served until it expires. wrapnotes the tags' state before it runsread, so content that changes while it reads is never served afterwards.setnotes it when it is called.- When Redis does not answer,
getgivesnull,wraprunsread, andset,deleteandclearTagdo nothing; SHADE logs it. A content clear SHADE could not make then is made good once Redis answers again: every cached value reads as a miss once. - Untrusted modules have no cache yet: use kv with
ttlMs.
Webhook events
A trusted module tells other systems what happened by emitting an event it declares in emits, with the webhooks capability: emit(txCtx, 'order.paid', { type: 'order', id }, data) in the transaction of the change it is about. Each is sent as <plugin>.<event> to the addresses an admin picked it for, in its external shape, signed and retried by core, exactly when the change commits. Declared optional and skipped, the event is still emitted (other modules may hear it) and sent nowhere. See Webhooks (shade/features/webhooks/README.md in the shade repository).
Realtime updates
A page that keeps a route's answer can hear when it changes. Give a public or account GET route that says what it answers a topic per request, and say when that topic changed: in the change's inTransaction (it goes once that commits) or after it:
{
method: 'GET', path: '/order-status', auth: 'public', rateLimit: { limit: 60, windowMs: 60_000, key: 'ip' },
answer: OrderStatusAnswer,
realtime: request => `order:${request.query.order}`,
handler: (ctx, request) => orderStatus(ctx, request.query.order)
}
// in the order's transaction (inTransaction), or after it:
await sendRealtimeUpdate(ctx, `order:${id}`)
The island's call sets repeat: { every: 30, while: <condition>, realtime: true }. The stream opens only after the route ran for that visitor, and an update says only "ask again", so a topic needs no secrets of its own: whoever may read the route hears it.
Instead of calling sendRealtimeUpdate, map events to topics in the manifest: realtime: { events: { 'commerce.order.paid': event => `order:${event.subject.id}` } } tells the topic's pages right after the event's change commits (each mapped event is a line of the consent). The routes with realtime are the updates channel of the module's realtime capability (realtime: {}; untrusted modules have it too), whose other channel is a trusted module's sockets. See Realtime.
Private files
A trusted module keeps files only it reads (an invoice's PDF) with moduleFiles(ctx): put(key, bytes, { contentType }), get(key), delete(key) and list({ prefix }). SHADE keeps them in Postgres and never serves them: send one to whoever may see it from your own route, after your own check (return new Response(bytes, { headers })). Declare the files capability with the most it may keep together and what it is: files: { maxBytes: 1024 ** 3, data: { purpose: 'shop.privacy.invoices', personal: 'person', retention: 'orders' } } (a file is at most 25 MB). Put a file in the transaction of the change it belongs to, moduleFiles(withDb(ctx, tx)). Email can carry it: attachments: [{ filename, contentType, content: attachmentContent(bytes) }]. See Private files.
Notifications
A trusted module tells a person something with notify(ctx, { to: { email }, subject, text }, { key, at }): now, or at at under its own key (the same key again moves it; cancelNotification(ctx, key) calls it off). Declare capabilities: { notify: { methods: ['email'] } }. Plan it in the transaction of its change, as the appointments module plans a booking's reminder. It goes through the notification methods the person chose (email when none), decided when it goes. See Notify.
Processes
A trusted module keeps work running with processes: [{ name, run(ctx, signal) }] and each process's parameters in the process capability: capabilities: { process: { processes: { presence: { mode: 'singleton' } } } }. The worker container role runs each in a worker thread of its own, as the module's own actor, until signal aborts, and restarts it with backoff when it ends or throws before that. Untrusted modules have none. See Processes.
Thread tasks
A trusted module runs slow work in a worker thread with a time and a memory budget, so a long or runaway run never holds up the API. Declare each task in the manifest part threadTasks, a function of plain data that returns (or resolves to) plain data, and run one with runThreadTask from the server entry:
import { checkAccessibility, type CheckInput } from '@shadestack/a11y'
import { defineModule, runThreadTask } from '@shadestack/module-sdk/server'
export default defineModule({
// …
threadTasks: { accessibility: input => checkAccessibility(input as CheckInput) }
})
// In the module's own code, with the context SHADE gave it:
const result = await runThreadTask(ctx, 'accessibility', input, { timeoutMs: 30_000 })
if (result.status === 'done') use(result.result)
timeoutMsis 1 to 60 000;memoryMbis 64 to 512, 256 when it gives none. The thread loads the module's entry, and with it about 30 MB of SHADE's code.- The result is
{ status: 'done', result },{ status: 'timeout', timeoutMs }or{ status: 'failed', error }(the task threw, ran out of memory, or returned what can't be cloned).runThreadTasknever throws for the task; it throws for a context SHADE didn't make for the module, a task its manifest doesn't have, or a budget out of range. - At most two runs at once in an API process; a run waiting for its turn counts against its budget.
- The thread gets the input and nothing of SHADE's: no database, no context, no Redis and an empty environment. Read what the task needs first and give it in the input; input and result cross as structured clones.
- A module runs only its own tasks. Untrusted modules have none: their code already runs in the sandbox.
- Without the API (a module's tests, scripts) the task runs in the calling thread, its input and result still cloned, and no budget stops it there.
Thread tasks are not a capability: they let a module do nothing it couldn't do in the API's process already.
Logging
Every context SHADE gives a trusted module (the events it hears, its routes, schedules, jobs and processes) has ctx.log, a ModuleLogger: ctx.log.info(message, fields?), warn, error and debug. Each call writes one JSON line to the instance's log with the time, level, message, container role, SHADE version, the request id of what is running and plugin set to your module's name, so the operator can filter by module and follow a request from the API into your job:
on: {
'entries.entry.published': async (ctx, event) => {
ctx.log.info('feed rebuilt', { items: 12, ms: 340 })
}
}
fields is plain data (numbers, text, booleans, small lists and objects). SHADE takes out what is personal or secret before anything is written, as the error log does: email addresses, IP addresses, query strings, tokens and credentials in texts are replaced, and a field named like a body, headers, a cookie, a token, a password, an email address, an IP address or an account is written as [redacted]. Log decisions and counts, never what a visitor typed. The request id is also ctx.requestId, and a job you queue from a request runs under its id. Untrusted modules have no ctx.log yet: what their code writes to the console is logged under their name. See Logs and request ids.
Tracing
When the operator has set an OpenTelemetry exporter, SHADE already makes a span for the events you hear, routes' requests, schedules, jobs, processes and thread tasks, and for every call you make through ctx: ctx.fetch, each ctx.db query (the kind of statement only), each ctx.kv call and enqueueJob. Each has plugin set to your module's name. For your own steps, ctx.trace (a ModuleTrace) runs work in a child span:
const price = await ctx.trace('price check', async () => quote(order), { items: order.lines.length })
It gives back what the work gives back; a throw marks the span failed (its class, never its message) and goes on. The name and the attributes (ModuleSpanAttributes: text, numbers and booleans, at most 20) are scrubbed like log lines, and an attribute named like a body, headers, a cookie, a token, a password, an email address, an IP address or an account is left out. Name what the work does, never who it is for. Without an exporter ctx.trace runs the work and nothing more, so leave the calls in. A log line written inside a span carries its trace id. Untrusted modules have no ctx.trace yet. In a module's own tests, build a context with the testing entry's trace. See Traces.
Health
SHADE measures a module's health itself: its processes, how its schedules' last runs ended and the errors recorded for it. A module adds a check for what only it knows with the manifest part health:
health: async (ctx, signal) => {
const key = await readProviderKey(ctx)
return key.expired ? { ok: false, note: 'The provider key expired' } : { ok: true }
}
The worker calls it every 5 minutes as the module's own actor, with a 10-second limit (signal aborts then). No answer in time, or throwing, counts as unhealthy. Keep it cheap and read-only. The note shows on the Modules page, never in an alert or an email. An untrusted module says "health": true in its sandbox package and answers GET /__shade/health with { "ok": true } or { "ok": false, "note": "…" }. Health is not a capability.
Retention
A module that keeps personal data declares how long: retention: [{ key, label, help?, defaultDays, minDays, purge(db, before, now) }]. Each kind appears in Settings → Data retention (key prefixed with the module name, label an admin translation key), and the core's hourly job calls purge with the cut-off, also while the module is off. See Data retention.
Consent
A module whose site parts need the visitor's consent (an embedded map, a video, a pixel) declares categories. Each says what it is, why, where it loads from, which cookies it sets and for how long, and where the outside party's privacy statement is. Its label, description and purpose are keys in the module's locale files, read in the page's language (else its primary code, the site's default, English). A new or changed language file asks visitors again:
export default defineModule({
name: 'videos',
// …
capabilities: { allowedSources: {}, consent: {} },
allowedSources: { site: { frame: ['https://player.example.org'] } },
consent: {
categories: [{
key: 'player',
// keys in locales/<language>.json: { "consent": { "player": { "label": "Videos", … } } }
label: 'consent.player.label',
description: 'consent.player.description',
purpose: 'consent.player.purpose',
hosts: ['https://player.example.org'],
cookies: [{ name: 'vid_*', firstParty: false, duration: { days: 180 } }],
privacyUrl: 'https://player.example.org/privacy',
needsProof: false
}]
}
})
- Every site source is covered. Each host in the module's site
allowedSourcesis named by a category'shosts, and a category names only those. A category with hosts names theirprivacyUrl.cookieslists what it sets:firstParty: truefor a cookie the site itself sets (withdrawing consent expires it), a trailing*for a prefix, andduration: 'session'or{ days }. - Or say why none is needed. A module whose site parts set no cookie and send nothing elsewhere, such as a head part that counts page views on the instance itself, declares
consent: { exempt: { reason } }instead (10 to 300 characters, shown to admins as written). Not both, unless the owner chooses (below). - Or let the owner choose. A module that needs no consent as built may also declare the categories an owner can put it behind, with
askWhen(ctx)answering, as the module, whether to ask now: analytics asks while itsaskConsentsetting is on. While it answers false the exemption applies; while it answers true, or fails, the categories do, and gate the head part. Since the site's pages carry the banner as built, ask for a rebuild when the answer changes (requestRebuildwhen it hearspackages.module.settings-changed):
Declareexempt,categories,headandaskWhen: async ctx => (await getModuleSettings<{ askConsent?: boolean }>(ctx, 'analytics')).askConsent === truetogether. - Checked twice. A module with site
allowedSourcesor a site head part (site/index.tsexportinghead) that declares neither is refused byshade-module buildand by the API when it loads. In tests,validateModule(plugin)andfolderProblems(plugin, dir)from@shadestack/module-sdk/testingrun the same checks. - Shown to admins. The categories (or the exemption) are lines of the
consentcapability (capabilities: { consent: {} }): the install consent, the Modules page and the approval list them, and a change asks the admin again. - Versioned. The site gets each category with a
versionthat changes whenever anything in it changes, and asks the visitor again. - Proof where it is needed. A category with
needsProof: true(marketing, advertising) gets a receipt on the instance for each choice: a random id the visitor can read, the banner configuration it answered, the answers and the time; no IP address or browser string. Receipts are kept 3 years, in the privacy screen's lookup and erasure (Consent banner). The module does nothing more for it. - A head part waits for its category. A module with categories and a site head part names the category that gates it:
consent: { categories: [...], head: 'player' }. The site renders the head part inert until the visitor allows that category, then adds it to the page, so its scripts need not check consent themselves. Its inline scripts run under the site's policy; scripts from an outside host need that host in the module's siteallowedSources(script). - Core shows the banner while the module is on. The module's script checks
window.shadeConsent?.has('<plugin>.<key>')and listens forshade:consentbefore loading anything (Consent banner). The legal texts (the privacy statement, what the business tells visitors) are the site owner's.
shade/test/testing/fixtures/modules/test-consent declares one full category, for SHADE's own browser tests. A client's instance never has it.
Editable emails
Experimental until a second module uses it. A module with the email capability may let admins edit the wording of its own emails on SHADE's Messages screen: it declares them in the manifest part emailTemplates and writes them with composeModuleEmail.
defineModule({
name: 'shop',
capabilities: { email: {} },
emailTemplates: {
'order-confirmation': {
placeholders: [{ name: 'name' }, { name: 'orderNumber' }, { name: 'lines', required: true }]
}
}
})
// locales/en.json (and one file per other language)
{ "emails": { "order-confirmation": {
"title": "Order confirmation",
"description": "Sent when an order is paid.",
"subject": "Your order {orderNumber}",
"body": "Dear {name},\n\n{lines}",
"samples": { "name": "Ann de Vries", "orderNumber": "2026-000042", "lines": "2 × Mug" }
} } }
// where the order is paid: the admin's wording, or the default, filled in as plain text
const { subject, text } = await composeModuleEmail(ctx, 'order-confirmation', order.locale, { name, orderNumber, lines })
await sendEmail(ctx, { to: [email], subject, text })
- The id on the Messages screen is
<plugin>.<key>. A placeholder is{name}; every declared placeholder needs a value; values are filled in as plain text, never read as placeholders, and the subject is one line. A required placeholder must stay in an edited body. - The texts are the module's locale files (see Texts for visitors). SHADE checks at load that
en.jsonhas the title, description, subject, body and a sample per placeholder, and that every file's subject and body keep the placeholders. - The Messages screen shows a tab per language: the site's languages first, then any your files add. A language without a file starts from the site's default text.
- Attachments stay in the module's code: appointments' booking confirmation still carries its
.ics. - The modules with emails of their own today are commerce (
commerce.order-confirmation) and appointments (appointments.booking-confirmation).
Mailing lists
Experimental until a second module uses it. A module with the email capability that sends marketing mail uses four functions (and importBulkSubscribers) instead of sendEmail; sendEmail stays for transactional mail and gets no headers. The module owns its public routes and its sign-up form; core owns the rules.
import { confirmBulkSubscription, requestBulkSubscription, sendBulkEmail, unsubscribeBulk } from '@shadestack/module-sdk/server'
// POST /subscribe: always answer the visitor the same, whatever the status.
await requestBulkSubscription(ctx, {
list: 'launch',
address,
consentText: 'I want the launch announcements by email. I can unsubscribe at any time.', // kept as the proof
confirmUrl: 'https://shop.example.org/api/v1/account/newsletter/confirm', // SHADE adds ?token=
subject: 'Please confirm your subscription',
text: 'Follow this link to confirm:\n\n{confirmUrl}'
})
// POST /confirm?token=… (a GET must never change anything: mail scanners follow links)
// { list, address, contactId }: the person's contact, confirmed now, for your own rows (contactReference).
await confirmBulkSubscription(ctx, { token })
// POST /unsubscribe?token=… The mail program's one click posts List-Unsubscribe=One-Click here.
await unsubscribeBulk(ctx, { token, via: 'one-click' })
// One message to one confirmed subscriber, with List-Unsubscribe, List-Unsubscribe-Post and a footer.
const result = await sendBulkEmail(ctx, { list: 'launch', to: address, subject, text, unsubscribeUrl: 'https://shop.example.org/api/v1/account/newsletter/unsubscribe' })
// { sent: true } or { sent: false, reason: 'not-subscribed' | 'suppressed' | 'limited' }
Links must be https (http on localhost while developing). A hard bounce or a complaint ends the address on every list. The lists keep each person as a contact: a sign-up finds or adds the address's contact, following the confirmation link confirms it, and erasing the person removes their subscriptions before the contact.
People who agreed elsewhere (a list moved from another tool) come in with importBulkSubscribers(ctx, { list, addresses, consentText, source, confirmedAt? }): up to 1000 addresses a call, confirmed, without a confirmation mail. The proof is what you pass: the consent text they agreed to, where (source), and when (confirmedAt, now when left out). It never adds a blocked address, anyone who left the list, or an erased person who had unsubscribed, and answers counts only: { imported, already, left, blocked, objected }.
An erased person who had unsubscribed or complained is kept as a keyed hash of the address only: sendBulkEmail answers suppressed for them until they confirm a new sign-up themselves. Admins see every module's lists on Email → Lists. The core fixture newsletter-probe (shade/test/testing/fixtures/modules/newsletter-probe) is a complete example.
Signed links and codes
Experimental until a second module uses them. A link mailed to someone to confirm, cancel or move something, or a code a person types (a ticket's, an invite's), is SHADE's: bound to your module, one purpose and one subject, expiring, used at most as often as you allow, and kept only as a keyed hash.
Declare each purpose in the manifest part links: what a link shows (view) and what pressing its button does (redeem), as data, never HTML. SHADE checks the token and shows your answer on its own page, or on the frontend's own links page when there is one (Your own page for SHADE's links).
import { defineModule, issueLink, withDb, type LinkView } from '@shadestack/module-sdk/server'
export default defineModule({
// …
links: {
purposes: {
'booking-cancel': {
// `subject`: what the link opens; `left`: how many uses it has left.
view: async (ctx, link): Promise<LinkView> => link.left
? { status: 'open', language: 'en', title: 'Cancel booking', text: ['Cancel it?'], action: { button: 'Cancel' } }
: { status: 'closed', language: 'en', title: 'Cancel booking', text: ['It is cancelled already.'] },
// `use(ctx)` uses the link in your transaction: false when it was used meanwhile, and then change nothing.
redeem: async (ctx, link) => ctx.db.transaction(async (tx) => {
if (!await link.use(withDb(ctx, tx))) return { status: 'closed', language: 'en', title: 'Cancel booking', text: ['It is cancelled already.'] }
// … cancel booking `link.subject` in `tx` …
return { status: 'closed', language: 'en', title: 'Cancel booking', text: ['Your booking is cancelled.'] }
})
}
}
}
})
// In a mail: `url` lands on SHADE's page or the frontend's; null without the API's address.
const { url } = await issueLink(ctx, { purpose: 'booking-cancel', subject: booking.id, expiresInMs: 7 * 86_400_000, contactId })
- A
viewwithaction.chooseasks for one choice first ({ legend, options: [{ value, label }] });redeemgets the chosenvalueaslink.choice. Check it: anything may come back. contactId: the contact the link is sent to. Using the link proves the address, and SHADE confirms the contact.- Anything that does not work (a wrong or expired token, another module's or purpose's) never reaches your code: SHADE answers the same
invalidview. - Codes people type:
issueCode(ctx, { purpose, subject, expiresInMs, maxUses?, length? })gives a code in a readable alphabet (digits and capitals without I, L, O and U; typing is forgiving).peekCodesays what one opens and how many uses it has left.redeemCodeuses it once, atomically, or answersnull, never why. Your route limits how often one can be tried. - A code with a text you choose:
issueCode(ctx, { …, text: 'SUMMER25' })(4 to 32 letters and digits, U too, read back by case only, sosummer25works andSUMM3R25does not). It is CONFLICT while the same text has not expired for that purpose. releaseCode(ctx, { purpose, secret, subject })gives back one use of a code thatsubjectused, when what used it did not happen (an order never paid). It answers whether a use was given back; call it once per use.links.theme(ctx): CSS variables for SHADE's own link page (--color-background,--color-text,--color-primary,--color-primary-contrast,--color-border,--font-body,--radius). The module that styles the site gives it.- In tests, the testing entry's
openLink(ctx, url)andfollowLink(ctx, url, choice?)show and use a link from a mail as its page would.
Client programs
A trusted module may call client programs: the client's own programs in any language that an admin approved on the Programs screen and that the instance's host, shade-programs, runs beside it. It never calls one by its address (moduleFetch refuses private addresses): it declares the client programs in its programs capability and calls them with callProgram from the server entry, which goes through the host.
export default defineModule({
name: 'shop',
capabilities: { programs: { names: ['price-model'] } },
// …
})
const answer = await callProgram(ctx, 'price-model', {
method: 'POST',
path: '/predict',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ size: 3 })
})
if (!answer.ok) throw new Error(`price-model answered ${answer.status}`)
const { price } = await answer.json() as { price: number }
request(ProgramRequest):method(GETby default, orHEAD,POST,PUT,PATCH,DELETE),pathon the client program (/predict?x=1),port(one it declared; its first by default),headers(onlyaccept,accept-language,content-type,if-match,if-modified-sinceandif-none-match),body(a string or bytes, at most 1 MB) andtimeoutMs(10 000 by default, at most 60 000).- The answer is a
Response: the client program's status, itscache-control,content-language,content-type,etag,last-modifiedandlocationheaders, and its body (at most 5 MB). A redirect is returned, never followed. - A client program the capability doesn't name is refused (FORBIDDEN, counted for the module). One that is not approved, an instance without a host, or a client program that is not running is CONFLICT. A host or client program that cannot be reached, fails or is too slow is UNAVAILABLE. Each carries a key the admin translates.
- The client program's own token, not the module's, decides what it may then do on the instance.
In tests, fakeProgramHost(db, answers) from the testing entry stands in for the host. Each client program it names is approved and running, and answers what its function returns (an echo of the method and path when there is none). Pass fake.programHost as extra: { programHost } to shop.ctx(...); fake.calls keeps every call. The programs capability still decides what the module may call.
Personal data
A module that keeps data about people declares where: personalData: [{ key, label, tables?, find(ctx, email, accountIds, contactIds), erase?(ctx, email, accountIds, contactIds), keepReason? }], with erase, keepReason or both. Admins then see, export and delete it per email address on the Personal data screen, also while the module is off (Personal data per person). accountIds are the ids of the accounts with the address and contactIds the person's contacts (below), both read before anything is erased. A source with both erase and keepReason deletes what may go; what find still returns afterwards is counted as kept (an order never paid goes, a paid one stays).
Contacts
Experimental. Core keeps one contact per email address a module met, with or without an account: the address, when the person confirmed it, the language they last used and the account it belongs to. What your module knows about the person stays in your tables, which refer to the contact instead of keeping a bare address:
import { contactEmail, contactReference, findOrAddContact, ownedByContact } from '@shadestack/module-sdk/server'
export const shopOrders = pgTable('shop_orders', {
id: id(),
contactId: contactReference('contact_id').notNull(), // on delete restrict: an order the law keeps keeps its contact
// …
})
// At checkout: the same id whether the contact was new or not, so nobody learns which addresses are known.
const contactId = await findOrAddContact(ctx, { email: input.email, language: input.locale })
// Its address, to send to or show: an SQL expression to select or filter on.
await ctx.db.select({ number: shopOrders.number, email: contactEmail(shopOrders.contactId) }).from(shopOrders)
// A signed-in account's own orders (an account route's `request.account`): their account's contacts and their address's.
await ctx.db.select().from(shopOrders).where(ownedByContact(shopOrders.contactId, request.account))
- Personal data. A table with a
contactReferencemust be in thetablesof apersonalDatasource that erases, or the module does not load. Find and erase bycontactIds(inArray(shopOrders.contactId, [...contactIds])). The contacts themselves are erased after every module's rows; one that rows you keep still refer to stays. - Confirmed. A contact is confirmed only when the person proves the address: signing in with it, or a link your module sent to the address and they followed (call
confirmContact(ctx, contactId)then). Only a confirmed address links a contact to an account, and only by signing in. - The People screen. Admins see every contact there. Your module shows what it keeps about one in a contact panel (
admin.contactPanels, see Where a module appears in the admin), read through a session route of your own that checks your read action.
Numbering
Experimental. A gap-free number series per module per year, as Dutch invoice law asks for invoices: 2026-0001, 2026-0002… Take the next number in the transaction of the change it numbers:
import { inTransaction, nextNumber } from '@shadestack/module-sdk/server'
await inTransaction(ctx, async (tx) => {
const { number } = await nextNumber(tx, 'invoices', { at: paidAt, digits: 4 }) // '2026-0001'
await tx.db.insert(shopInvoices).values({ number, orderId })
})
- Only in a transaction, and only on the context SHADE gave your code: the series' row stays locked until the transaction commits, so a second caller waits, and a rollback gives the number back. No gap, no number twice. A Postgres sequence leaves gaps and is not used.
- The year is the year of
at(default now) in the site's time zone: each series starts at 1 every year. The answer is{ number, year, sequence }, the sequence padded todigits(default 4). - Your own. A series is named with small letters, digits and hyphens, and belongs to your module. It stays when the module is removed, so installed again it never repeats a number.
Holds
Experimental. Hold N of one of your resources until an expiry, or a time range of it, so the last place is never held twice: stock while a customer pays, a time slot, a seat. SHADE keeps no catalogue of your resources: you name them (sku:MUG-1, slots:default) and give the capacity with each hold, from your own data.
import { confirmHold, heldCount, hold, inTransaction, releaseGroup } from '@shadestack/module-sdk/server'
await inTransaction(ctx, async (tx) => {
// CONFLICT holds.errors.full (with `available`) when fewer than 2 of the 5 are free.
await hold(tx, { resource: 'sku:MUG-1', quantity: 2, capacity: 5, expiresAt: inTenMinutes, group: `order:${orderId}` })
})
await heldCount(ctx, 'sku:MUG-1') // 2 while it runs
await confirmHold(ctx, holdId) // counts until released
await confirmHold(ctx, holdId, { taken: true }) // you took the units off your own count: counts no more
await releaseGroup(ctx, `order:${orderId}`) // give an order's holds back
- Atomic. A hold takes a lock per resource for the rest of the transaction, counts what is held and only then holds. In your transaction it is kept or rolled back with your change.
- What counts: confirmed holds, and held ones until their
expiresAt. A hold past its expiry stops counting at once and can't be confirmed; SHADE's sweep marks it expired every minute.takenkeeps a confirmed hold as proof without counting it, for stock you lowered yourself. - Time ranges:
during: { start, end }(the end not included) counts the most held at any one moment of it, widened bybufferMinuteson both sides;heldCounttakes the same options. With a capacity of 2, holds for 09:00–09:30 and 09:30–10:00 use one place at a time, so a hold for 09:00–10:30 still fits. A page of free times readsheldRangesonce and counts each time withpeakHeld(ranges, { start, end }, bufferMinutes), asholdcounts. - A quota per holder:
holders(your keys, such ascontact:<id>orip:<visitor key>) withquota: 3refuses a fourth running hold of the resource by any of them (CONFLICTholds.errors.quota). An ended hold keeps nobody's key. - Groups:
groupnames holds that go together;groupHoldsreads them andreleaseGroupends them. - Live counts: every change tells the realtime topic
holdsTopic(resource)once it commits. A route that shows a count names it in itsrealtime. - Your own. Only on the context SHADE gave your code, on your module's holds alone. Removing the module backs them up and forgets them; ended holds go a week after they end.
heldCounts(ctx, resources)counts many at once.
Waitlists
Experimental. When a resource is full, a holder can wait in line for it. When room comes free, SHADE offers it to the first in line by holding it for them:
import { acceptOffer, claim, heldRanges, offerNext, withdrawClaim } from '@shadestack/module-sdk/server'
const place = await claim(ctx, { resource: 'slots:default', during: { start, end }, holder: `contact:${contactId}`, group: `booking:${id}` })
// When your module hears that a hold was freed (below): offer the room to those in line, in order.
await offerNext(ctx, 'slots:default', { capacity: 2, during: { start, end }, bufferMinutes: 10, offerMinutes: 30 })
await acceptOffer(ctx, claimId) // the offer's hold is confirmed
await withdrawClaim(ctx, claimId) // out of line; an offer is given back
await heldRanges(ctx, 'slots:default', { during: { start, end } }) // the ranges held, to cut free times from
- In order.
offerNextworks under the resource's lock: the first claims that fit each get a hold that expires afterofferMinutes, held by the claimant in the claim'sgroup. The first claim that does not fit stops it, so nobody skips the line. A holder has one running claim at a time. - The event. When a hold ends or is released, SHADE tells the module that owned it with
holds.hold.freed(owner,resource,quantity,start,end), through the manifest parton. No other module hears it. Your handler callsofferNextand tells the person. - Ending. An offer that is not accepted before its hold expires lapses, and its room is freed again, so the next in line is offered it. A claim whose range has started lapses too. Ended claims go a week later.
groupClaims(ctx, group)reads claims that go together. - Your own. Only on the context SHADE gave your code, on your module's claims alone. Removing the module backs them up and forgets them.
Time rules
Experimental. Core keeps your module's named opening rules in the site's time zone: a week of opening periods and exceptions to it. SHADE works out the open times; your module cuts them into what it sells. No capability is needed.
import { ensureTimeRules, saveTimeRules } from '@shadestack/module-sdk/server'
import { isOpen, openIntervals, withoutPast } from '@shadestack/module-sdk/shared'
const { rules, timeZone, updatedAt } = await ensureTimeRules(ctx, 'default') // closed all week the first time
await saveTimeRules(ctx, 'location:7', { rules: withoutPast(next, today), baseUpdatedAt: null }) // audited as time-rules.update
const intervals = openIntervals(rules, from, to, timeZone) // open stretches as instants, at most 400 days
isOpen(rules, new Date(), timeZone)
- The rules.
TimeRulesis aweek(seven days of at most four non-overlappingOpeningPeriods,09:00–17:00) and at most 366exceptions. An exception isclosed(the whole day) oropen(at its own periods instead of the week's), from adate, repeatingevery(RECURRENCES):once(or each day untiluntil),week,month(skipped in months without that day),month-weekday(such as the first Monday) oryear. It may have anuntiland anote. - Which decides. A dated (
once) exception beats a repeating one, and a closing beats an opening.appliesOnandperiodsOnanswer for one date;closedRules()gives rules that are never open. - Open times.
openIntervalscuts the open stretches to[from, to), joins touching ones and handles clock changes. It throws for more than 400 days. - Keys. Rules are kept per module under a key you choose (
default,location:<id>).findTimeRulesanswers null when there are none;deleteTimeRulesremoves them. - Saving.
saveTimeRulesrefuses rules that can't hold (VALIDATION) and drops exceptions that are over. WithbaseUpdatedAt(theupdatedAtyou read, or null when none were stored) a save over a newer one is CONFLICTcommon.errors.changedMeanwhile. Check your own permission first: SHADE checks none. - Admin. The component
OpeningHoursFieldedits the rules withv-model,timeZoneanddisabled. The opening hours guide page shows what an admin sees. - Rules are your module's alone. Removing the module backs them up and forgets them.
Locations
Experimental. The business's places and their addresses are kept by core, on the Locations screen, and so are the rules every module writes an address by:
import { mainLocation } from '@shadestack/module-sdk/server'
import { checkPostcode, formatAddress } from '@shadestack/module-sdk/shared'
const seller = await mainLocation(ctx) // the business's own address; null while no location is added
const lines = seller ? [seller.name, ...formatAddress(seller.address, { locale: 'nl-NL' })] : []
// A delivery address whose postcode must be its country's:
const Delivery = z.object({ line1: z.string(), postalCode: z.string(), city: z.string(), country: z.string() }).superRefine(checkPostcode)
- Countries.
COUNTRIES(ISO 3166-1 alpha-2),EU_COUNTRIES(the 27),isCountry,isEuCountry, andcountryName(code, locale). - Postcodes.
isPostcodeOf(country, postcode)checks the format for the EU's 27 and the United Kingdom, Switzerland, Norway, Iceland, Liechtenstein, the United States, Canada and Australia; elsewhere any postcode is taken.normalizePostcodewrites it the country's way (1234abbecomes1234 AB).checkPostcodeis the same check for a schema, its issue onpostalCode.PostalAddressis a whole address with the check and an optionalregion. - Writing an address.
formatAddress(address, { locale, country })gives lines the way the country writes them, then the country's name (left out withcountry: false).
Fiscal records
Experimental. A document the law keeps (an invoice, a credit invoice, a receipt) is a fiscal record, kept by core: numbered from one of your module's series, stored exactly as issued, kept until 1 January of the eighth year after the year it was issued (seven whole years), and then deleted by retention. Issue it in the transaction of the change it belongs to:
import { fiscalRecordFile, fiscalRecordReference, issueFiscalRecord, withDb } from '@shadestack/module-sdk/server'
export const shopInvoices = pgTable('shop_invoices', {
id: id(),
fiscalRecordId: fiscalRecordReference('fiscal_record_id'), // null once the law no longer keeps it
// …
})
const record = await issueFiscalRecord(withDb(ctx, tx), {
series: 'invoices', kind: 'invoice', digits: 4, at: paidAt, contactId: order.contactId, contentType: 'application/pdf',
render: ({ number }) => renderPdf(order, number) // the document names its own number
})
// record: { id, number, issuedAt, keptUntil, body }; later: await fiscalRecordFile(ctx, record.id)
- Once. A record is never changed: there is no update. A rollback leaves no record and gives the number back.
- Kept by law. A person's records are listed with their end date on the Personal data screen and counted as kept when the person asks to be erased; their contact stays with them. Neither your module's retention nor uninstalling it removes a record.
- Private files. Fiscal records follow the
filesswitch: while it is off,issueFiscalRecordis NOT_FOUND. You need nofilescapability for them.
Lifecycle guard
Experimental. A status that moves in steps (an order, a booking) has one table of where it may go; defineLifecycle keeps every write of it to that table:
import { defineLifecycle } from '@shadestack/module-sdk/server'
export const ORDER_LIFECYCLE = defineLifecycle(shopOrders, {
pending: ['paid', 'cancelled'], paid: ['shipped', 'refunded'], shipped: ['refunded'], cancelled: [], refunded: []
})
await inTransaction(ctx, async (tx) => {
const moved = await ORDER_LIFECYCLE.move(tx, eq(shopOrders.id, id), 'shipped', {
set: { carrier },
audit: row => ({ action: 'shop.orders.ship', targetType: 'order', targetId: row.id, summary: `Order ${row.number} shipped` }),
event: row => ({ name: 'order.shipped', subject: { type: 'order', id: row.id }, data: { number: row.number } })
})
if (!moved) throw conflict('This order changed meanwhile')
})
movewrites the status only where the row is still in a status it may come from, withset, the audit entry and the event in your transaction. It answers null when another change came first, and writes nothing then.canMove,sourcesOfandassertMove(CONFLICT) answer from the same table. It is a guard, not a workflow engine: what happens around a move (stock, emails) stays your code.
Terms acceptance
Experimental. Keep the proof that a person accepted your terms, or a consent text, in the transaction of what they accepted it for:
import { acceptTerms } from '@shadestack/module-sdk/server'
import { acceptedText, withdrawalUntil } from '@shadestack/module-sdk/shared'
const text = acceptedText(settings.termsTexts, input.terms) // only a text you offer, in any language
if (!text) throw validation(undefined, [{ path: 'terms', message: 'Accept the terms to order' }])
await acceptTerms(tx, { terms: 'checkout', text, contactId, subject: { type: 'order', id: order.id }, withdrawal: 'goods' })
withdrawalUntil('goods', '2026-03-01') // '2026-03-15': 14 days from the day the goods arrived
- What is kept: the text, its version (
termsVersion: the text's SHA-256), the contact, the subject, the kind of sale and when. It is in the person's data and kept on erasure, for seven years by default under retention. withdrawalis the kind of sale:goods(14 days from receipt),servicesanddigital-content(14 days from the contract; digital content loses it once the supply starts with consent),dated-leisure(an event or course on a date: none) andnone(no sale at a distance, such as a consent to how details are used).
Tax
Experimental. VAT is the business's, kept once by core: the categories, the dated rates of the EU's 27 with the business's own on Settings, VAT rates, VAT numbers, reverse charge and exports. Your module decides its prices and who may order without VAT; core says what is charged:
import { checkVatNumber, vatRatesAt } from '@shadestack/module-sdk/server'
import { chargedRate, isExport, isReverseCharge, vatBreakdown } from '@shadestack/module-sdk/shared'
const rates = await vatRatesAt(ctx, now) // the rates in force at that moment
const rate = chargedRate('reduced', { home: 'NL', country: 'DE', oss: true, rates }) // 7
if (isReverseCharge({ home: 'NL', country: 'DE', vatNumber })) {
// Before your transaction: VIES may be asked, when the business switched it on.
const check = await checkVatNumber(ctx, 'DE', vatNumber) // { valid, checkedBy: 'vies' | 'format' | 'format-vies-unanswered' }
if (!check.valid) throw validation(undefined, [{ path: 'vatNumber', message: 'This VAT number is not valid in VIES' }])
}
const vat = vatBreakdown(lines, shippingCents, rates.NL.standard, 'EUR') // the VAT per rate, shipping in proportion
- The arithmetic is exact on the money type:
vatInGross,netOfGross,vatOnNet,rateTenths, andformatVatRate(rate, locale)writes5,5%. - VIES is an outside call the business chooses; keep what
checkVatNumberanswered with your record (the order says which check decided). It never throws for VIES's failures. - The One-Stop-Shop report: give core your sales and refunds charged at another EU country's VAT under One-Stop-Shop with the manifest part
taxSales(trusted modules):(ctx, { from, to }) => TaxSale[], each{ country, rate, grossCents, vatCents, currency }, a refund negative, dated by your invoice. The report adds up every module that is on, per quarter, country and rate. - In tests,
stubVies({ send })from the testing entry answers for VIES.
The country of an IP address
Experimental. countryOfIp(ip) gives the two-letter country of an address, looked up on the instance in DB-IP's IP to Country Lite (CC BY 4.0), or null. The address is never kept. Credit DB-IP where you show countries, with the month ipCountriesMonth() gives. In tests, stubIpCountries(packIpCountries(csv, month)) gives your own ranges and stubIpCountries(null) the shipped data again.
For digital services the EU lets a seller rely on two pieces of evidence of where the customer is. customerCountry([{ kind: 'billing-address', country }, { kind: 'ip-address', country: countryOfIp(ip) }]) settles the country when two kinds agree and no other country has two (contradicted says a piece points elsewhere).
Visitor keys and bots
Experimental. To compare visitors without keeping who they are (at most three unpaid orders per address), keep a key for the address, never the address:
import { isBot, visitorKey } from '@shadestack/module-sdk/server'
const key = visitorKey(ctx, 'shop.unpaid', request.ip) // null without an address or without APP_SECRET
const daily = visitorKey(ctx, 'stats', request.ip, { day: '2026-11-18' })
if (isBot(request.headers['user-agent'])) return // crawlers, link previews, monitors, no user agent
- The key is the vault's HMAC of the purpose, the day (when given) and the address. Keys of two purposes or two days never match. A purpose is lower-case letters, digits,
.,-and_; name it after your module and rule (commerce.unpaid). - With
day, the same address gives another key the next day: for counting visitors without following them. - Without APP_SECRET (some tests) the key is null: skip the check rather than compare nulls.
- The key is personal data while it can still match: list it in your personal data and drop it when it has done its work.
Texts for visitors, in any language
Experimental. What visitors read (emails to them, a page a link opens, an invoice, a starter's words, a consent category) comes from your module's locale files, one per language, never from { en, nl } in code. A third language is one more file:
locales/
en.json { "cart": { "free": "free", "total": "Total: {amount}" } }
nl.json { "cart": { "free": "gratis", "total": "Totaal: {amount}" } }
de.json { "cart": { "free": "kostenlos" } }
import { messages, textsIn } from '@shadestack/module-sdk/server'
const texts = await messages(ctx, order.locale) // a page's language, an Accept-Language header, or null
texts.t('cart.total', { amount: formatMoney(total, formattingLocale(texts.language)) })
const everywhere = await textsIn(ctx, 'cart.free') // { nl: 'gratis', en: 'free', de: 'kostenlos' } for the site's languages
- SHADE reads
locales/<language>.json(nested objects;{ "cart": { "free": … } }is the keycart.free) when the module loads, andshade-module buildships the folder. A broken file stops the load. - Each key comes from the first of the page's language (
nl-BE), its primary code (nl), the site's default language and English that has it, sode.jsonmay hold only some keys.tthrows for a key no file has. {name}is filled in as plain text; a value is never read as a placeholder.- The admin's own texts stay in
admin/locales(Dutch and English). - From the shared entry:
pickLanguage(wanted, available, fallback?)(reads anAccept-Languageheader too),primaryLanguage('en-GB')givesen,formattingLocale(language)gives what to pass toIntlandformatMoney(a bareenbecomesen-GB), andformatDateRange(start, end, language, { timeZone })writes a time from start to end. - In tests,
setModuleLocales(plugin, dir)from the testing entry reads another folder in place of yours.
Uninstall hook
onUninstall(ctx) runs when an admin uninstalls the module, after the backup and before its data and settings are removed, in the same transaction (ctx.db, which reaches the module's own tables). Use it for what core doesn't know about, such as a webhook registered at an outside service. If it throws, the uninstall stops and nothing is removed.
Sealing again after APP_SECRET changes
A trusted module that keeps sealed values in its own tables (ctx.vault.seal) gives onSecretsRotated(ctx). When the operator replaces APP_SECRET and runs rotate-secrets (Rotating APP_SECRET), it runs as the module, on or off, and seals each value again with the new secret:
onSecretsRotated: async (ctx) => {
let resealed = 0
for (const row of await ctx.db.select().from(fleetClients)) {
if (ctx.vault!.isCurrent(row.token)) continue
await ctx.db.update(fleetClients).set({ token: ctx.vault!.reseal(row.token) }).where(eq(fleetClients.id, row.id))
resealed++
}
return resealed
}
It runs on every run of the command, so it leaves current values alone, and resolves to how many it sealed again. Settings marked secret are SHADE's to seal again. A secret in a link the module sent by email (ctx.vault.hash) is checked with ctx.vault.hashMatches(value, hash), which also accepts the hash made with the previous APP_SECRET.
Services
A module that needs email or accounts declares the capability (capabilities: { email: {} }, accounts). The manifest has no services key, and a manifest with one is refused at load. Until the service behind a required capability is ready (set up, and switched on where it has a switch), the module shows "Needs setup" on the Modules page, with a link to the service's screen, and cannot be switched on. While the module is on, the service cannot stop working.
Appointments is the example: it sends its confirmations with sendEmail and declares email, and accounts as optional. Guests book without an account, and its staff routes answer only while the capability is on (hasCapability(ctx, 'accounts')). A module context without the capability is refused by the service itself (sendEmail starts with requireCapability): FORBIDDEN, counted for the module.
The providers behind capabilities with settings are registered in one shape, in the provider registry (shade/kernel/providers/registry.ts): each says whether it is configured, whether it is on and which others it needs (registerProviderSetup). readyProviders, missingDependencies and neededBy answer the same questions for all of them: accounts need email, and email cannot be switched off while accounts or a module need it.
Payments are not a service of core: the official payments module offers them to the modules that require it (Calls between modules). The module that takes money starts a checkout with callModule, sends the visitor to checkoutUrl, and hears every change of its payments as an event (payments.payment.<status>) in its manifest's on. Amounts are SHADE's Money in euros. Refunds and cancelling are calls too, made after the module's own permission check.