Skip to content

Sync definitions

Instead of creating roles, event types and subscriptions by hand in each environment, describe them in code next to the feature that uses them and push them with one call. The code is the source of truth, history lives in git, and CI can run the same step against every environment. The concept and the platform behaviour are in Sync definitions; this page is the TypeScript API.

A DefinitionSet belongs to one application. Build it with the fluent builder from the sync namespace (import sync from the package root; there is no @flowcatalyst/sdk/sync entry point):

import { FlowCatalystClient, sync } from '@flowcatalyst/sdk';
const definitions = sync
.defineApplication('orders')
.withRoles([
{ name: 'admin', displayName: 'Administrator', permissions: ['orders:admin:order:*'], clientManaged: false },
])
.withEventTypes([
{ code: 'orders:fulfillment:shipment:shipped', name: 'Shipment Shipped' },
])
.withConnections([{ code: 'orders-webhook', name: 'Orders Webhook' }])
.withSubscriptions([
{
code: 'shipment-tracking',
name: 'Shipment Tracking',
target: 'https://tracking.example.com/webhooks/flowcatalyst',
connectionCode: 'orders-webhook',
eventTypes: [{ eventTypeCode: 'orders:fulfillment:shipment:shipped' }],
dispatchPoolCode: 'default',
mode: 'BLOCK_ON_ERROR',
maxRetries: 5,
timeoutSeconds: 30,
},
])
.build();
const client = new FlowCatalystClient({ /* ... */ });
const result = await client.definitions().sync(definitions, { removeUnlisted: true });

sync.defineApplicationFromEnv() reads the application code from FLOWCATALYST_APP_CODE and throws if it is unset. You can also build the plain DefinitionSet object yourself; every category is optional, and only the categories present are synced.

The builder methods are withRoles, withPermissions, withEventTypes, withConnections, withSubscriptions, withDispatchPools, withPrincipals, withProcesses, withScheduledJobs, withPush, withOpenapiSpec, forClient and build. Repeated calls append.

Category Key fields Notes
Roles name, displayName, description, permissions, clientManaged name is the short name; the platform stores <app>:<name>. Permissions are 4-part strings (app:context:aggregate:action) with * wildcards, or permission() factories. clientManaged: true lets client admins assign the role.
Event types code, name, description code is app:subdomain:aggregate:event; the first segment must be the application. JSON schemas are not synced; add them with client.eventTypes().addSchemaVersion(id, schema) or in the console.
Connections code, name, description, externalId, client Carries nothing environment-specific: the platform assigns the application’s own service account. Synced before subscriptions so connectionCode resolves.
Subscriptions code, name, target, eventTypes, connectionCode, connectionId, sharedConnection, dispatchPoolCode, mode, maxRetries, timeoutSeconds, dataOnly, client See below.
Dispatch pools code, name, description, concurrency, rateLimit concurrency default 10, rateLimit (per minute) default 100. See Pools.
Principals email, name, roles, active Matched by email, on the internal identity provider. roles are short names. Users from an external IdP are not listed here.
Processes code, name, description, body, diagramType, tags Workflow documentation; code is app:subdomain:process; body is stored verbatim (Mermaid by default).
Scheduled jobs code, name, crons, timezone, payload, concurrent, tracksCompletion, timeoutSeconds, deliveryMaxAttempts, targetUrl, clientId crons must be 6-field, seconds-first expressions; a 5-field cron is rejected. See Cron.
Push rules, keys See Push rules and tickets.
OpenAPI withOpenapiSpec(json) Publishes the application’s REST document; each sync replaces the previous version.

Define a permission once and link it from several roles. application defaults to the set’s application code, and build() resolves factories to lower-cased 4-part strings:

import { sync } from '@flowcatalyst/sdk';
const ViewPosts = sync.permission({ context: 'posts', aggregate: 'post', action: 'view' });
const EditPosts = sync.permission({ context: 'posts', aggregate: 'post', action: 'edit' });
const set = sync
.defineApplication('blog')
.withPermissions([ViewPosts, EditPosts])
.withRoles([{ name: 'editor', permissions: [ViewPosts, EditPosts] }])
.build();
// role blog:editor grants blog:posts:post:view and blog:posts:post:edit

There is no standalone “create permission” call: permissions reach the platform through the roles that grant them. The withPermissions catalogue is for reuse in your own code. See Permissions in code and Permissions and roles.

  • target is an absolute URL, sent as is, or a path such as /webhooks/orders. A path resolves against the set’s targetBaseUrl (from forClient(client, targetBaseUrl)), then against the synchroniser’s subscriptionTargetBaseUrl option. There is no further fallback: a blank target, or a path with nothing to resolve against, fails that subscription’s scope locally rather than sending a partial list.
  • connectionCode names a connection owned by this application, unless sharedConnection: true, which names a shared (application-less) connection. There is no fallback between the two; the wrong namespace answers 404 CONNECTION_NOT_FOUND. connectionId is environment-specific, so prefer the code.
  • mode is typed IMMEDIATE | BLOCK_ON_ERROR. Omit it and a new subscription gets the platform default, NEXT_ON_ERROR (deliver a message group in sequence, moving on past a failure), while an existing subscription keeps its stored mode. When you set it, sync applies it on create and on update, so it overwrites a mode changed in the console; a value the platform does not know is refused with INVALID_MODE. BLOCK_ON_ERROR holds a group at a failure until it is resolved, per subscriber. See Ordering.
  • dataOnly: true posts only the event data, not the envelope.
  • eventTypes bindings are { eventTypeCode, filter? }.

Set the base URL once on the synchroniser; the options apply only to the first client.definitions(options) call in a process, because the instance is cached:

const synchroniser = client.definitions({ subscriptionTargetBaseUrl: 'https://api.example.com' });

client.definitions() returns a DefinitionSynchronizer:

Method Use
sync(set, options?) One application.
syncAll(sets, options?) Several applications, in order. Does not merge sets for the same application.
syncGrouped(sets, options?) Merges all sets for the same application, then syncs each application once. Returns Record<applicationCode, SyncResult>.
syncPush(applicationCode, push) Only the push rules and keys.

SyncOptions:

Option Effect
removeUnlisted Delete platform rows created through the SDK that are not in the submission, per category and per (application, client) scope. Console-created rows are always kept. Default false (additive).
skipRoles, skipEventTypes, skipConnections, skipSubscriptions, skipDispatchPools, skipPrincipals, skipProcesses, skipScheduledJobs, skipPush, skipOpenapi Skip a category even if the set carries it.

Categories are synced in this order, each as its own call: roles, event types, connections and subscriptions (per scope), dispatch pools, principals, processes, scheduled jobs, push, OpenAPI. A failure in one category does not roll back earlier ones.

A successful call resolves to a SyncResult: for each category a { created, updated, deleted, syncedCodes, error? } or { skipped: true } (test with sync.isSynced(r.roles)).

If any category or scope failed, the whole call resolves Err, so isErr() is enough to fail a deploy. The error has type: 'partial_failure' and carries the full result, including everything that did sync, as error.partial:

const result = await client.definitions().sync(definitions, { removeUnlisted: true });
if (result.isErr()) {
console.error('Sync failed:', result.error.message);
if (result.error.type === 'partial_failure') {
console.error(JSON.stringify(result.error.partial, null, 2));
}
process.exit(1);
}

A genuine transport or authentication failure is a plain SdkError instead. syncAll and syncGrouped run every set to completion and report partial as a list or a record; a plain SdkError from one set still stops the batch at that point. See Errors.

Several clients (multi-tenant applications)

Section titled “Several clients (multi-tenant applications)”

Connections and subscriptions are scoped per FlowCatalyst client. A row’s client (an identifier slug, never an id) or the set’s .forClient(slug, targetBaseUrl?) decides the scope. The platform treats each (application, client) pair as a separate call, and with removeUnlisted it deletes everything of that scope that the call does not list. The synchroniser therefore makes one call per scope, global scope first, and never merges or splits a scope.

const globalSet = sync.defineApplication('orders')
.withConnections([{ code: 'shared-webhook', name: 'Shared Webhook' }])
.build();
const acmeSet = sync.defineApplication('orders')
.forClient('acme', 'https://acme.example.com')
.withConnections([{ code: 'acme-webhook', name: 'Acme Webhook' }])
.withSubscriptions([{
code: 'acme-orders',
name: 'Acme Orders',
target: '/webhooks/orders', // resolves against acme.example.com
connectionCode: 'acme-webhook',
eventTypes: [{ eventTypeCode: 'orders:sales:order:created' }],
}])
.build();
await client.definitions().syncGrouped([globalSet, acmeSet], { removeUnlisted: true });

Use syncGrouped, not syncAll, whenever more than one set can target the same application. Two sync() calls for one scope are two separate calls, and under removeUnlisted the second deletes what the first just created. The same code twice in one scope is a configuration error that fails that category locally. A tenant you stop yielding is simply no longer synced; its rows are not removed.

Who may listen to a push topic is declared with the other definitions. A client listens when a rule allows it, or when it holds a ticket your backend minted. Rules and ticket keys are a full replace at the gateway, so give both halves every time. See Topics and tickets and Push.

import { sync, TicketMinter } from '@flowcatalyst/sdk';
// PUSH_TICKET_KEY = "kid:base64url-seed" (an Ed25519 32-byte seed; treat as a secret)
const tickets = TicketMinter.fromConfig('shop', process.env.PUSH_TICKET_KEY!, [
// during a rotation, the previous key(s), still published so live tickets verify
]);
const push = {
rules: [
{ pattern: 'shop:orders:{id}', requires: ['shop:orders:order:view'] },
{ pattern: 'shop:user:{principal}' },
{ pattern: 'shop:announcements', public: true },
],
keys: tickets,
};
const definitions = sync.defineApplication('shop').withPush(push).build();
await client.definitions().sync(definitions); // push is one step of sync()
await client.definitions().syncPush('shop', push); // or on its own (a full replace)
  • The first segment of every pattern is the application code. {principal} must equal the subscriber’s principal id, {client} the stream’s client; any other {name} matches one segment.
  • A rule with neither {principal} nor requires must say public: true, and a public rule cannot also require permissions.
  • The gateway refuses, with a code, rules for another application’s patterns, duplicates, more than 200 rules, more than 4 keys, or keys that are not public Ed25519 JWKs. A set without push leaves the gateway as it is; skipPush: true skips it too.
  • Rotation. Add the new key and keep the old one as previous, sync, start signing with the new key, wait one ticket lifetime (at most 5 minutes), drop the old key, sync again. The minter accepts at most three previous keys.

For access a rule cannot express (this user may see order 7 but not order 8), mint a ticket in your own endpoint after your own access check:

const ticket = tickets.mint({
client: 'acme', // the stream's client; '_platform' for platform-wide
topics: ['shop:orders:ord_7', 'shop:orders:ord_8:{part}'],
sub: 'prn_1', // optional, recorded in logs
// jkt: '<dpop key thumbprint>', // optional: the subscribe must prove that key
// ttlSeconds: 60, // 1 to 300, default 60
// streamExp: new Date(/* ... */), // optional: the latest the stream may live
});
// hand `ticket` to the browser; it POSTs { topics, tickets: [ticket] } to {platform}/api/push/subscriptions

A ticket is an EdDSA JWS with iss set to your application code and aud fw-push. mint throws TicketError for a topic outside your application, more than 100 topics, an empty topic list, a lifetime outside 1 to 300 seconds, or a malformed client. tickets.jwks() returns the JWKS that sync sends. This needs Node’s node:crypto (Ed25519). The constants TICKET_AUDIENCE, MAX_TICKET_TTL_SECONDS, DEFAULT_TICKET_TTL_SECONDS and MAX_TICKET_TOPICS are exported.

Keep each module’s definitions beside its code and assemble them in one file:

src/
fulfillment/events.ts // EventTypeDefinition[]
fulfillment/subscriptions.ts // SubscriptionDefinition[]
flowcatalyst.ts // builds the DefinitionSet
scripts/sync-flowcatalyst.ts // calls client.definitions().sync(...)
scripts/sync-flowcatalyst.ts
const result = await client.definitions().sync(appDefinitions, {
removeUnlisted: process.env.FLOWCATALYST_REMOVE_UNLISTED === 'true',
});
if (result.isErr()) process.exit(1);

Sync talks to the platform over HTTP, so test it against fcdev for a real check, or stub the FlowCatalystClient requests. The set itself is plain data: call .build() and assert on the object, for example that permission() factories resolved to the strings you expect. The SDK’s tests (connections-subscriptions-sync.test.ts, push-plan-sync.test.ts, permission-definitions.test.ts) show both approaches.