### Install dependencies Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/postgres/README.md Install the required packages for the Postgres backend. ```bash npm install @iterativeflow/postgres @iterativeflow/core pg ``` -------------------------------- ### Install conformance and core packages Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/conformance/README.md Install the required conformance and core packages as development dependencies. ```bash npm install -D @iterativeflow/conformance @iterativeflow/core ``` -------------------------------- ### Install @iterativeflow/memory and @iterativeflow/core Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/memory/README.md Use npm to install the memory backend and the core iterativeflow package. ```bash npm install @iterativeflow/memory @iterativeflow/core ``` -------------------------------- ### Install @iterativeflow/dashboard and @iterativeflow/core Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/dashboard/README.md Install the required dashboard and core packages via npm. ```bash npm install @iterativeflow/dashboard @iterativeflow/core ``` -------------------------------- ### Initialize Postgres backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/postgres/README.md Setup the Postgres pool, apply the schema, and create the engine. ```typescript import { createEngine } from "@iterativeflow/core"; import { createPgBackend, pgPool, applySchema } from "@iterativeflow/postgres"; import { Pool } from "pg"; const sql = pgPool(new Pool({ connectionString: process.env.DATABASE_URL })); await applySchema(sql); // idempotent; creates the `workflow` schema + tables const engine = createEngine(createPgBackend(sql), [myFlow]); ``` -------------------------------- ### Install IterativeFlow packages Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/README.md Install the core engine and memory backend packages via npm. ```bash npm install @iterativeflow/core @iterativeflow/memory ``` -------------------------------- ### Enable LISTEN/NOTIFY for faster worker wake-ups Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/postgres.md Install triggers and start a listener to reduce latency. Do not use this behind a transaction pooler as it requires a dedicated connection. ```ts import { createPgListener, applyNotifyTriggers } from "@iterativeflow/postgres"; await applyNotifyTriggers(sql); // install the triggers once; skip this behind a pooler const listener = createPgListener(pool); // pass { schema } if you changed it — it must match listener.start(); // opens the LISTEN connection; nothing fires until you call this const backend = createPgBackend(sql, { listener }); // on shutdown, before pool.end(): await listener.close(); ``` -------------------------------- ### Install MySQL backend dependencies Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mysql.md Install the required packages including the MySQL backend, core engine, and the mysql2 driver. ```bash npm install @iterativeflow/mysql @iterativeflow/core mysql2 ``` -------------------------------- ### Install @iterativeflow/dynamodb dependencies Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/dynamodb/README.md Install the required packages to use the DynamoDB backend with iterativeflow. ```bash npm install @iterativeflow/dynamodb @iterativeflow/core @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb ``` -------------------------------- ### Install Notify Triggers Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/postgres.api.md Installs the NOTIFY triggers into the database. Should be run after applySchema. ```typescript declare const applyNotifyTriggers: (sql: Sql, schema?: string) => Promise; ``` -------------------------------- ### Install Redis backend dependencies Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/redis.md Install the required packages for the Redis backend, including the core engine and ioredis. ```bash npm install @iterativeflow/redis @iterativeflow/core ioredis ``` -------------------------------- ### Install SQLite dependencies Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/sqlite.md Install the required packages for using SQLite with IterativeFlow. ```bash npm install @iterativeflow/sqlite @iterativeflow/core @libsql/client ``` -------------------------------- ### Quick start workflow definition and execution Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/core/README.md Define a flow using defineFlow and execute it using the engine with an in-memory backend. ```ts import { createEngine, defineFlow } from "@iterativeflow/core"; import { createMemoryBackend } from "@iterativeflow/memory"; const double = defineFlow<{ x: number }, number>({ name: "double", version: 1, run: async (ctx, input) => ctx.step("d", () => input.x * 2), }); const engine = createEngine(createMemoryBackend(), [double]); const handle = await engine.submit(double, { x: 21 }); const stop = engine.run(); // resident worker loop; returns a stop fn const res = await engine.result(handle, { timeoutMs: 5_000 }); await stop(); // res.output === 42 ``` -------------------------------- ### Install MongoDB dependencies Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mongodb.md Install the required packages for the MongoDB backend, including the peer dependency mongodb. ```bash npm install @iterativeflow/mongodb @iterativeflow/core mongodb ``` -------------------------------- ### Install Durable Objects dependencies Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/durable-objects.md Install the required core and Durable Objects backend packages via npm. ```bash npm install @iterativeflow/durable-objects @iterativeflow/core ``` -------------------------------- ### Run a worker with Redis backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/redis.md Initialize the Redis client and backend, define a flow, and start the engine. ```ts // worker.ts import Redis from "ioredis"; import { createRedisBackend } from "@iterativeflow/redis"; import { createEngine, defineFlow } from "@iterativeflow/core"; const client = new Redis(process.env.REDIS_URL!); const backend = createRedisBackend(client); const greet = defineFlow({ name: "greet", version: 1, run: async (ctx, input: { name: string }) => `hi ${input.name}`, }); const engine = createEngine(backend, [greet]); const stop = engine.run(); await engine.submit(greet, { name: "world" }); // on shutdown: await stop(); await client.quit(); ``` -------------------------------- ### Engine.run Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Starts a resident worker loop for continuous workflow processing. ```APIDOC ## Engine.run(opts?) ### Description Starts a resident worker loop that handles ticks and maintenance. Returns a function that can be called to stop the loop. ### Parameters - **opts** (RunLoopOpts) - Optional - Configuration options for the worker loop. ``` -------------------------------- ### Initialize MySQL backend for iterativeflow Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/mysql/README.md Configures the MySQL pool using mysql2 and initializes the iterativeflow engine with the MySQL backend. Ensure the schema is applied using applySchema before starting the engine. ```ts import { createPool } from "mysql2/promise"; import { createMysqlBackend, applySchema, mysqlPool } from "@iterativeflow/mysql"; import { createEngine } from "@iterativeflow/core"; const sql = mysqlPool(createPool(process.env.MYSQL_URL)); await applySchema(sql); const engine = createEngine(createMysqlBackend(sql), [ /* your flows */ ]); ``` -------------------------------- ### applyNotifyTriggers Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/postgres.api.md Installs NOTIFY triggers for the workflow system. ```APIDOC ## applyNotifyTriggers(sql: Sql, schema?: string) ### Description Installs the NOTIFY triggers required for event signaling. This should be run once after `applySchema`. ### Parameters - **sql** (Sql) - Required - The SQL interface instance. - **schema** (string) - Optional - The Postgres schema name. ``` -------------------------------- ### Define and execute a durable workflow Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/README.md This example demonstrates defining a workflow with a durable sleep and signal, configuring a Postgres backend, and executing the flow. ```ts import { createEngine, defineFlow, signalType } from "@iterativeflow/core"; import { createPgBackend, pgPool } from "@iterativeflow/postgres"; import { Pool } from "pg"; const onboard = defineFlow({ name: "onboard", version: 1, signals: { survey: signalType<{ score: number }>() }, // declare the signal's payload type run: async (ctx, input: { userId: string }): Promise<{ score: number }> => { await ctx.step("create-account", () => createAccount(input.userId)); await ctx.sleep(3 * 24 * 60 * 60_000); // 3 days, durable const survey = await ctx.signal("survey"); // typed { score: number } return { score: survey.score }; }, }); const engine = createEngine(createPgBackend(pgPool(new Pool())), [onboard]); const stop = engine.run(); // resident worker loop; returns a stop fn const handle = await engine.submit(onboard, { userId: "u_1" }); // 3 days later, from a webhook: await engine.signal(handle, "survey", { score: 9 }); const { output } = await engine.result(handle); // { score: 9 } await stop(); ``` -------------------------------- ### Run a worker with SQLite backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/sqlite.md Initializes the SQLite backend and engine to execute flows. The engine is started and stopped using the returned stop function. ```ts // worker.ts import { createSqliteBackend } from "@iterativeflow/sqlite"; import { createEngine, defineFlow } from "@iterativeflow/core"; import { sql } from "./db"; const backend = createSqliteBackend(sql); const greet = defineFlow({ name: "greet", version: 1, run: async (ctx, input: { name: string }) => `hi ${input.name}`, }); const engine = createEngine(backend, [greet]); const stop = engine.run(); await engine.submit(greet, { name: "world" }); // on shutdown: await stop(); ``` -------------------------------- ### Initialize and run a persistent worker Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/postgres.md Configures the Postgres backend and starts the engine to process flows until stopped. ```ts // worker.ts import { createPgBackend } from "@iterativeflow/postgres"; import { createEngine, defineFlow, submit } from "@iterativeflow/core"; import { sql, pool } from "./db"; const backend = createPgBackend(sql); // pass { schema: "flows" } if you changed it const greet = defineFlow({ name: "greet", version: 1, run: async (ctx, input: { name: string }) => `hi ${input.name}`, }); const engine = createEngine(backend, [greet]); const stop = engine.run(); // claims and runs work until you call stop() await engine.submit(greet, { name: "world" }); // on shutdown: await stop(); await pool.end(); ``` -------------------------------- ### Query pending work for autoscaling Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mysql.md Examples of calling the pending_work function to check the backlog for the whole system or a specific flow shard. ```sql SELECT pending_work(NULL, UNIX_TIMESTAMP(NOW(3)) * 1000); -- whole backlog SELECT pending_work(JSON_ARRAY('greet'), UNIX_TIMESTAMP(NOW(3)) * 1000); -- one flow's shard ``` -------------------------------- ### Set up the database with applySchema Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/sqlite.md Initialize the database client and apply the schema to configure WAL mode and performance defaults. ```ts // db.ts import { createClient } from "@libsql/client"; import { libsqlDb, applySchema } from "@iterativeflow/sqlite"; export const client = createClient({ url: "file:iterativeflow.db" }); export const sql = libsqlDb(client); await applySchema(sql); ``` -------------------------------- ### Set up the database schema Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mysql.md Initialize the database pool and apply the required engine schema using db.ts. ```typescript // db.ts import { createPool } from "mysql2/promise"; import { mysqlPool, applySchema } from "@iterativeflow/mysql"; export const pool = createPool(process.env.DATABASE_URL!); export const sql = mysqlPool(pool); await applySchema(sql); ``` -------------------------------- ### Set up the database schema Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/postgres.md Initialize the engine tables and functions using applySchema. This operation is idempotent and can be run on every boot or as a migration. ```ts // db.ts import { Pool } from "pg"; import { pgPool, applySchema } from "@iterativeflow/postgres"; export const pool = new Pool({ connectionString: process.env.DATABASE_URL }); export const sql = pgPool(pool); await applySchema(sql); ``` -------------------------------- ### Set up the DynamoDB table Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/dynamodb.md Initialize the DynamoDB client and ensure the required table exists using ensureTable. ```ts // db.ts import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { docClient, ensureTable } from "@iterativeflow/dynamodb"; export const low = new DynamoDBClient({}); export const doc = docClient(low); await ensureTable(low); // creates the "iterativeflow" table + index if absent ``` -------------------------------- ### Initialize iterativeflow with MongoDB backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/mongodb/README.md Demonstrates how to connect to a MongoDB replica set, ensure necessary indexes, and initialize the iterativeflow engine. ```ts import { MongoClient } from "mongodb"; import { createMongoBackend, ensureIndexes } from "@iterativeflow/mongodb"; import { createEngine } from "@iterativeflow/core"; const client = new MongoClient(process.env.MONGO_URL); // a replica-set connection string await client.connect(); await ensureIndexes(client.db("iterativeflow")); const engine = createEngine(createMongoBackend(client), [ /* your flows */ ]); ``` -------------------------------- ### createDashboard(engine, opts) Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/dashboard.api.md Creates a mountable dashboard as a single Web fetch handler. It serves a self-contained UI at the base path and a JSON API under /api over the engine query and control surface. ```APIDOC ## createDashboard(engine, opts) ### Description Creates a mountable dashboard as a single Web `fetch` handler. It works in Node 18+, Bun, Deno, and edge/workers, or behind a thin Express/Hono adapter. ### Signature `createDashboard(engine: Engine, opts?: DashboardOpts) => (req: Request) => Promise` ### Parameters - **engine** (Engine) - Required - The IterativeFlow engine instance. - **opts** (DashboardOpts) - Optional - Configuration options for the dashboard. ### DashboardOpts - **basePath** (string) - Optional - URL prefix the dashboard is mounted under (e.g., "/admin/flows"). - **events** (function) - Optional - A function that fetches a run's event timeline, taking a `runId` (string) and returning a `Promise`. ``` -------------------------------- ### Set up the database with ensureIndexes Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mongodb.md Initialize the MongoClient and create the necessary indexes for the engine using ensureIndexes. This operation is idempotent. ```ts // db.ts import { MongoClient } from "mongodb"; import { ensureIndexes } from "@iterativeflow/mongodb"; export const client = new MongoClient(process.env.MONGO_URL!, { writeConcern: { w: "majority" } }); await client.connect(); await ensureIndexes(client.db("iterativeflow")); ``` -------------------------------- ### Define and run a basic flow Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/README.md Create a flow using defineFlow, initialize the engine with a memory backend, and execute the flow. ```ts import { createEngine, defineFlow } from "@iterativeflow/core"; import { createMemoryBackend } from "@iterativeflow/memory"; const double = defineFlow<{ x: number }, number>({ name: "double", version: 1, run: async (ctx, input) => ctx.step("d", () => input.x * 2), }); const engine = createEngine(createMemoryBackend(), [double]); const stop = engine.run(); const handle = await engine.submit(double, { x: 21 }); const res = await engine.result(handle, { timeoutMs: 5_000 }); await stop(); // res.output === 42 ``` -------------------------------- ### Initialize Engine with Memory Backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/memory/README.md Import createEngine and createMemoryBackend to initialize the iterativeflow engine with an in-memory backend. ```ts import { createEngine, defineFlow } from "@iterativeflow/core"; import { createMemoryBackend } from "@iterativeflow/memory"; const engine = createEngine(createMemoryBackend(), [myFlow]); ``` -------------------------------- ### Create and mount the dashboard handler Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/dashboard/README.md Initialize the dashboard with an engine and mount it to a fetch-native server route. ```ts import { createDashboard } from "@iterativeflow/dashboard"; const handler = createDashboard(engine, { basePath: "/admin/flows" }); // Mount on any fetch-native server (Hono, Bun, Next route handler, Workers): app.all("/admin/flows/*", (c) => handler(c.req.raw)); ``` -------------------------------- ### Serverless execution cycle with engine.serverlessTick Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/core/README.md Demonstrates how to use engine.serverlessTick to drive a single reconciliation cycle and schedule the next wake-up time for serverless environments. ```ts const { nextWakeAt } = await engine.serverlessTick(); if (nextWakeAt) await scheduleOneShot(nextWakeAt); // else: nothing pending — exit; a push on submit/signal starts the next cycle. ``` -------------------------------- ### createSqliteBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Creates a SQLite Backend instance using a provided Sql connection. ```APIDOC ## createSqliteBackend(sql: Sql, opts?: SqliteBackendOpts) ### Description Creates the SQLite {@link Backend} using the provided {@link Sql} connection. Store, Queue, and Timer share the database to ensure atomic outbox commits. ### Parameters - **sql** (Sql) - Required - The database connection interface. - **opts** (SqliteBackendOpts) - Optional - Configuration options including table name prefix and ID generator. ``` -------------------------------- ### Access pending work metrics Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/dashboard/CHANGELOG.md The engine.pendingWork method returns the count of claimable jobs, due timers, and due crons, which is exposed via the dashboard's GET /api/metrics endpoint. ```typescript engine.pendingWork(names?) ``` -------------------------------- ### createPgListener Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/postgres.api.md Initializes a LISTEN connection to multiplex channels for a specific schema, enabling real-time notifications for workflow progress and work dispatch. ```APIDOC ## createPgListener(pool, opts) ### Description Creates a listener that manages a Postgres LISTEN connection. It handles reconnection with backoff and provides mechanisms to wake up workers or observers when events occur. ### Parameters - **pool** (Pool) - Required - The Postgres connection pool. - **opts** (PgListenerOpts) - Optional - Configuration object containing the `schema` to listen on. ``` -------------------------------- ### Set up and run engine inside a Durable Object Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/durable-objects.md Initialize the backend and engine within the Durable Object class, applying the schema in the constructor and driving the engine via serverlessTick in an alarm method. ```ts // MyFlowObject.ts import { createDurableObjectBackend, applySchema } from "@iterativeflow/durable-objects"; import { createEngine, defineFlow, serverlessTick, registry } from "@iterativeflow/core"; const greet = defineFlow({ name: "greet", version: 1, run: async (ctx, input: { name: string }) => `hi ${input.name}`, }); export class MyFlowObject { private backend; private engine; constructor(private ctx: DurableObjectState) { this.backend = createDurableObjectBackend(ctx.storage.sql); this.engine = createEngine(this.backend, [greet]); ctx.blockConcurrencyWhile(async () => { await applySchema(ctx.storage.sql); // once, before the first request }); } async submit(name: string) { return this.engine.submit(greet, { name }); } // Drive one pass on an alarm; use nextWakeAt to set the next alarm. async alarm() { const { nextWakeAt } = await serverlessTick(this.backend, registry([greet]), { batchMax: 16, leaseMs: 30_000, }); if (nextWakeAt) await this.ctx.storage.setAlarm(nextWakeAt); } } ``` -------------------------------- ### Initialize WorkflowDO with Durable Object Backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/durable-objects/README.md Shows how to set up a Durable Object class to use the iterativeflow engine with the Durable Object SQLite storage backend. ```ts import { createDurableObjectBackend, applySchema } from "@iterativeflow/durable-objects"; import { createEngine } from "@iterativeflow/core"; export class WorkflowDO { #engine; constructor(ctx: DurableObjectState) { ctx.blockConcurrencyWhile(() => applySchema(ctx.storage.sql)); this.#engine = createEngine(createDurableObjectBackend(ctx.storage.sql), [ /* your flows */ ]); } // drive the engine from an alarm() handler or fetch() } ``` -------------------------------- ### createMongoBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/mongodb.api.md Initializes a MongoDB backend instance using a provided MongoClient and optional configuration. ```APIDOC ## createMongoBackend(client, opts?, boundSession?) ### Description Creates a MongoDB Backend instance. The backend requires a replica set deployment to support multi-document transactions. ### Parameters - **client** (MongoClient) - Required - The MongoDB client instance. - **opts** (MongoBackendOpts) - Optional - Configuration options including database name, collection prefix, and ID generator. - **boundSession** (ClientSession) - Optional - A session to bind to the backend. ``` -------------------------------- ### createOpSqliteBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Builds a SQLite Backend directly on an op-sqlite database. ```APIDOC ## createOpSqliteBackend(db: OpSqliteDB, opts?: SqliteBackendOpts) ### Description Builds the SQLite {@link Backend} directly on an op-sqlite database. Run {@link applySchema} once before first use. ``` -------------------------------- ### createPgBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/postgres.api.md Creates a Postgres-backed workflow engine instance that manages storage, queues, and timers within a single transactional domain. ```APIDOC ## createPgBackend(sql, opts) ### Description Initializes the backend using a provided SQL connection source. It integrates with the listener to support transactional enqueueing and completion notifications. ### Parameters - **sql** (Sql) - Required - The SQL interface for database operations. - **opts** (PgBackendOpts) - Optional - Configuration including `schema`, `id` generator, and `listener` instance. ``` -------------------------------- ### createRedisBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/redis.api.md Initializes a new Redis backend for iterativeflow using an existing ioredis client instance. ```APIDOC ## createRedisBackend ### Description Creates a Redis backend instance that implements the iterativeflow Backend interface. It uses an ioredis client to manage storage, queues, and timers within a shared keyspace. ### Signature `createRedisBackend(client: RedisClient, opts?: RedisBackendOpts): Backend` ### Parameters - **client** (RedisClient) - Required - An ioredis connection instance (e.g., `new Redis(url)` or a Cluster). - **opts** (RedisBackendOpts) - Optional - Configuration options for the backend. #### RedisBackendOpts - **prefix** (string) - Optional - Key prefix for namespacing. Defaults to `iterativeflow`. - **id** (IdGen) - Optional - Id generator for runs, signals, and lease tokens. Defaults to RFC-4122 v4. ``` -------------------------------- ### createMysqlBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/mysql.api.md Creates a MySQL-backed workflow engine. ```APIDOC ## createMysqlBackend(sql: Sql, opts?: MysqlBackendOpts) ### Description Initializes the MySQL Backend, which provides the four ports (Store, Queue, Timer, etc.) over a single Sql connection. ### Parameters - **sql** (Sql) - Required - The Sql interface instance. - **opts** (MysqlBackendOpts) - Optional - Configuration including `prefix` for table names and `id` generator. ``` -------------------------------- ### createSqliteBackend Factory Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Creates a Backend instance using the provided Sql connection and options. ```ts declare const createSqliteBackend: (sql: Sql, opts?: SqliteBackendOpts) => Backend; ``` -------------------------------- ### createEngine Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Initializes a new workflow engine instance with a specified backend and flow definitions. ```APIDOC ## createEngine(backend, flows, opts?) ### Description Creates and returns an Engine instance to manage workflow execution. ### Parameters - **backend** (Backend) - Required - The storage backend for the engine. - **flows** (readonly AnyFlow[]) - Required - A list of flow definitions. - **opts** (EngineOpts) - Optional - Configuration options for the engine. ``` -------------------------------- ### webhookSignalBridge(backend, opts) Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/webhooks.api.md Initializes a webhook signal bridge with the provided backend and configuration options. ```APIDOC ## webhookSignalBridge(backend, opts) ### Description Initializes a bridge for webhook signals. This function processes incoming requests and verifies them using the provided backend and options. ### Parameters - **backend** (Backend) - Required - The backend instance used for signal processing. - **opts** (WebhookSignalBridgeOptions) - Required - Configuration options for the bridge. ### Throws - **WebhookError** - Thrown when verification fails, indicating the request should be rejected as untrusted. ``` -------------------------------- ### Initialize Webhook Bridge and Handle Requests Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/webhooks/README.md Configures the webhook bridge with a GitHub verifier and a correlation function, then demonstrates how to handle incoming webhook requests in an HTTP handler. ```ts import { webhookSignalBridge, github } from "@iterativeflow/webhooks"; const bridge = webhookSignalBridge(backend, { verify: github(process.env.GITHUB_WEBHOOK_SECRET!), // Map a verified event to the parked run(s) it concerns. `correlate` owns the app's // "PR 42 → runId" lookup — the bridge can't know it. correlate: async (event) => { if (event.type !== "issue_comment") return []; const pr = (event.payload as { issue: { number: number } }).issue.number; const runId = await findRunForPr(pr); // your state return runId ? [{ runId, name: "qa:approved", payload: event.payload }] : []; }, }); // In your HTTP handler — pass the RAW body (the bytes GitHub signed): app.post("/webhooks/github", async (req) => { const result = await bridge({ body: await req.text(), headers: req.headers }); return Response.json(result); // { type, id, deliveries: [{ runId, name, delivered }] } }); ``` -------------------------------- ### createOpSqliteBackend Factory Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Builds a Backend instance directly on an op-sqlite database. ```ts declare const createOpSqliteBackend: (db: OpSqliteDB, opts?: SqliteBackendOpts) => Backend; ``` -------------------------------- ### Enable low-latency push with LISTEN/NOTIFY Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/postgres/README.md Configure triggers and a listener to enable instant push notifications for resident deployments. ```typescript import { applyNotifyTriggers, createPgListener, createPgBackend } from "@iterativeflow/postgres"; await applyNotifyTriggers(sql); // once, alongside applySchema — installs the two triggers const listener = createPgListener(pool, { schema: "workflow" }); listener.start(); // one dedicated LISTEN connection, reconnects with backoff const backend = createPgBackend(sql, { listener }); // wires BOTH push seams off the one listener const engine = createEngine(backend, flows); engine.run(); // claim loop wakes on enqueue; result() waiters wake on completion — no extra wiring ``` -------------------------------- ### createDurableObjectBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/durable-objects.api.md Creates a Backend instance backed by a Durable Object's SQLite storage. ```APIDOC ## createDurableObjectBackend(storage: SqlStorage, opts?: SqliteBackendOpts) ### Description Creates a Backend instance that uses a Durable Object's `ctx.storage.sql` as its storage layer. This allows the full iterativeflow SQLite backend to run inside a Durable Object. ### Parameters - **storage** (SqlStorage) - Required - The Durable Object's SQLite storage interface. - **opts** (SqliteBackendOpts) - Optional - Configuration options for the SQLite backend. ### Returns - **Backend** - An initialized backend instance. ``` -------------------------------- ### createDynamoBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/dynamodb.api.md Initializes the DynamoDB backend implementation for IterativeFlow. ```APIDOC ## createDynamoBackend(doc: Doc, opts?: DynamoBackendOpts) ### Description Creates a Backend instance using a provided document client and table configuration. This backend enables the Store, Queue, and Timer ports to operate over a single transactional DynamoDB table. ### Parameters - **doc** (Doc) - Required - An object exposing a `send` method (e.g., DynamoDBDocumentClient). - **opts** (DynamoBackendOpts) - Optional - Configuration options including table name and ID generator. ``` -------------------------------- ### Initialize Redis Backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/redis/README.md Configures the iterativeflow engine using a Redis backend initialized with an ioredis client. ```ts import { Redis } from "ioredis"; import { createRedisBackend } from "@iterativeflow/redis"; import { createEngine, defineFlow } from "@iterativeflow/core"; const backend = createRedisBackend(new Redis(process.env.REDIS_URL)); const engine = createEngine(backend, [ /* your flows */ ]); ``` -------------------------------- ### opSqliteDb Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Adapts an op-sqlite database to the Sql interface. ```APIDOC ## opSqliteDb(db: OpSqliteDB) ### Description Adapts an [op-sqlite](https://op-engineering.github.io/op-sqlite) database to the sqlite backend's {@link Sql} interface. It handles transaction management (BEGIN IMMEDIATE/COMMIT/ROLLBACK) manually to ensure deterministic behavior. ``` -------------------------------- ### Create Memory Backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/memory.api.md Initializes an in-memory backend that provides atomic, synchronous mutations. It is designed to pass conformance suites and act as an oracle for real backend implementations. ```ts import { Backend, IdGen } from "@iterativeflow/core/backend"; //#region src/backend.d.ts /** * The in-memory reference backend: the four ports over one shared, single-threaded state. * Because every mutation core is synchronous, an outbox commits with no `await` boundary * in between — genuinely atomic, exactly what a Postgres `BEGIN…COMMIT` or a DynamoDB * `TransactWriteItems` buys on a real backend. It passes every `*Conformance` suite, * including `outboxConformance`, so it doubles as the oracle every real backend must match. */ declare const createMemoryBackend: ({ id: idGen }?: { id?: IdGen; }) => Backend; ``` -------------------------------- ### libsqlDb Adapter Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Adapts a @libsql/client Client to the Sql interface, where tx opens a single write transaction. ```ts declare const libsqlDb: (client: Client) => Sql; ``` -------------------------------- ### Initialize iterativeflow with SQLite Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/sqlite/README.md Configures the iterativeflow engine using a libSQL client and the SQLite backend. Ensure applySchema is called before initializing the engine. ```ts import { createClient } from "@libsql/client"; import { createSqliteBackend, applySchema, libsqlDb } from "@iterativeflow/sqlite"; import { createEngine } from "@iterativeflow/core"; const sql = libsqlDb(createClient({ url: "file:workflow.db" })); // or a Turso url await applySchema(sql); const engine = createEngine(createSqliteBackend(sql), [ /* your flows */ ]); ``` -------------------------------- ### Store Interface and StartResult Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Defines the Store port for durable checkpointing and the StartResult structure for run creation. Implementations must adhere to the design invariant of one durable write per step. ```typescript interface StartResult { runId: string; created: boolean; status: RunStatus; } interface Store { startRun(spec: RunSpec): Promise; startManyRuns(specs: readonly RunSpec[]): Promise; loadRun(runId: string): Promise; loadRunRow(runId: string): Promise; loadRunRows(runIds: readonly string[]): Promise<(RunRow | undefined)[]>; arriveAtJoin(parentRunId: string, childRunId: string): Promise; } ``` -------------------------------- ### createMemoryBackend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/memory.api.md Creates an in-memory reference backend that manages shared, single-threaded state for atomic operations. ```APIDOC ## createMemoryBackend ### Description Creates an in-memory reference backend. This backend provides atomic operations and is designed to pass conformance suites, serving as an oracle for real backend implementations. ### Signature `createMemoryBackend({ id?: IdGen }): Backend` ### Parameters - **id** (IdGen) - Optional - A custom ID generator function. ``` -------------------------------- ### Define Flow with Signal Await Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/webhooks/README.md Shows how to park a flow execution until a specific signal is received from a webhook. ```ts const qa = defineFlow({ name: "qa", version: 1, run: async (ctx, input) => { const approval = await ctx.signal("qa:approved"); // parks until the webhook arrives return runQa(input, approval); }, }); ``` -------------------------------- ### Engine.serverlessTick Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Executes a single cycle for scheduled invocations, suitable for serverless environments. ```APIDOC ## Engine.serverlessTick() ### Description Performs one full cycle for a scheduled invocation (crons, reconcile, drain, claim). Designed to be called from an EventBridge or cron Lambda. ``` -------------------------------- ### Run a worker with DynamoDB backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/dynamodb.md Configure the engine with the DynamoDB backend and execute a flow. ```ts // worker.ts import { createDynamoBackend } from "@iterativeflow/dynamodb"; import { createEngine, defineFlow } from "@iterativeflow/core"; import { doc } from "./db"; const backend = createDynamoBackend(doc); const greet = defineFlow({ name: "greet", version: 1, run: async (ctx, input: { name: string }) => `hi ${input.name}`, }); const engine = createEngine(backend, [greet]); const stop = engine.run(); await engine.submit(greet, { name: "world" }); // on shutdown: await stop(); ``` -------------------------------- ### Ctx.step Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Executes a function once and memoizes its result, ensuring exactly-once execution across crashes. ```APIDOC ## step(name: string, fn: (arg: StepArg) => Promise | T, policy?: StepPolicy): Promise ### Description Run `fn` once and memoize its result. On replay the stored result is returned and `fn` is NOT re-run. `fn` is at-least-once across a crash BEFORE the checkpoint commits, so keep its side-effects idempotent; the memo is exactly-once. ### Parameters - **name** (string) - Required - Unique identifier for the step. - **fn** (function) - Required - The function to execute. - **policy** (StepPolicy) - Optional - Execution policy including retries, timeout, and error classification. ``` -------------------------------- ### Engine Configuration and Liveness Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Defines the liveness snapshot structure and default engine configuration options. ```typescript interface Liveness { queue: QueueDepth; runs: Record; } interface EngineOpts { batchMax?: number; leaseMs?: number; retry?: RetryPolicy; observe?: ObserveOpts; id?: IdGen; now?: Clock; } ``` -------------------------------- ### SqliteBackendOpts Configuration Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Options for configuring the SQLite backend, including table name prefixes and custom ID generators. ```ts interface SqliteBackendOpts { /** Table-name prefix, for running multiple engines in one database. Default none. */ prefix?: string; /** Id generator for runs, signals, and lease tokens. Defaults to {@link newId} (RFC-4122 v4). */ id?: IdGen; } ``` -------------------------------- ### doStorageSql Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/durable-objects.api.md Adapts a Durable Object's SQLite storage to the Sql seam. ```APIDOC ## doStorageSql(storage: SqlStorage) ### Description Adapts a Durable Object's `ctx.storage.sql` to the iterativeflow SQLite backend's `Sql` seam. This allows the backend to interact with the DO storage directly. ### Parameters - **storage** (SqlStorage) - Required - The Durable Object's SQLite storage interface. ### Returns - **Sql** - The adapted SQL interface. ``` -------------------------------- ### Initialize the iterativeflow engine with DynamoDB Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/dynamodb/README.md Configure the engine using the DynamoDB backend. The ensureTable function is intended for development use and requires CreateTable IAM permissions. ```typescript import { createEngine } from "@iterativeflow/core"; import { createDynamoBackend, docClient, ensureTable } from "@iterativeflow/dynamodb"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; const low = new DynamoDBClient({}); await ensureTable(low, "iterativeflow"); // dev only; needs CreateTable IAM const engine = createEngine(createDynamoBackend(docClient(low), { table: "iterativeflow" }), [ myFlow, ]); ``` -------------------------------- ### Dashboard Configuration and Creation Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/dashboard.api.md Defines the DashboardOpts interface for configuring the dashboard and the createDashboard function to serve a self-contained UI and JSON API. ```ts import { Engine, FlowEvent } from "@iterativeflow/core"; //#region src/api.d.ts /** Dashboard configuration. `events` supplies the durable timeline (e.g. postgres `listEvents`). */ interface DashboardOpts { /** URL prefix the dashboard is mounted under (e.g. "/admin/flows"). Default none. */ basePath?: string; /** Fetch a run's event timeline. Omit if the backend records no events. */ events?: (runId: string) => Promise; } /** * A mountable dashboard as a single Web `fetch` handler — works in Node 18+, Bun, Deno, and * edge/workers, or behind a thin Express/Hono adapter. Serves a self-contained UI at the base * path and a JSON API under `/api` over the {@link Engine} query + control surface. */ declare const createDashboard: (engine: Engine, opts?: DashboardOpts) => ((req: Request) => Promise); //#endregion export { type DashboardOpts, createDashboard }; ``` -------------------------------- ### Register conformance suites Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/packages/conformance/README.md Register the store and engine conformance suites at the top level of a test file, providing a factory function that returns a fresh backend instance. ```ts import { storeConformance, engineConformance } from "@iterativeflow/conformance"; import { createMyBackend } from "./backend"; storeConformance("my-backend", () => createMyBackend()); engineConformance("my-backend", () => createMyBackend()); ``` -------------------------------- ### libsqlDb Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Adapts a @libsql/client Client to the Sql interface, enabling transactional operations. ```APIDOC ## libsqlDb(client: Client) ### Description Adapts a `@libsql/client` {@link Client} to the internal {@link Sql} interface. The `tx` method opens one write transaction. ### Parameters - **client** (Client) - Required - The libSQL client instance. ``` -------------------------------- ### webhookSignalBridge(options: WebhookSignalBridgeOptions) Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/webhooks.api.md Creates a handler that verifies a webhook and maps it to signal deliveries for durable runs. ```APIDOC ## webhookSignalBridge(options: WebhookSignalBridgeOptions) ### Description Creates a bridge handler that verifies an incoming webhook and correlates it to specific run signals. This allows external events to wake up parked flows. ### Parameters - **options** (WebhookSignalBridgeOptions) - Required - Configuration containing the verifier and the correlation logic. ### Returns - **WebhookSignalBridge** - A function that processes the raw request body and headers, returning a BridgeResult. ``` -------------------------------- ### opSqliteDb Adapter Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Adapts an op-sqlite database to the Sql interface, handling transaction logic internally. ```ts declare const opSqliteDb: (db: OpSqliteDB) => Sql; ``` -------------------------------- ### Initialize and run a worker with MongoDB backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mongodb.md Configures the MongoDB backend and engine to execute flows, including shutdown procedures. ```ts // worker.ts import { createMongoBackend } from "@iterativeflow/mongodb"; import { createEngine, defineFlow } from "@iterativeflow/core"; import { client } from "./db"; const backend = createMongoBackend(client, { db: "iterativeflow" }); const greet = defineFlow({ name: "greet", version: 1, run: async (ctx, input: { name: string }) => `hi ${input.name}`, }); const engine = createEngine(backend, [greet]); const stop = engine.run(); await engine.submit(greet, { name: "world" }); // on shutdown: await stop(); await client.close(); ``` -------------------------------- ### Ctx.invoke Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Spawns a child flow or a set of parallel child flows. ```APIDOC ## invoke(flow: Flow, input: CI): Promise ### Description Spawn `flow(input)` as a child run and return its output. The child is created exactly once (recorded in the step memo); the parent parks until the child completes. ### Parameters - **flow** (Flow) - Required - The flow definition to invoke. - **input** (CI) - Required - The input data for the child flow. ``` -------------------------------- ### Configure op-sqlite for React Native Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/sqlite.md Sets up the op-sqlite adapter for on-device durable execution. Open one database connection and reuse it to avoid multi-connection issues. ```ts import { open } from "@op-engineering/op-sqlite"; import { opSqliteDb, createOpSqliteBackend, applySchema } from "@iterativeflow/sqlite"; const db = open({ name: "iterativeflow.db" }); const sql = opSqliteDb(db); await applySchema(sql); const backend = createOpSqliteBackend(sql); ``` -------------------------------- ### Run transactions with inTx Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mysql.md Use inTx to execute submit or enqueue operations alongside custom database writes within a single transaction. ```javascript inTx(pool, (backend, tx) => ...) ``` -------------------------------- ### serverlessTick Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Executes a full engine cycle for a serverless invocation, including firing crons and driving orphans. ```APIDOC ## serverlessTick(backend, flows, opts) ### Description Performs a full engine cycle designed for serverless environments (e.g., Lambda). It fires due crons, re-drives orphans, and executes a batch of flows. ### Parameters - **backend** (Backend) - Required - The backend instance. - **flows** (FlowRegistry) - Required - The flow registry. - **opts** (TickOnceOpts) - Required - Configuration options for the cycle. ``` -------------------------------- ### OpSqliteDB Interface Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Structural interface for op-sqlite database compatibility, supporting both synchronous and asynchronous execution. ```ts interface OpSqliteDB { execute(sql: string, params?: unknown[]): OpSqliteResult | Promise; } ``` -------------------------------- ### Query pending work for autoscaling Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/postgres.md Retrieves the current backlog of claimable jobs, timers, and crons to inform KEDA autoscalers. ```sql SELECT workflow.pending_work(); -- whole backlog SELECT workflow.pending_work(ARRAY['greet']); -- one flow's shard ``` -------------------------------- ### Ctx.log Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Emits a durable log line to the event sink. ```APIDOC ## log(message: string, data?: unknown): void ### Description Emit a durable log line to the event sink (visible on the dashboard timeline), tagged to this run. Fire-and-forget and NOT memoized. ### Parameters - **message** (string) - Required - The log message. - **data** (unknown) - Optional - Additional data to log. ``` -------------------------------- ### Create Local Wakeup Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Initializes a process-local, edge-triggered Wakeup instance. This is a connection-safe default that does not require persistent connections like LISTEN or streams, making it compatible with RDS Proxy or PgBouncer. ```ts declare const createLocalWakeup: () => Wakeup; ``` -------------------------------- ### mysqlPool Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/mysql.api.md Adapts a mysql2/promise Pool to the Sql interface required by the backend. ```APIDOC ## mysqlPool(pool: Pool, opts?: MysqlPoolOpts) ### Description Adapts a `mysql2/promise` Pool to the `Sql` interface. The `tx` method checks out one connection for the unit of work. ### Parameters - **pool** (Pool) - Required - The mysql2/promise pool instance. - **opts** (MysqlPoolOpts) - Optional - Configuration options including `setIsolation` (default true). ``` -------------------------------- ### Wakeup Interface Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md The Wakeup interface handles completion-signaling, allowing for low-latency wakeups or poll-based waiting. ```APIDOC ## Wakeup Interface ### Methods - **wait(runId: string, timeoutMs: number): Promise** - Block up to `timeoutMs`, returning early if a signal for `runId` arrives. - **signal(runId: string): Promise** - Wake any current waiters on `runId`. ``` -------------------------------- ### submit Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Submits a workflow run, creating it idempotently and enqueuing it if it is a new run. ```APIDOC ## submit ### Description Creates a workflow run (idempotent) and enqueues it if freshly created. Returns a typed handle for the run. ### Signature `submit(backend: Backend, flow: Flow | Contract, input: I, opts?: SubmitOpts, now?: Clock) => Promise>` ``` -------------------------------- ### arriveAtJoin method Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md Decrements the join countdown for a parent run. The executor wakes the parent when the count reaches zero. ```typescript arriveAtJoin(parentRunId: string): Promise; ``` -------------------------------- ### applySchema Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/sqlite.api.md Applies the required database schema DDL to the SQLite database. ```APIDOC ## applySchema(sql: Sql, prefix?: string, opts?: ApplySchemaOpts) ### Description Applies the schema DDL idempotently. On file stores, it also configures safe PRAGMAs like WAL mode and busy_timeout. ### Parameters - **sql** (Sql) - Required - The database connection interface. - **prefix** (string) - Optional - Table name prefix. - **opts** (ApplySchemaOpts) - Optional - Configuration for PRAGMA settings. ``` -------------------------------- ### Queue Port Methods Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/core.api.md The primary interface for queue operations, allowing for job lifecycle management across different storage backends. ```typescript interface Queue { enqueue(runId: string, opts?: EnqueueOpts): Promise; claim(opts: ClaimOpts): Promise; heartbeat(lease: Lease, opts: { leaseMs: number; now?: Date; }): Promise; ack(lease: Lease, opts?: { now?: Date; }): Promise; depth(now: Date, names?: readonly string[]): Promise; } ``` -------------------------------- ### Run a worker with MySQL backend Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/patterns/backends/mysql.md Configure the engine with the MySQL backend and execute a flow in worker.ts. ```typescript // worker.ts import { createMysqlBackend } from "@iterativeflow/mysql"; import { createEngine, defineFlow } from "@iterativeflow/core"; import { sql, pool } from "./db"; const backend = createMysqlBackend(sql); const greet = defineFlow({ name: "greet", version: 1, run: async (ctx, input: { name: string }) => `hi ${input.name}`, }); const engine = createEngine(backend, [greet]); const stop = engine.run(); await engine.submit(greet, { name: "world" }); // on shutdown: await stop(); await pool.end(); ``` -------------------------------- ### storeConformance Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/conformance.api.md Verifies the Store contract as executable invariants. Every backend must pass this suite to be considered complete. ```ts declare const storeConformance: (label: string, makeStore: () => Store | Promise) => void; ``` -------------------------------- ### applySchema Source: https://github.com/ahmedrowaihi/iterativeflow/blob/main/etc/mysql.api.md Applies the required database schema. ```APIDOC ## applySchema(sql: Sql, prefix?: string) ### Description Applies the schema DDL to the database. This operation is idempotent and should be run once before use. ### Parameters - **sql** (Sql) - Required - The Sql interface instance. - **prefix** (string) - Optional - Table name prefix. ```