Extending blocks
Add your own columns to a block's table, steer its methods with hooks, wrap its transport and add methods, without forking the block.
A block covers the common case, and your app adds what makes it yours: a
plan column on organizations, a rule that refuses an invite above the seat
limit, a request id on every database call, a method the block doesn't have.
Each need has one place, from the least code to the most:
| You want to | Use | Where |
|---|---|---|
| Change what the block does | blocks.<module> options, permissions and hooks | SQL config |
| Add columns and get them back, typed | A column in your own schema file and the fields option | SQL and TS |
| Refuse, rewrite or observe a call | hooks on the block, or SQL before_/after_ hooks | TS or SQL |
| Run code around every database call | wrapTransport(transport, middleware) | TS |
| Add a method | extendBlock(block, build) | TS |
| Add a block of your own | defineBlock({ ... }) | TS |
Rules that must hold for every write, including writes that skip
TypeScript, belong in SQL: a permission, a check constraint or a before_
hook. Hooks in TypeScript are for app logic around a call: plan limits,
defaults, metrics.
Your own fields
Add columns to a table the block creates with alter table ... add column
in one of your own schema files. The block reads each column as a field: it
copies the column on create and update and returns it from its reads. A name
the block already uses is skipped, so a column can't shadow role or id.
alter table "better_supabase"."your_table" add column "plan" text not null default 'free';
alter table "better_supabase"."your_table" add column "seats" integer not null default 3;
alter table "better_supabase"."your_table" add column "locale" text not null default 'en';On a table of your own, the columns already exist: list the ones the block
takes as fields in the table comment (@bsb fields plan, seats), or use
options.attributes (organizations), or nothing at all (profiles, which
return the whole row).
Then pass a Standard Schema for those fields (zod, valibot, arktype), keyed by database name. The block types its reads and writes with it, parses the values it reads, and validates writes before they reach the database:
import { createOrganizations } from "better-supabase/blocks/organizations";
import { z } from "zod";
export const OrganizationFields = z.object({
plan: z.enum(["free", "pro", "enterprise"]),
seats: z.number().int().positive(),
});
const organizations = createOrganizations({
transport,
fields: OrganizationFields,
});
const [first] = await organizations.mine().orThrow();
first?.plan; // "free" | "pro" | "enterprise"
await organizations.update(id, { seats: 0 }); // { ok: false, error: { kind: "validation" } }A write sets only some fields, so issues about fields it leaves out are
ignored; the database applies its defaults and not null checks. A stored
value the schema rejects is a validation error on the read, so keep the
schema able to read the rows you already have. The parsed fields are merged
over the row, so the block's own columns stay even when the schema strips
keys it doesn't name.
Notifications type their data the same way, per notification type: see
typed data.
The option names the block's main table; tables the block fills on its own
(lines, deliveries, history rows) take no extra columns. A function that
gains a fields argument for them gets it only when the table has a column you added,
and each build drops the signature it doesn't create, so turning the option
on or off leaves one function that a call matches.
| Block | Columns from | fields types |
|---|---|---|
| organizations | options.attributes, a column you add | mine(), create, update |
| invitations | a column you add to invitations | invitationFields: invite, updateInvitation, myInvitations |
| profiles | a column you add, or any column you adopt | mine(), updateMine |
| notifications | the data of each type; a column you add to events | send, get, list, page |
| deals | a column you add to deals | every deal it returns, create, update |
| drive | a column you add to drive_nodes | every node it returns, createFolder, upload |
| employees | a column you add to employees | every employee it returns, create, update |
| activities | a column you add to activities | every activity it returns, log, update |
| flags | a column you add to flags | list, save |
| forms | a column you add to forms | create, update, get, list |
| hiring | a column you add to jobs | saveJob |
| inventory | a column you add to inventory_locations | saveLocation |
| invoices | a column you add to invoices | every invoice it returns, create |
| orders | a column you add to orders | checkout, getOrder, capture, invoice |
| parties | a column you add to companies | saveCompany, mergeCompanies, listCompanies |
| pipelines | a column you add to pipelines | save, list |
| promotions | a column you add to promotions | savePromotion |
| push | a column you add to devices | register, tokensFor |
| quotes | a column you add to quotes | create, update, send, decide, revise, fromDeal |
| relations | a column you add to relations | link, of, edges |
| reminders | a column you add to reminders | save |
| saved-views | a column you add to views | save, duplicate, list |
| service-accounts | a column you add to principals | create, list |
| access-requests | a column you add to access_requests | writes: request; reads: every read |
| agents | a column you add to agents | writes: create, update; reads: every agent read |
| ai-chat | a column you add to ai_chats | writes: chats.create, chats.update; reads: chats.get, chats.list |
| ai-files | a column you add to ai_files | writes: files.upload, files.store; reads: the file reads |
| ai-schedules | a column you add to ai_scheduled_tasks | writes: create, update; reads: create, update, pause, resume, list |
| announcements | a column you add to announcements | writes: publish, update; reads: listActive, list |
| api-keys | a column you add to api_keys | writes: create (rotate copies them); reads: list, verify |
| approvals | a column you add to approval_requests | writes: request; reads: every request read |
| attachments | a column you add to attachments | writes: upload, put; reads: every attachment read |
| bookings | a column you add to bookings | writes: the customer object of hold and public.hold; reads: every booking read |
| calendar | a column you add to calendar_events | writes: save and the occurrence edits; reads: events |
| catalog | a column you add to products | writes: createProduct, updateProduct; reads: the saved product |
| collections | a column you add to subject_collections | writes: create, rename; reads: create, rename, list |
Deals, employees, invoices and the blocks from access-requests to
collections take the columns next to their own fields
(create(id, { name, region }) writes region); the others take them
under fields (saveJob(id, { title, fields: { level: 3 } })). Every
block returns them under fields, and the blocks from access-requests to
collections merge the parsed values into the row they return. Except
organizations, profiles, employees, drive and attachments, a block copies
the columns right after its insert, so give a not null column a default.
The other blocks with a managed table that apps extend take the same pair:
a column you add to the table below and fields on the creator. A
read returns the columns under fields, keyed by database name, and a
write takes them as fields and copies only the columns it names, so the
others keep their default.
| Block | Table | fields on writes |
|---|---|---|
| comments | comments | create, edit |
| connectors | connector_servers | servers.create, servers.update |
| share-links | share_links | create |
| signatures | signature_requests | request |
| sla | sla_policies | savePolicy |
| tags | tags | create, update |
| targets | targets | save |
| teams | teams | create, update |
| templates | templates | save |
| time-entries | time_entries | start, log, update |
| trash | trash_items | trash |
| versions | versions | snapshot |
| waitlist | waitlist_entries | join, for a new address only |
| webhook-inbox | webhook_inbox | store |
| tasks | tasks | create, update by column name |
| workflow-editor | workflow_definitions | definitions.save |
sso, state-machine, usage, webhooks and workflows take hooks but no
fields: their rows mirror another system (Supabase Auth, the IdP, an
engine's run registry), are written by triggers on the app's own table, or
are a metering log whose per-event data goes in metadata.
A few blocks keep no app columns: numbering (counters the module
owns), onboarding (progress rows of the steps defineChecklist declares),
outbox (an event log whose payload carries the app's data), reactions,
search (an index rebuilt from each subject's own row) and settings
(values typed by defineSettings).
Hooks
hooks runs your code around a block's methods, keyed by method name. A
before hook gets the arguments and returns nothing to go on, new arguments
to replace them, or a DbError to refuse the call, which then returns that
error without reaching the database. An after hook gets a copy of the
result and the arguments: it can record, never change. When it throws, the
error is logged and the caller still gets the result.
import { dbError } from "better-supabase";
const organizations = createOrganizations({
transport,
hooks: {
invite: {
async before([request]) {
if (request.organizationId === null) return;
const used = await seatsUsed(request.organizationId);
if (used >= (await seatLimit(request.organizationId))) {
return dbError("forbidden", "Every seat is taken", {
hint: "SEATS_FULL",
});
}
},
after(result, [request]) {
if (result.ok) metrics.increment("invites", { role: request.role });
},
},
create: {
before: ([attributes, options]) => [
{ plan: "free", ...attributes },
options,
],
},
},
});Hooks are typed per method, so request above is an InviteRequest and
result a Result<InvitationSent>. Every block takes them through
createBlocks, keyed like the blocks, and
blocks that consume one through a port (ai-schedules sending notifications) go
through its hooks too:
const blocks = createBlocks(
{
transport,
hooks: { notifications: { send: { before: checkQuietHours } } },
},
{ organizations: organizationsBlock, notifications: notificationsBlock },
);For a block you build yourself, withBlockHooks(block, hooks) from
better-supabase/blocks does the same.
Hooks in SQL
A hook in TypeScript runs only for calls through the block. For a rule
every caller must meet, use the SQL hooks the module calls inside its
functions, named before_<entity>_<action> and after_<entity>_<action>.
A before_ hook raises to refuse the write; an after_ hook runs in the
same transaction, so seeding rows for a new organization commits or rolls
back with it.
| Module | SQL hooks |
|---|---|
| organizations | before_organization_create(attrs jsonb, owner uuid), after_organization_create(organization, owner uuid), before_organization_update(organization, attrs jsonb), after_organization_update(organization, attrs jsonb) |
| profiles | before_profile_update(attrs jsonb, user_id uuid), after_profile_update(user_id uuid), after_profile_sync(user_id uuid) |
| notifications | before_notification_send(notification jsonb), after_notify(event uuid), and notification_audience |
| comments | before_comment_create(tenant uuid, subject_type text, subject_id text, body text), after_comment_create(message uuid), before_comment_assign(message uuid, assignee uuid), after_comment_assign(task uuid) (assign hooks need the tasks block) |
| inbox | before_inbox_conversation_start(inbox uuid, input jsonb), before_inbox_message_send(conversation uuid, input jsonb), before_inbox_conversation_assign(conversation uuid, assignee uuid, team uuid), before_inbox_conversation_status_change(conversation uuid, status text), and an after_ hook with the conversation or message id for each |
| workflows | before_workflow_schedule_create(name text, workflow text, tenant uuid), after_workflow_schedule_create(schedule uuid), before_workflow_start_request(key text, workflow text, tenant uuid), after_workflow_start_request(request uuid) |
| enrollments | before_enrollment_create(tenant uuid, program text, subject_type text, subject_id text), after_enrollment_create(enrollment uuid), before_enrollment_cancel(enrollment uuid), after_enrollment_cancel(enrollment uuid) |
| automations | before_automation_save(tenant uuid, rule jsonb), after_automation_save(rule uuid), before_automation_remove(rule uuid), after_automation_remove(rule uuid) |
| sequences | before_sequence_save(tenant uuid, sequence jsonb), after_sequence_save(sequence uuid), before_sequence_enroll(sequence uuid, subject_type text, subject_id text), after_sequence_enroll(enrollment uuid) |
The organization argument has the type of the organizations table's id.
Define the function in the hooks schema (public by default) and the
module calls it when it exists; SQL hooks
shows how to point a module at another schema or function.
Your own block declares plan limits and meters the same way as the shipped ones: defineBlock({ limits: { add: { meter: "seats" } }, meters: { add: { meter: "seats" } } }). Keys are client method names. createBlocks({ metering: true }) applies them when the usage block is in the set; see usage.
Transport middleware
Every block calls its SQL functions through a transport. wrapTransport
runs middleware around each call, for every block that uses the transport:
tracing, a statement timeout, an argument every function of your own takes.
Middleware has apiVersion: 1 and a name, and passes the request on with
next. It rejects with the error next rejected with, so the block still
maps it to a DbError.
import {
defineTransportMiddleware,
rpcTransport,
wrapTransport,
} from "better-supabase/blocks";
const traced = defineTransportMiddleware({
name: "tracing",
call: (request, next) =>
tracer.startActiveSpan(`${request.schema}.${request.fn}`, async (span) => {
try {
return await next(request);
} finally {
span.end();
}
}),
});
const transport = wrapTransport(rpcTransport(supabase), traced);testBlockTransportMiddleware(middleware) from better-supabase/testing
checks the contract; see conformance.
New methods
extendBlock(block, build, options) adds methods. build gets the block,
so a new method can compose the existing ones, and call for SQL functions
you add to the block's schema, with the block's error mapping. Pass the
block's transport (and schema) for call. Redefining a method the block
has throws: wrap it with a hook instead.
import { extendBlock } from "better-supabase/blocks";
const organizations = extendBlock(
createOrganizations({ transport }),
(base, { call }) => ({
archive: (organizationId: string) =>
call(
"archive_organization",
{ organization: organizationId },
() => true as const,
),
owned: () =>
base
.mine()
.map((memberships) => memberships.filter((m) => m.role === "owner")),
}),
{ transport },
);The extended block keeps every method's Result contract: a new method
returns an AsyncResult and never throws for a database error.
Your own blocks
Every block is described by one manifest, built with defineBlock and
exported from the block's subpath (commentsBlock from
better-supabase/blocks/comments). A block of your own uses the same
function, so createBlocks and defineBlocks take it next to the built-in
ones:
import { defineBlock, defineEvents, event } from "better-supabase/blocks";
export const invoicingEvents = defineEvents({
"invoice.sent": event<{ readonly invoiceId: string }>(),
});
export const invoicingBlock = defineBlock({
name: "invoicing",
events: invoicingEvents,
consumes: { notifier: "optional" },
create: createInvoicing,
category: "commerce",
entities: { invoice: { mutability: "editable", emits: { create: false } } },
});| Field | What it is |
|---|---|
name | The block's name, kebab-case |
sql | The SQL modules it installs, the keys of blocks in the config |
options | A blockOptions schema per SQL module, which types blocks.<module>.options and schemas/config-v1.json |
events | Its own events, from defineEvents |
consumes | The ports it needs, each optional or required |
provides | The ports it builds from its client, such as notifier: (client) => client |
create | Its creator, create<Name>(options) |
client | The name of its headless controller, when it has one |
category | Where it sits in the catalog: identity, tenancy, work, commerce, developer and so on (16 in all) |
entities | What each entity declares about itself: how it changes, its sorts and facets, and which methods record an event (Declare your entities) |
links | The links from its entities to other blocks' entities (Declare links and concerns) |
concerns | The row-level concerns its tables take part in beyond audit and events |
recipes | The UI recipes that use it |
record | The part of a record page it owns, from defineRecordBinding (Record bindings) |
Declare your entities
entities holds one entry per entity the block owns, keyed by the entity's
singular noun (invoice, risk_matrix). Every field is optional, so a block
declares what it knows today:
| Field | What it declares |
|---|---|
mutability | editable (has an update), append-only, state-machine (changes through named transitions) or read-only |
sorts | The names sort.by accepts, each a sort the SQL list function implements |
facets | The names facets counts values of |
filters | The names filters accepts, each with a list of values |
search | true, or the columns the entity's search indexes; q is accepted only when it is set |
emits | Per method (create, update, delete, archive, restore, purge): true when it records an event, false when a mutating method records none |
expectedVersion | true when update takes an expectedVersion (the row's updatedAt) and refuses a stale one with a STALE_WRITE conflict |
idempotent | The methods that take an idempotencyKey and claim it through the idempotency block, such as ["create"] |
permissions | The permission key each verb checks, as <block>.<entity>.<verb> (Declare permission keys) |
recordAccess | "team" when the entity's rows are visible by record team, so a list can filter by the caller's teams |
personalData, subjectColumn, erase | The columns that hold personal data, the column that names the person, and what an erasure does to the rows: delete, anonymize or keep. An append-only entity never declares delete (Plan subject access) |
retention, legalHold | The retention kind the rows follow and whether a legal hold on it stops their purge |
history | true or the columns whose changes field-history keeps, so a page shows a history tab |
partition | { by, every, archive }: the timestamp column, month, quarter or year, and detach or drop for old partitions |
offline | true, or { scope, where?, systemRows?, join? } when better-supabase powersync streams can sync the entity to a device. scope is user, self, tenant or readers, where adds column = value or column is null conditions, systemRows names the tables that keep tenant-less rows, and join lists the tables and rules that tie the rows to others (owned, referenced, member-set, member-organizations, readers and subject, each described in the EntityOfflineJoin type); the generator writes the stream query from them, and a test keeps the blocks that declare it equal to the blocks the generator supports (ADRs 0920, 0926 and 1031) |
flag, methods | The feature flag key that hides the entity and the block methods it hides. createBlocks({ flags }) returns not_found from those methods while flags(key) is false (ADR 0922) |
realtime, versioned, meter, limit | Reserved for the generators and checks that read them; each is documented where it starts to take effect |
const blocks = createBlocks(
{ transport, flags: (key) => provider.isEnabled(key) },
{ shipments: shipmentsBlock },
);A check that throws counts as off, and a method shared by several flagged entities needs every flag on. Without flags nothing is enforced.
tests/blocks/write-safety-gaps.ts lists the editable entities that take no expectedVersion yet and the entities whose create takes no idempotencyKey; write-safety.test.ts fails on one that is missing from the list and on one that is listed after it was fixed. The lists only shrink.
The conformance test fails when an entity has no mutability, when emits
names a method that records no event of the entity, and when a method is marked
false that is not on the known list in tests/blocks/emit-gaps.ts. The
capability matrix in the repository's block audit is generated from these
declarations by pnpm catalog.
Mark public events
An event is internal until its block marks it public. Pass the option to
event and read the list with webhookEventCatalog, so an app offers a webhook
subscriber only the events a block means to expose:
import {
defineEvents,
event,
webhookEventCatalog,
} from "better-supabase/blocks";
export const invoicingEvents = defineEvents({
"invoice.sent": event<{ readonly invoiceId: string }>({ public: true }),
"invoice.reminder_queued": event<{ readonly invoiceId: string }>(),
});
webhookEventCatalog([{ name: "invoicing", events: invoicingEvents }]);
// [{ block: "invoicing", type: "invoice.sent" }]organizations, shipments, invoices and orders mark theirs today. The
generated entity matrix in the repository's block audit lists them under
"The webhook event catalog" (ADR 0919).
Declare permission keys
permissions maps a verb to the key it checks. The key is
<block>.<entity>.<verb> in snake case, with the block name's hyphens written
as underscores (risks.risk.read, api_keys.api_key.rotate). The verbs are
read, create, update, archive, delete, export, import and manage,
plus named domain verbs such as approve, publish or close. A key a module
already checks keeps its two-part form (leave.read), so a manifest can name
today's keys without renaming them. The conformance test fails on any other
shape.
gen reads these keys with the keys the block's SQL module checks. With
gen.permissionCatalog it writes them as catalog rows, grants every key to the
owner and admin roles and each read key to member, and lists them in
apiKeyScopes and oauthScopes (Permission catalog).
A subject entity registers for search with its title column and the body
columns search lists. search: false keeps it out, and an app replaces the
columns on the entity in blocks.<name>.names (see
Scope and naming).
Declare links and concerns
links lists how the block's entities point at other blocks' entities. Each
link has a key, a kind, the source entity of this block and the target
block and entity. blockLink writes one in a line:
import { blockLink, defineBlock } from "better-supabase/blocks";
export const quotesBlock = defineBlock({
name: "quotes",
category: "commerce",
entities: { quote: { mutability: "state-machine" } },
links: [
blockLink(
"fromDeal",
"conversion",
"quote",
"deals",
"deal",
"quote_from_deal",
),
],
concerns: ["lifecycle", "search"],
});A reference link is a typed pair or a foreign key, a relation link is a
contributed relations kind and a conversion link names the action that
creates the target and records created_from. concerns lists the row-level
concerns the block's tables take part in beyond the audit and event triggers
that every block table gets: history, lifecycle, realtime and search.
The SQL module's NAMES stays the source the SQL renders from, and a test
fails when the manifest and NAMES disagree, so the catalog and the page
generator read the manifest.
The list contract
Every list entity has three reads over one SQL list function (ADR 0749):
page(options) returns a keyset page, facets(options) returns the values of
each declared facet with their counts, and count(options) returns
{ value, exact }. They take the same options, so a page and the counts beside
it always describe the same rows.
| Option | What it does |
|---|---|
q | Free text over the entity's search columns; an entity without search returns invalid_input |
sort | { by, direction? }, where by is one of the entity's sorts, or a list of up to three; the entity's own order when left out. A block that reads one sort orders by the first term and lists the rest in ListPage.sorted.ignored |
filters | Column to a list of values; a row matches any of a filter's values, and an empty list leaves the filter off |
after | The previous page's nextCursor; it is valid only for the sort it came from |
limit | The most rows to return; each list documents its default and cap |
PageSort, SortReport, sortsOf and MAX_PAGE_SORTS come from the same entry. A page you
write yourself reads sortsOf(options.sort), and sets sorted on the page it returns when it
reads fewer terms than it was given (Sort by several columns).
ListPage, PageOptions, FacetOptions, FacetResult, Count and
EntityList are exported from better-supabase/blocks. facets and count
read at most the list's totalCap rows (10,000 by default) and report
exact: false when they stopped there. A sort, filter, facet or text the entity
does not declare returns an invalid_input error before any call is made.
To give a block the contract, for each of its list entities:
- In the SQL module, build the list options with the helpers from
src/sql/list-template.ts. Replace each(v_x is null or x.col = v_x)predicate and itsv_xvariable withfilterAny("key", "x.col", "type")(a flag isfilterFlag("key"), a single valuefilterFirst("key")). Addsorts(a name to its keys, the first key'sdirbeing the default direction) andfacets(a name to its SQL expression). Every key list ends on the row id so the cursor is unique, and a nullable key goes throughcoalesce. Name the new filters,sort,direction,facetandcountin the function's header comment. - In
src/blocks/<block>/lists.ts, export oneEntityListSurfaceper entity withsorts,facets,filtersandsearch, and spread it into the entity's entry in the manifest. The names are the same as in the SQL. - In the client, build
entityList({ entity, surface, call, tenant, fn, rowOf })once and exposepage,facetsandcount(xPage,xFacets,xCountwhen the block has several entities). Remove the block's own page options type. Keeplistas the capped convenience. - Add the manifest to
BLOCKSintests/blocks/list-surface.test.ts, which fails when the manifest and the SQL name different sorts, facets or filters. Add the client test beside the block's others. - Update the golden SQL files (
pnpm --filter better-supabase exec vitest run tests/sql -u), the block's docs page,api/exports.jsonand the changeset's old-to-new table. A change to a manifest field grows the server chunk, so reset the server baseline in the same PR (ADR 0690, 0750).
Bulk, export, import and jobs
Four more calls share one shape across blocks (ADR 0854, 0855, 0856 and 0852). All of them
are exported from better-supabase/blocks.
| Call | What it does |
|---|---|
bulk(ids, action, options) | Runs an action on distinct ids and returns { succeeded, failed: [{ id, error }] }. More ids than the entity's bulk.limit (500 by default) fail with BULK_TOO_MANY before anything runs. |
bulkItems(items, apply, options) | The same report for a value per row: each item is { id, ...value }, a repeated id fails with BULK_DUPLICATE_ID, and the limit counts items (ADR 1075). Name the call bulk<Verb> when an entity has no single action, as drive.bulkShare does. |
export(options) | Streams the rows of page under the same q, filters and sort as CSV, one page at a time, as a ReadableStream<string>. A list built with entityList has it; a block with its own page calls exportCsv(page, options). |
{ jobId } and jobs.get(jobId) | A long call returns { jobId: "<kind>:<id>" }. createJobs({ bulk, import, export, workflow, webhook, queue }) reads the kind off the id and returns one JobResult: status, progress, result, error and done. |
importTarget | A manifest field with the import entities the block takes rows for. importTargetsOf(blocks) from better-supabase/blocks/imports lists them. |
An entity declares its part in the manifest with bulk: { limit, actions } and
export: true | { columns, maxRows }. A download route is
exportResponse(entity.page, "invoices.csv", options), which answers with
text/csv and a Content-Disposition header. An export stops at maxRows
(100,000 by default) with the hint EXPORT_ROW_CAP, and the part already
written stays valid CSV.
Pass format to write another line-oriented format (ADR 1029). csvFormat is the default,
ndjsonFormat writes one JSON object per line, and an ExportFormat of your own has a
contentType, an optional header(columns) and rows(items, columns, escapeFormulas).
exportResponse answers with the format's content type. Formats that write a whole document
(payroll, OSCAL, SEPA, iCalendar) keep their own exports.
import { exportResponse } from "better-supabase/blocks";
export function GET(request: Request) {
const status = new URL(request.url).searchParams.getAll("status");
return exportResponse(
(page) => invoices.page({ ...page, organizationId }),
"invoices.csv",
{ filters: { status } },
);
}An index that serves a sort is still the block's own: the list function seeks into an index on the sort keys only when the table has one, and the page generator (lane M) adds the missing ones.
Four more fields declare what the app has to provide, so add and init can
write it and print the rest (the wiring):
| Field | What it is |
|---|---|
env | The env keys it reads, each { key, description, required? }; add appends them to .env.example |
providers | The implementations it takes, each with its option, type, from, required and a stub example |
routes | The registry items with its routes, without the framework suffix (outbox-relay for outbox-relay-next) |
workers | The crons or processes it needs, with the path and schedule a cron calls |
export const invoicingBlock = defineBlock({
name: "invoicing",
create: createInvoicing,
env: [
{
key: "INVOICING_API_KEY",
description: "Server-only: the invoicing service key.",
},
],
providers: [
{
option: "tax",
type: "TaxProvider",
from: "better-supabase/commerce",
required: false,
description: "Computes tax on invoice lines.",
example: "fixedRates({ rates })",
},
],
});Doctor reads the same fields for the installed blocks: BS504 fails on a required env key no env file lists, and BS505 on a required provider no source passes.
The ports are notifier, files, attachments, workflows, mailer and sink
(the table says who provides each).
A block reaches another block only through a port it consumes, and never
builds another block's client.
Every built-in block follows one contract, which
tests/blocks/conformance.test.ts checks over the manifests: the creator is
create<Name>(options) and takes BlockOptions, it accepts hooks, every
managed table takes fields, every call goes through
blockCall, the block has its own event map, and it builds no other block's
client. The test lists the blocks that don't meet a rule yet; the list only
shrinks.
Last updated on