Building your own UI
sanoma/app is one UI over a config; another (a Slack bot, an internal tool) can be built on the same pieces, which the package exports for that:
describeConfig(config)and its types (ConfigDescription,WorkflowEntry,OpEntry,VendorEntry,ResourceTypeEntry,DeclaredResource,ResourceProblem), andloadDataFiles(root, connectors)andreadResources(config), fromsanoma/workflows/describe: what to render, as plain JSON, with each workflow’s outline. Its shape isConfigDescriptionSchema, fromsanoma/workflows/description(zod and nothing of Node, so a browser may import it): each entry type is inferred from its schema, and the schema refuses a key it does not name. Beside what the sections above say, a resource type carries itscapabilities(host,databaseandwakeupfrom its spec,sourcefor a type a host type’ssourcefield names, such asgithub.repository), a vendor itscredentials(each variable its driver’senvdeclares: its name, description and whether it is optional, never a value or a status), and the policy itsfiles(each.cedarfile’s path and text, the root’s then each app’s). It is a separate entry so the worker never loads the parser the outline uses, and the lint refuses it in workflow files.resolveConfig(config)returns the checked config as aResolvedConfig, with the operations and drivers by id, the resource types by<vendor>.<type>(types), the workflows by name (the built-insdrift,applyandcallamong them), itsrootand each vendor’scredentials(CredentialStatus);isOp(x)tells an operation from a built-in in a workflow’suses.readSites(root, description, connectors, policies?), fromsanoma/workflows/describe, whichdescribeConfigreturns assites: what each site calls, read from its source with oxc and never run (its pages are browser code: what they call is the site’s outline), for a workflow’s Used by; itssite.tsis loaded. A site is a folder ofsites/with aroutes/, named as a URL segment; its files (.ts,.tsx, less tests, specs and stories outsideroutes/:routes/**,components/**and any other) are read for each<RunForm workflow="…" />and each use ofapi, both imported fromsanoma/site, called or passed on (queryFn: api.data.leads.list):api.<name>andapi.<name>.<method>are the workflow whoseapiNameOfis<name>,api.data.<collection>.<op>a collection,api.<vendor>.<resource>.<op>the operation of that id. Each is aSiteCall(kind,target,method, what it calls of a workflow or collection as written (start,latest,list),via,file,line,column, andpage, the page’s path from itscreateFileRouteorcreateLazyFileRouteid, in a page’s file); aSiteEntryholds a site’sname, itstitle(defineSite({ title })insite.ts, the file’s default export, which a zod schema checks: a key it does not name or a field of the wrong type (a number foricon) is a problem and that field is left out, the rest still read, so a badiconkeeps a site public, though a wrongpublic,loginorlocalesleaves out all three; aloginnaming no login half, orlocalesthat are no language tags or not on a public site without a login, is a problem too), itspages(eachSitePageapathfrom the id of a route file underroutes/, not in a file or folder whose name starts with-, one per path, a layout and its index being one; and on a path with one parameter, such as/sites/www/blog/$slug,content, the one kind its file reads an entry of by that parameter,content.<kind>.get(params.slug)(orslug, destructured) withcontentfromsanoma/site, for the app’s sitemap and its pages’ languages, whichsiteContentPages(root)gives the app’s build alone, path to kind; andcalls: truewhen it may make a call, from one of its files, a layout’s above it by route id, or a site file they import, directly or not (the whole rule is onSitePage.calls), which keeps it from being prerendered (buildAppBundleinsanoma/app/bundle)), itscalls, itswarnings(on a public site, each page with one parameter whose file reads content but not by that parameter, so the sitemap lists none of its pages: a warningsanoma checkprints and does not fail on) and itsproblems: each call to a workflow, collection or operation the config does not have (calls workflow "<name>", which does not exist), or to an operation a page may not call directly, and, given the policies (describeConfigpasses them unless they have problems), on a public site each start (api.<name>(…),.start(…), aRunForm) and direct call that no companypermitcould let a visitor make, itswhenandunlessaside (one naminganonymous; on a site with alogin,anonymousor the groupvisitors), whose message ends with the permit to add, and, whatever the policies, its call of a built-in workflow or read of a workflow’s runs but.result(.latest,.runs,.approvals,.ledger), which the app refuses a visitor; whichsanoma checkfails on. A name not written out (a variable, a template with holes, a computed member) is skipped, as is a call through a namespace import or a destructuredapi, though its page counts as calling.generateApi(description)andwriteApi(root, description), fromsanoma/workflows/describe: a site’s typedapi,.sanoma/api.ts(API_FILE), from aConfigDescription, types and JSDoc only and the same text for the same description. It holds a record type per collection andCompanyApi:<apiNameOf(workflow)>: WorkflowFn<input>per workflow, built-ins too;<vendor>: { <resource>: { <op>: OpFn<input> } }for the operationsdirectmarks;data: { <collection>: CollectionApi<record> }; each member documented from its title or description. Then it augmentssanoma/site’sRegister. Inputs are typed from their JSON Schema for the kinds a start form draws, constants, and unions of them (nullamong them); anything else, and every output, isunknown. A workflow withdescribeConfig’s api-name problem is left out (problems).writeApiwrites only when the text differs (wrote).SanomaClient: call an operation directly (call, see Direct calls), start runs, list them (runs({ limit, status, workflow })) or read a workflow’s last result (latest), read a run’s ledger and approvals, decide approvals, with the checks described above, and start a drift check or an apply and read its report (drift,driftReport,apply,applyReport, see Drift and Apply).client.chatskeeps the operator agent’s chats in the config’s database:open({ id, person, engine, title })(the id the browser gave the new chat),attach(id, draftId),upsert(id, messages)(the AI SDK’s UI messages, each by its id, a new one after the last),load(id),get(id)andlist(person)(the newest first,Chat).APPROVALS_EVENTanddecisionEventOf(approvalId): the DBOS events a run publishes its approvals and each decision on, for a UI that reads DBOS directly.ApprovalMessageis the zod schema of a decision as a run reads it.RunArgsis what a run receives: its input,startedByand, for a sandbox run, its scenario assandbox.mayDecide(approval, principal, run, people)andapproverLabel(approver): who may decide, and how to name them, the same way the run does.isEnded(status)andENDED_STATUSES: the run statuses that read no more decisions;RUN_STATUSES: every run status, in the order a run may pass through them.- Errors:
errorCode(err)for the code to branch on,errorMessage(err)for the text of anything thrown,invalidInput(what, issues)to build aninvalid_inputerror from zod issues (InputIssueis one issue, without symbols in its path), and the classesSanomaError,PolicyDeniedError,RejectedError,WithdrawnError,ApprovalPendingErrorandDriverError. Read codes witherrorCode, neverinstanceof. sanoma/workflows/sharedexportsmayDecide,approverLabel,errorMessage,isEnded,ENDED_STATUSES,RUN_STATUSES,DRIFT_WORKFLOW,CALL_WORKFLOW,isLoopback(whether a host is this machine:localhost,127.x.x.x,::1),problemAt(a problem’s place:file:line:column, elsefile#export, elsefile),problemLine(a problem as one line: its place, then: message, or the message),exportSpan(whereexport const <name>orexport defaultis in a file’s text, for marking a declaration),credentialReady(a variable is set, or optional and unset) and theRunStatusandCredentialStatustypes, the resource types’ types (Resource,ResourceSpec,ResourceFields,References,FieldReference,Declared,Declaring,DeclaredResource,ResourceProblem) and the drift report’s (DriftReport,DriftResult,DriftField,DriftStatus), with nothing else: no DBOS or Node imports, so a browser bundle can use them. The main entry exports them too.LedgerRecordandLedgerStorefor the audit record (LedgerBodyis a record without the fields every record carries, andLedgerGroupa record’sctx.alltag),postgresLedger(databaseUrl)(the default),jsonlLedger(dir)andmemoryLedger()to keep it, andRUNTIME_VERSION, this package’s version as the runtime reports it.
Outline
Section titled “Outline”outlineWorkflow(wf), from sanoma/workflows/describe, reads a workflow’s shape from the file that defined it, for drawing it before it runs, and the worker holds every run to it, so the drawing is what a run can do and nothing else. describeConfig returns it as each workflow’s outline:
import { outlineWorkflow } from "sanoma/workflows/describe";
outlineWorkflow(announce);// { nodes: [{ kind: "op", path: "0", id: "ghost.post.create", span: [913, 974] }, …, { kind: "approval", path: "2", title: "Review launch copy", span: […] }, …], file: "/…/workflows/announce.ts" }It parses the file with oxc-parser (TypeScript in a repo, .tsx included, JavaScript once built) and lists, in the order they run, the calls run makes on its first parameter, whatever it is named: operations (op, with a * for a computed segment such as ctx[vendor].comments.list, as the built-in drift imports each resource by its type, with the step’s name), approvals (with the title, when it is a string literal or a top-level const holding one), sleeps (with their name), and ctx.all: all with one branch per member of an array literal, or for anything else, such as ids.map(…), each with the callback’s calls as its body. Around them it shows loops and .map, .forEach and .reduce callbacks as repeat, if, switch, ?:, &&, || and ?? as branch (one case per arm that makes calls, plus one empty case for the way past them when there is one: an arm without calls, an if without else, a switch without default, the right side of && not run), and try / catch as try, with the handler’s calls as handler; a finally is not read. It does not read the functions run calls, whether defined outside run (a helper that takes ctx) or inside it, only callbacks passed to ctx.all, .map, .forEach and .reduce, and it cannot see how many times a loop runs or which arm is taken: the ledger says that, per run. Each loop, and each each, has a label read from its code: for each of subscribers for for (const s of subscribers) or subscribers.map(…), for each key of for for…in, repeat while queue.length for a while, do or for with a test, and repeat for one without (the code on one line, cut at 40 characters). A loop’s label is no step’s name, and need not be unique.
Each node’s path is its place in the outline: its index among its siblings, under its parent’s path and the index of the branch, case or body it is in ("2", "2.1.0"), the same for the same tree however the code is laid out. Each node’s span is where its code is in the file, as UTF-16 offsets (a string index, and what CodeMirror counts): the call, the ctx.all(…), the loop or .map(…) call, the whole if / else chain, switch, ?: or &&, or the try statement. describeConfig puts the file’s text beside the outline, as the workflow’s source, with \n line endings; a server can keep that from its clients, since it is a whole file.
defineWorkflow records the file it is called from as the workflow’s file, by itself; nothing passes it, and a definition made from code with no file (an eval, a bundle without one) is refused. The outline is read from that file, which must hold the workflow as an object literal with its name (a string literal, or a top-level const of the file holding one) and a run function taking ctx by name; otherwise it is { error }, saying why (the file could not be read or parsed, holds no workflow of that name, or run destructures ctx). It is { error } too, one line per problem at file:line:column, when run holds what the graph cannot draw: the control flow and uses of ctx that lintWorkflow refuses (see Keeping workflows replay-safe). Either way startWorker refuses the config, since nothing could say where the workflow’s calls are.
The worker reads each workflow’s outline when it starts and holds every run to it. Each ctx call captures where the workflow made it, from the stack, and the worker finds the call node whose code holds that position; a call from anywhere else fails the run with call_not_in_outline, naming the file, line and column and what to do (inline the helper): from a function the outline does not read, from another file, from a finally, or through an alias (const create = ctx.ghost.post.create). ctx.now(), ctx.runId and ctx.startedBy are exempt: a read of the clock, and values. The records a call writes name its node as node (its path): op.called, sleep.started, approval.requested (a policy hold’s approval names the held call’s node) and each group of a ctx.all, so a UI places a run’s steps in the code exactly, a loop’s every pass on its one node. Records written by a worker from before calls were placed have no node.
Status: early (0.x). The API may change between minor versions.
TODO: redact fields a schema marks .meta({ sensitive: true }) from the ledger, the approvals event and DBOS’s step records, so a secret passed by mistake is not kept.
Runs in a page
Section titled “Runs in a page”sanoma/workflows/page runs a company’s workflows inside a browser page, the base of a static demo: await pageRuntime({ workflows, collections?, connectors?, world?, actor?, decide? }). Every vendor is its connector’s fake and every collection is in memory, so no email, charge or post leaves the page. world is the world every run starts from (loadWorld’s, from scenarios/world.feature): its Given steps applied to the fakes as a sandbox run’s are; reset() makes the fakes again and seeds them, and drops the runs; stop() drops the runs alone (a demo’s unmount): a sleeping run’s sleep fails with run_ended, its timer cleared, and a dropped run’s next operation, approval, sleep or ctx.all never settles, so it goes no further and its .result stays unanswered; until a reset, a run started after stop() stops at its first call. There is no DBOS, no policy and no store: each approval a run asks for is decided at once, approved unless decide(approval) says "reject" (the run then fails with approval_rejected). ctx.sleep waits as a worker’s does, on a timer of the page’s: the run stays at its sleep.started, running (as the app reports a sleeping run), until the time it names, and .result with waitMs answers run_running meanwhile. transport(request) answers what the app’s callApi does for a site’s api, so createApi(transport) gives a page the same api: an operation a person may call directly, on its fake; <workflow> or <workflow>.start ({ runId }); .result (the run’s output once it ends, or its failure); .latest, .runs, .approvals, and .ledger, the run’s records (LedgerRecord, each with the step’s name, an operation’s input and output, a sleep’s until) for a run card. Its failures are the runtime’s errors (errorCode), not the app’s responses. A page’s build gives a connector’s module its package’s vendorInfo (vendorInfos() from sanoma/app/bundle, as the Worker’s build does) and names each company file from the root (companyFiles(root, { fromRoot: true })), which the page reads a collection’s app from.
These pages describe sanoma 0.11.24.