import { type TwinResource } from './serve.js'; import { GitObjectStore } from './git/objects.js'; import { GitRefs } from './git/refs.js'; import { type SocketDecl, type SocketSession } from './sockets.js'; import type { LiveAccess, LiveDecl } from './live/types.js'; import { type MachinePool } from './machines.js'; import { type ApplicationAnswer, type ApplicationStandIn, type EventRender, type EventScheme, type EventsDecl, type EventValues } from './events.js'; import type { RateBudgetDeclaration } from './rateBudget.js'; import { type HandlerCrypto, type KeyFormat } from './signing.js'; import { type ManagedDatabase } from './managed-database.js'; import { type RedisDialect, type RunItem } from './redis/engine.js'; import { type Mail, type MailReply } from './smtp.js'; export { ownField, parseBracketForm } from './form.js'; import { type MultipartPart } from './multipart.js'; import type { CorsDecl } from './cors.js'; import { type TwinAction } from './actions.js'; import type { DerivedCall, DerivedCoreOutcome, DerivedHandler, DerivedOperation, DerivedSurface } from './derived.js'; import { type PackDescriptor } from './packRegistry.js'; import type { ScenarioDecision, ScenarioHandler } from './scenario.js'; import { type ScenarioLedger } from './scenario-consume.js'; import { type PlacedFault } from './placements.js'; /** How a stored field gets its value when the server assigns it. `now` is the world clock in the * manifest's time format; `id` the subject's id; a `value` is stored as given. */ /** A field the server assigns: the World clock's now, the subject's id, a fixed value, or a template over the stored * fields (and `{id}`), base64-encoded when `encode` says (GitHub's `node_id`: `05:Label{id}` in base64). */ export type FieldRule = { now: true; } | { id: true; } | { value: unknown; } | { template: string; encode?: 'base64'; }; /** A move of one state field, as data. `operation` is the operationId that causes it (an update * that requests `to` when absent); `from` the values it leaves; `effects` the other fields it writes; * `refusal` what the vendor answers when `from` does not hold. */ /** Who moves a state: a caller of the API (the default), the person on a vendor's hosted page or * another outside party (`external`), the vendor on its own (`vendor`), or time (`time`). A move * that is not the API's never answers an API call's legality. */ export type Actor = 'api' | 'external' | 'vendor' | 'time'; export type Transition = { operation?: string; actor?: Actor; from: string[] | '*'; /** the value it moves to; absent, the value stays (a guard that moves nothing), and absent with a `refusal`, the * operation is refused in the `from` states (a move another transition allows from there is taken first) */ to?: string; effects?: Record; /** placeholders `{from}`, `{to}`, `{field}`, `{id}` */ refusal?: { status: number; code?: string | number; message: string; }; /** a refusal of its own for a particular current value (an invoice already `paid`) */ refusals?: Record; /** where the rule comes from: a docs URL, the SDK's types, or a recording */ source: string; }; /** A state field's machine. Values compare as strings, so a boolean field reads `'true'`/`'false'`, and * a field that is absent reads as `initial`. `derive` names states a stored value only implies (a * timestamp that is 0 until something happens), tried in order. `vendorInitial` is where the vendor * starts a subject when the twin starts it elsewhere. */ export type StateField = { initial: string | boolean; transitions: Transition[]; /** Plain updates may repeat the current representation without another state move. */ unchanged?: 'allow'; derive?: Array<{ state: string; when: { equals?: unknown; gt?: number; truthy?: boolean; absent?: boolean; }; }>; vendorInitial?: string; }; /** What a move to `to` stores in the field: a boolean field's value is a boolean, and a derived field's * value is written by the move's effects (a state name is not a timestamp), so it stores nothing itself. */ export declare function storedState(decl: StateField, to: string | undefined): unknown; /** The state a stored value is in, by the field's machine. */ export declare function stateOf(decl: StateField, value: unknown): string; export type ResourceDecl = { /** the tree's subject type, when it differs from the resource name */ storedAs?: string; idPrefix: string; /** a setting held once per parent at a path of its own (`/v1/projects/{ref}/config/auth`, GET and PATCH, which the * surface names by the schema its GET answers): keyed by the path's parameter, it answers `defaults` under what was * written until first written, and an update merges into it, making it on first write */ setting?: { defaults: Record; }; /** this resource's id template, when it is not the manifest's (`ids.template`): `{uuid}`, `{ksuid}` (Clerk's), `{letters:20}` (twenty * lowercase letters, a Supabase project ref), `{digits:16}` (fixed-width decimal), `{snowflake:}` (Discord's ids), or a `{prefix}`/`{n}` * template */ ids?: string; /** fields the server assigns on create */ assigned?: Record; state?: Record; /** state candidates the manifest rules are not state */ notState?: string[]; /** id-holding fields a caller may ask to receive embedded, and the resource each holds */ embeds?: Record; /** `embeds` fields the vendor answers embedded on every answer, asked or not (its schema gives the object with no id * alternative: Stripe's issuing card's `cardholder`): still stored as the id, hydrated from the current object */ alwaysEmbedded?: string[]; /** the vendor's own fields whose names begin with `_` (GitHub's `_links`, a HAL object's), which the vendor answers: * answered like any field, where every other `_` field is the pack's bookkeeping and never answered */ vendorUnderscored?: string[]; /** Stored fields omitted from vendor views, without renaming them in retained state. Raw rows and * ctx.own retain them for parent scope and semantics; get, rows, render and core answers omit them. */ viewOmit?: readonly string[]; /** fields the vendor answers as a list of the current children of another resource (Stripe's subscription `items`: * its subscription_items), built on every answer from the child rows whose `by` field holds this id, in the order * they were made, each through the child's own view and its embedding; never a stored copy. `list` is the list's own * fields around `data`, where `{id}` is this resource's id and `"{count}"` the children's number */ collections?: Record; }>; /** this resource's deletion answer, when it is not the manifest's (`vector_store.deleted`) */ deleted?: unknown; /** a child addressed under its parent: the path parameter naming the parent, the stored field that * holds it, and the parent resource, whose not-found answers a missing parent */ /** `param` is the path parameter naming the parent, or `params` several with `value` the template * that joins them into what `field` stores (`{owner}/{repo}`). `where` finds the parent by its stored * fields when its stored id is not what the path names (a repository stored as `repo:7` with `owner` * and `name`, addressed as `{owner}/{repo}`): each stored field against a template over the path. */ parent?: { param?: string; params?: string[]; value?: string; field: string; resource: string; allowDeleted?: boolean; where?: Record; /** Global subject paths omit the collection's parent labels; tenancy still applies. */ whenNamed?: true; /** private fields a child observed under its parent keeps from the parent's parameters (`_jurisdiction: * '{jurisdiction}'`), where the child's own read names none and a later read under it needs one ("Refresh") */ keep?: Record; }; /** a number the resource counts per parent (a repository's issue numbers, a thread's messages): * the stored field, set on create to one past the highest among its siblings */ number?: { field: string; }; /** the field the vendor's answer names a subject's id by, when it is not `id` (Daily's webhook `uuid`, Twilio's `sid`, * Asana's `gid`): the subject's id is answered under it, and no `id` */ idAs?: string; /** an update replaces the fields it names (`replace`), merges a nested object one level into them with `''` removing * a key (`merge`, the default: Stripe's metadata), or merges nested objects at every level with `null` removing a key * (`deep`: Clerk's metadata, "a deep merge … remove metadata keys at any level by setting their value to null") */ update?: 'merge' | 'replace' | 'deep'; /** the stored subject id when it is not the path's last parameter: a template over the path * parameters (`{vector_store_id}::{file_id}`) */ key?: string; /** a resource every tenant shares (a catalogue the vendor keeps for all, its countries or currencies): the manifest's * `tenant` does not scope it */ shared?: boolean; /** only subjects whose stored fields match are readable (a resource stored for every call but * answered only when asked to be kept) */ readableWhen?: Record; /** fields the vendor answers pending until its own work fills them, `for` (a duration of World time) after the subject * was made or after a write that set any of `on` (default: the field itself): a read before then answers `value`, one * after answers what is stored (a merge state computed in the background, a deployment's readiness) */ pending?: Record; /** this resource's not-found answer when it is not the manifest's: a message (`{id}`), or an * error code (an RPC vendor's `channel_not_found`) */ notFound?: string | { code: string; message?: string; }; /** query parameters of the list operation that filter on the same-named field */ filters?: string[]; order?: { field: string; direction: 'asc' | 'desc'; }; /** the list's ordering parameter (`order_by=-created_at`): `[+-]` over `fields`, `default` when absent; any * other field is refused with `invalid` (`{fields}` in its message names them), never ignored */ orderBy?: { param: string; fields: string[]; default: string; invalid: ErrorSpec; }; /** fields no two live subjects share (a permission's `key`; a membership's `organization_id` and `user_id` together): * a create or update that would make a second one is refused with `refusal`, by the core and by `ctx.conflict` */ unique?: Array<{ fields: string[]; refusal: ErrorSpec; }>; /** the subjects a delete takes with it (an organization's memberships and invitations): each resource whose `field` * holds the deleted subject's id, deleted first, each through the write path as its own delete (its events sent). * The field may be a dot path; exact field names take precedence. */ cascade?: Array<{ resource: string; field: string; }>; /** fields that name a subject as its id does (an organization by its id or its slug): a path's id and `ctx.find` * match either */ alternateKeys?: string[]; /** fields that pair a subject a deploy settled with no vendor id with the vendor's copy a refresh observes (Slack's * `channel_join` message, made by `conversations.join` and answered by no id: its `subtype` and `user`), where the * `alternateKeys` do not; a subject missing one is never paired by them ("Refresh", adoption) */ adoptBy?: string[]; /** the list's search parameter (`query`): a row matches on an `exact` field's whole value or a `partial` field's * substring, case-insensitively */ search?: { param: string; exact?: string[]; partial?: string[]; }; /** fields that count this subject's children (an App's `installations_count`): the live subjects of `of` whose `by` * holds this one's id (or vendor `parentKey`), only those with `present` set or `absent` unset when named and without * any matching `unless` field, plus `plus` (a customer's * `next_invoice_sequence` is one past its numbered invoices). `by` may be a dot path; exact field names take * precedence. The kernel keeps each whenever a child is written, the parent it left too when the write moves it; `of` * may name a bookkeeping type no resource declares, written with `ctx.record`. A count is kept by the lane that * declares it: a child another lane writes is not counted there. */ counts?: Record; plus?: number; }>; /** how the vendor's state of this type is read back into a root (the real-system adapters, "Refresh"): the list that * enumerates it (once per parent, under `parent`; `complete: false` when it is not the whole type; `items`, the answer's * path to them, when the spec does not name the list it answers), the one read of a singleton, or `none` with why the * vendor offers no read-back. Every stored resource the vendor holds declares one. `{ get, known: true }`: the vendor * lists no whole type, so the World's own subjects of it are each read again by `get` (a 404 is one gone), and what * those reads observe anchors its children's lists; completeness is those subjects alone. */ /** `next`: where an answer names the next page's cursor (AWS's `NextToken`), sent back as `cursor` (the same name * unless said) in the query, or in the body of a list asked by POST (an RPC list: AWS JSON's `x-amz-target`); a * map of parameter to answer path where a page names several (S3's `key-marker` and `upload-id-marker`); `more`, the * answer's flag that another page follows (S3's `IsTruncated`). `headers`: fixed headers of the list, `{name}` filled * from the parent's parameters; `variants`: header sets each listed in turn, one type whole across them (R2's * jurisdictions). A blob read by an `operation` (a GET of the unit's surface, filled from the subject's fields and * its parent's parameters) keeps the bytes in the World's blobs, their key in `field`, and in `headersField` the * answer's headers `keepHeaders` names (a name ending `*` a prefix: `x-amz-meta-*`), both fields private. */ refresh?: ({ list: string; unpaginated?: true; keyed?: true; detail?: string; detailMerge?: string; detailWith?: Record; detailParams?: Record; complete?: false; items?: string; shape?: RefreshShape; next?: string | Record; nextLink?: { header: string; rel: string; query: string; when?: Record; }; cursor?: string; more?: string; } | { get: string; known?: true; gone?: { status: number; says: string; }; }) & { params?: Record; headers?: Record; variants?: ReadonlyArray<{ headers: Record; }>; blobs?: ReadonlyArray<{ path: string; key: string; resource?: string; fields?: Record; } | { operation: string; field: string; headers?: Record; headersField?: string; keepHeaders?: string[]; }>; query?: Record; idAs?: string; graphql?: { query: string; variables?: Record; items: string; pageInfo?: string; cursor?: string; }; } | { none: string; }; /** the reads a root scoped to one of the vendor's things makes instead of `refresh` */ scopedRefresh?: ReadonlyArray; /** the other resources one create of this one makes, and where its answer names each's id (a JSON path) */ companions?: Record; /** the field telling a newer copy of a subject from an older (an `updated_at`): an ingested event older than the * root's copy folds nothing */ version?: string; }; /** How a vendor's signed webhooks are folded into a root (the real-system adapters, "Ingest"). */ export type IngestDecl = { scheme: EventScheme | ReadonlyArray; /** where the event names its type: a header, a body path, and a sub-action path joined to it with `.` */ type: { header?: string; body?: string; action?: string; }; /** the JSON path of the event's object */ object: string; /** event type → the resource it carries, where `events.types` read backwards and `.created|updated|deleted` * do not say it */ types?: Record; }>; /** an event answered instead of folded (Slack's url_verification): the body fields it matches, and the answer, a * `$body.` read from the event or a literal */ handshake?: { when: Record; answer: string; }; }; /** Which lane a request is the vendor's gateway's to send ("Other wires: lanes"), each condition it names holding: a * path under `path` (Supabase's `/rest/v1`), a path matching `pathPattern` (a regular expression, where a front routes * by one: Sentry's sends a project's numbered `/api//` to Relay), a host matching `host` (a regular expression: * `^secretsmanager\.`), a header starting with `header.prefix` (AWS's `x-amz-target: secretsmanager.`), and a host not in `exceptHosts`. */ export type LaneRoute = { lane: string; path?: string; host?: string; exceptHosts?: ReadonlyArray; pathPattern?: string; /** a header starting with `prefix`, or, with `absent`, a request whose header does not (Clerk's Frontend API is asked * without a Backend API secret key) */ header?: { name: string; prefix: string; absent?: true; }; /** where two of the vendor's APIs share one address: the route passes a path only the root's API serves (the lane's * surface does not), which is the root's */ unlessOnlyRoot?: true; }; /** A vendor's lanes: its routes, first match first, the lane that takes what no route names (`default`), and the * gateway's CORS. A `/_twin/` door goes to the lane whose manifest declares it. */ export type LanesDecl = { cors?: CorsDecl; routes: ReadonlyArray; default?: string; }; /** The manifest of a vendor whose every API is a lane (Cloudflare's API v4 and R2, AWS's services): no API of its own, * only what the vendor's front says — its discovery facts, its lanes and its descriptor. */ export type VendorManifest = { vendor: string; discovery?: DerivedManifest['discovery']; lanes: LanesDecl; descriptor: Omit; ingest?: IngestDecl; rateBudget?: RateBudgetDeclaration; /** the vendor has no vendor-backed half (architecture, "The descriptor"): packOf copies it, and derives no state system */ vendorBacked?: DerivedManifest['vendorBacked']; /** what of the vendor's records identifies a person, for every lane's records (architecture, "A real account's data"): * a pack with units declares it here, on the manifest its entry exports */ privacy?: PrivacyDecl; }; /** `code` as the vendor writes it: a string, or a number (Discord's JSON error codes are integers) */ export type ErrorSpec = { status: number; message: string; code?: string | number; param?: string; kind?: string; }; /** Where the vendor reads a request's idempotency key: a request header; a body field at a dotted path (`when`: only * while another body field, at its dotted path, holds `equals`); or the request's content itself (its path, query and * body, hashed: a repeat of the same content is the same request). A request with no key is not deduplicated. */ export type IdempotencyKeySource = { header: string; } | { body: string; when?: { body: string; equals: unknown; }; } | { content: true; }; /** The vendor's idempotency layer, as its pack declares it. A failure the World's scenario places lands inside it, so a * repeat with the same key replays the failure as the vendor keeps it. */ export type IdempotencyDecl = { /** the key's request header: the same as `key: { header }` */ header?: string; /** where the key comes from, when it is not `header` */ key?: IdempotencyKeySource; /** the bookkeeping type a key's record is kept under (starts with `_`) */ storedAs: string; /** whose keys share one space: the account's (default) or each credential's (the one the request presents) */ scope?: 'account' | 'credential'; /** how long a key is kept, a duration of World time (`24h`, `5m`); a request with a key kept longer is a new request. * Absent: kept for ever */ keptFor?: string; /** what a repeat with a kept key answers: the first answer as it was (`answer`, default); the subject the first * request made, as it stands now (`subject`: the first answer's `id`, or the value at `subjectId`'s dotted path, a * subject of the operation's resource, else the first answer as it was); or a declared error */ replay?: 'answer' | 'subject' | { error: ErrorSpec; }; subjectId?: string; /** the answer to a kept key sent with other parameters; absent, the key replays whatever the parameters */ conflict?: ErrorSpec; /** the answer to a request whose key is held by a request still in progress in this twin; absent, each goes on */ inProgress?: ErrorSpec; /** `methods` defaults to POST; `onlySuccess` (keep only 2xx answers) to false */ methods?: string[]; onlySuccess?: boolean; }; /** How a form value outside its spec's list is refused (DerivedOperation.enums): the error, its message filled with * `{param}` (the bracket name) and `{values}` (the values it takes); `documented`, values the vendor documents outside * its spec, by operation and path; `version`, the header naming the API version a request is made at and the version * the spec is, so a request pinned to another version, whose lists the pack does not hold, is not checked. */ export type EnumRefusal = ErrorSpec & { documented?: Record>; version?: { header: string; served: string; }; }; /** A vendor screen a World serves (docs/contributing/architecture.md, "Screens"). A `flow` is a hosted * page an application sends its user through, held to its documented round trip; a `workspace` is a * screen people work in. `demand` says who reaches it; `controls` names what a person acts on, the * vendor's way, each a (screen, control) cell. */ export type ScreenDecl = { id: string; /** a hosted flow a person is sent through, a workspace they work in, or a content host serving what the vendor stores * (its CDN: an uploaded image, a video, a default avatar) */ kind: 'flow' | 'workspace' | 'content'; host: string; /** every other host the screen answers on (a sandbox's dashboard and production's, one page) */ hosts?: string[]; path: string; demand: string; status: 'done' | 'todo'; controls?: string[]; /** wherever this screen would answer (its host, a World's place, its path alone), a request the pack's API names for * its method is the operation's, not this screen's: a site whose pages draw while its forms and links act on * operations the spec writes at the same paths (Hacker News's /login page posts to POST /login; its front page at `/` * would otherwise take GET /vote) (architecture, "Screens") */ yieldsToApi?: true; /** a content screen that takes a form at a World's place (`/@/…`), beside GET and HEAD: the methods it * takes, with its demand (an upload bucket a page posts a lease's form to: Reddit's S3 hosts) (architecture, "A page * at a World's place") */ takes?: ReadonlyArray<'POST'>; /** a workspace page that shows one record: the stored type and the path parameter its id fills (a pull request's * page, `{number}`); `?show=:` asked of the pack's workspaces opens it (architecture, "Workspace") */ shows?: { type: string; param: string; }; /** the stored types a workspace page lists, where `?show=` lands for a record no page shows by itself */ lists?: ReadonlyArray; /** the vendor's documentation of the round trip or the screen */ source: string; }; /** A protocol hook's arguments: the root's executor (it applies the sealed credential; `issued` carries one the vendor * issued instead), the group and its first entry's recorded input, the perform's context, the derived perform of an * input (`send`: the recorded request, or one the hook changed), the stored id the World's id of a type resolves to, * the surface's base path, and the World's blobs of this twin. */ export type PerformHookArgs = { execute: import('./remote-execute.js').RemoteExecute; group: import('./actions.js').TwinAction[]; /** Recorded local effects before root reference translation, for local blob ownership. */ localGroup: import('./actions.js').TwinAction[]; input: Record; ctx: import('./head.js').PerformContext; send: (input: Record) => Promise; resolve: (type: string, localId: string) => string; basePath: string; blob: (key: string) => Promise; }; export type PerformHook = (args: PerformHookArgs) => Promise; export type GitRepositoryDecl = { resource: string; name: string; remote: string; }; export type GitPushDecl = { resource: string; repository: string; remote: string; ref: string; before: string; after: string; }; /** A template over a row's fields (`{field}`, a dotted path read through objects), every name filled or refused. */ export declare function fillTemplate(template: string, row: Record): string; /** A pack's git repository `name` in a World (the store and refs `ctx.git(name)` answers), under the twin's state and, * for a namespaced account, that account's. */ export declare function gitRepositoryOf(m: DerivedManifest, name: string, root?: string): { store: GitObjectStore; refs: GitRefs; }; /** The name a repository row's code is kept under: the manifest's `git.repository.name` (a template over `{id}` alone) * filled with the row's first World id, the one an adoption rebound to the vendor's (walked back through the aliases), * so the screen, a refresh, a deploy and a waiting push's protection name one repository before and after adoption. */ export declare function gitNameOf(m: DerivedManifest, id: string, root?: string): string; /** A kind of identifying value (ADR 0036, "A real account's data"): a person's `name`, `email`, `phone`, `ip`, an account * `id` (a user id, a distinct id), a `place`; replaced by one keyed pseudonym of the same form wherever it occurs. A * person's act `time`, a user `agent` and a `url`'s query are quasi-identifiers, changed only where declared: a time * moves by the key's one offset, an agent keeps its products' major versions, a URL's query values take * pseudonyms. */ export type IdentifierKind = 'name' | 'email' | 'phone' | 'ip' | 'id' | 'place' | 'time' | 'agent' | 'url' /** an email at a mailbox provider whose subaddress rule is the separator (Gmail's `+`): `local+tag@d` is the mailbox * `local@d` labelled, pseudonymized as P(`local@d`)'s local part with its tag (ADR 0036, "A real account's data") */ | 'email+' | 'email-'; export type PrivacyDecl = { identifiers: Record>; }; export type DerivedManifest = { /** Vendor data-plane hosts mapped to an already-running customer guest. */ machineRoutes?: ReadonlyArray<{ host: string; resource: string; where: Record; name: string; port: number | string; }>; /** The pack's descriptor, as data (docs/contributing/architecture.md, "The descriptor"), every field but `vendor`, which * is the manifest's: the pack registers `packOf(manifest)`, so its index is a fixed file. A lane has none. */ descriptor?: Omit; vendor: string; /** the kernel service the pack writes */ service: string; /** `json: 'always'` reads a body as JSON whatever its content type (GitHub does) */ /** `strict`: a vendor that refuses a body field its operation does not declare, a value of another type, or a number * outside the spec's bounds (a NestJS validation pipe: Supabase's "property x should not exist"), with its messages; * `{name}`, `{type}` (`a string`, `an integer`), `{min}` and `{max}` are filled. `ctx.fields` checks a body so. */ body: { form?: { coerce: boolean; enumRefusal?: EnumRefusal; }; json?: 'always'; validation?: { operations?: ReadonlyArray; status: number; missing: unknown; type: unknown; range: unknown; }; strict?: { status: number; code?: string; unknown: string; type: string; range: string; arrays?: Record; }; }; /** `acceptProvided`: a create that names its own `id` keeps it (a vendor that seeds by id). The template counts * (`{prefix}_{n}`), or is `{uuid}` for a vendor whose ids are UUIDs: the next is derived from the resource and its * count, so a World mints the same ids every run */ ids: { template: string; acceptProvided?: boolean; }; /** operations the derived core must not claim though their resource is declared: a gap until someone models them */ unmodeled?: string[]; /** documented variants of a served operation that no demand asks for, by operation: each a parameter present * (`pause_collection`), present on any item of a list (`items[].price_data`), or with a value * (`payment_method_data.type=sepa_debit`, `payment_method_types[]=sepa_debit`), or holding one entry of a comma-separated * value (`tweet.fields~=geo`; a parameter whose name holds a dot is read by that name). A request asking one is answered the * manifest's gap before its handler runs, as an operation no handler serves is (architecture, "Creating a pack", * step 7), so no pack line answers it */ variants?: Record; /** operations that only read though nothing in the spec says so (a POST that returns data): * a read-only twin answers them */ reads?: string[]; /** operations of the vendor's API that set an account up rather than use it: an operator registering an OAuth client * on the vendor's own admin routes, as a person makes settings on the vendor's site. Each is recorded as a door's * write is (the World's own), so a deploy never offers it to the vendor and the vendor-backed acceptance holds it as * what the account already has; `why` says who performs it and where */ accountSetup?: Array<{ operation: string; why: string; }>; /** how the vendor writes an instant: Unix seconds, Unix milliseconds (Clerk's `created_at`), or ISO 8601 */ time: 'unix' | 'unix-ms' | 'iso'; /** the vendor's CORS, as its gateway answers a browser (cors.ts): the pack's fetch is served behind `withCors` */ cors?: CorsDecl; /** the HTTP status a vendor answers every error below `below` with, when its body names the error's own status * (storage-api: 400 for every error but a 500, the body's `statusCode` the error's: `{ status: 400, below: 500 }`) */ errorsAnsweredAs?: { status: number; below: number; }; /** the texts the vendor reads as a boolean in a parameter, compared without case (Supabase: `true`, `1`, `yes`, `on`, * `y`, `enabled` and their opposites); absent, `true` and `false`. `ctx.flag` reads with them. */ booleans?: { truthy: string[]; falsy: string[]; }; /** the vendor's error body, with `{message}`, `{code}`, `{param}`, `{kind}` placeholders; a * placeholder with no value is left out when `errorOmitsAbsent` */ error: unknown; errorOmitsAbsent?: boolean; /** the `{kind}` an error takes when it names none */ defaultKind?: string; /** what a write to a read-only twin answers */ readOnly: ErrorSpec; /** what a body labelled JSON that does not parse answers; absent, a 400 in the vendor's error body */ malformedBody?: ErrorSpec; /** the vendor's front merges repeated slashes in a path before it routes (nginx's default `merge_slashes`): a request * to `//r/x//about` is `/r/x/about`, merged on arrival before a door, a screen or an operation is matched */ mergeSlashes?: boolean; /** a request header that selects the vendor's API version, and the answer to a malformed one * (`{value}` in its message is the header's value) */ version?: { header: string; pattern: string; error: ErrorSpec; }; /** request headers that carry meaning to the vendor (a tenant header such as `Stripe-Account`): recorded with a write * so its perform sends them again (the real-system adapters, "What a pack declares"); `version.header` is too. A name * ending `*` is a prefix: every header it begins (S3's `x-amz-meta-*`, an object's own metadata). */ headers?: string[]; /** the vendor's signed webhooks, folded into a root */ ingest?: IngestDecl; /** the vendor's documented limits, charged by the executor on every live call (D8), and the one its server keeps * (`served`), which a World's scenario switches on */ rateBudget?: RateBudgetDeclaration; /** the operations the vendor documents as eventually consistent (a search index that finds a new object after a * short delay; a configuration in force a while after it is set): where a World's scenario `lag` answers from the * World as it stood its `by` ago, and nowhere else. `reads`, by operation: the resources it reads as of then (absent: * every resource it reads, the kernel's own bookkeeping apart) */ eventuallyConsistent?: { operations: string[]; reads?: Record; }; /** cursors the vendor keeps for a time, by operation: the request's `param` (a path parameter, else the query's, else * the body's) names a subject of `resource` by `field` (default its id); a subject made more than `keptFor` (a * duration of World time) before the request is past the vendor's retention, and the request is answered `error` */ cursors?: Record; /** where the vendor's repositories' code lives, as templates over a row's fields (`{field}`) (architecture, "The * real-system adapters"; ADR 0031): the resource whose rows are the vendor's repositories, the name each is kept under * (over `{id}` alone: the row's first World id, `gitNameOf`) and its remote (the vendor's absolute git URL), which a * refresh fetches; and the resource a push to a World repository records, one row per ref, with the World id of the * repository row it pushed to, which a deploy pushes */ git?: { repository: GitRepositoryDecl; push: GitPushDecl; }; /** a pack whose wire has no derived perform (a socket, a line protocol, a managed database): binding a root is refused * with this reason */ vendorBacked?: { none: string; }; /** the resource the vendor's paths name the account by (Cloudflare's `accounts/{account_id}`): with a root, the * World's account is the one account the root's credential reaches, which refresh observes ("The account a root * is", architecture) */ account?: string; /** a vendor protocol one recorded request cannot express, by the operation that ends it: a session whose answer * issues the credential its next calls carry (Cloudflare's assets upload), performed by the hook in place of the * derived request, which it composes (`send`) ("Protocols a request cannot express", architecture) */ performs?: Record; /** what of the vendor's records identifies a person (ADR 0036, "A real account's data"; architecture, "A real account's * data"): by resource type, each field (a dot path into the record's fields; `*` any one key, a list stepped into) * whose value is an identifier or a quasi-identifier, with its kind, which a root's pseudonymizing refresh replaces */ privacy?: PrivacyDecl; /** `withParam`: the error names the path parameter that held the unknown id */ notFound: { status: number; message: string; code?: string | number; kind?: string; withParam?: boolean; }; /** the list envelope (placeholders `{data}`, `{has_more}`, `{url}`, `{first_id}`, `{last_id}`), * its page size, its cursors, and where an unknown cursor starts: the first page or past the end. * Absent when the unit serves no stored list; the core does not own lists without this declaration. */ list?: { style: 'envelope'; envelope: unknown; limit: { param: string; default: number; max: number; }; after?: string; before?: string; unknownCursor?: 'start' | 'end'; /** an opaque cursor over positions (`{next_cursor}` in the envelope; empty on the last page), * in place of id cursors: `base64-offset` is base64 of `{"o":}` */ cursor?: { param: string; encoding: 'base64-offset'; } | { param: string; encoding: 'offset-template'; template: string; link: { previous: string; next: string; results: string; cursor: string; }; }; /** numbered pages (1-based, the size in `limit.param`), with the vendor's `Link` header * naming the first, previous, next and last pages (`link`); the envelope may name `{total_count}` and `{max_page}` */ page?: { param: string; link: boolean; }; /** offset paging: `param` names how many items to skip; the page sits under the operation's envelope key beside the * envelope, whose `{total_count}` is the count before paging (Tremendous's `{ orders: [...], total_count }`) */ offset?: { param: string; }; /** page sizes by operationId, where a vendor's lists differ from `limit` (Tremendous: orders 10/500, invoices 10/10) */ limits?: Record; /** envelopes by operationId, where a vendor's lists differ from `envelope` (Tremendous gives `total_count` on orders, * rewards and invoices, and none on campaigns, funding sources or webhooks) */ envelopes?: Record; }; /** an RPC vendor's success envelope, merged into every answer, with the resource under the * operation's envelope key (`{ ok: true, channel: {...} }`) */ success?: Record; /** who is calling, from the request's credential (and the tree, where the vendor keeps tokens) */ identity?: (authorization: string | null, root?: string) => string; deleted: unknown; expandParam?: string; /** server-sent events: `data` lines, optionally `event:` lines named by each event, and the * sentinel a finished stream ends with */ sse?: { named: boolean; done?: string; }; /** an operation whose stream is framed otherwise (named events, no sentinel) */ streamFor?: Record; /** the vendor's idempotency layer (IdempotencyDecl): a write repeated with the same key answers as the vendor * replays it; the same key with other parameters answers `conflict` */ idempotency?: IdempotencyDecl; /** how the vendor reads its credential, and what it answers without one or with a key the twin * reserves as invalid, or one of a shape the vendor never issues (`keyFormat`, a pattern every key it issues * matches: Resend's begin `re_`); a request that presents no such header at all is a trusted in-process call. * `held`: the key must be one the account holds, kept by its SHA-256 in a stored type's field (a token a Tokens page * made: `{ storedAs: '_access_token', hashField: 'sha256' }`), the live key of an `issued` purpose (`ctx.issueKey`), or * one of the World's `standing` keys (the one its seeds and init hand the app); any other is `invalid`. */ /** how the vendor reads its credential: the `header`, after its `scheme` (`''`: the header's whole value, an * `x-api-key`), or any of `also` (ElevenLabs' `xi-api-key` beside `Authorization`, Google's `?key=`); `paths` (a * regular expression) the paths it gates, every other passing ungated; a key the World issued is `held` by its hash */ auth?: { header: string; scheme: string; also?: Array<{ header?: string; scheme?: string; query?: string; }>; paths?: string; missing: ErrorSpec; invalidKeys: string[]; keyFormat?: string; invalid: ErrorSpec; gateWhenAbsent: boolean; held?: ({ storedAs: string; hashField: string; } | { storedAs?: never; hashField?: never; }) & { issued?: string[]; standing?: string[]; /** a field set true on a key no longer held (OpenRouter's `disabled`) */ unless?: string; }; /** operations that check a credential of their own, not the account's (Cloudflare's asset upload reads its upload * session's JWT from the same header): the gate leaves them to their handler */ exempt?: string[]; /** ordered API-skin error wires, selected before scenario matching and ordinary routing */ wires?: Array<{ paths: string; error: DerivedManifest['error']; missing?: ErrorSpec; invalid?: ErrorSpec; }>; /** the vendor checks the key before it routes: a path it does not have is refused a missing or invalid key first */ beforeRouting?: boolean; }; /** headers every answer carries (a request id); a value's `{hex:N}` is filled per answer, from the World's count of * answers (so a second World answers the same ids in the same order), unless the handler set the header itself */ answerHeaders?: Record; /** an origin the pack writes into URLs it mints, rewritten in every JSON answer to where this * twin is reached for the request (twinPublicBase) */ origin?: { placeholder: string; }; /** Disclosed local connection fields, separate from vendor response schemas. */ worldFields?: Record>; resources: Record; /** Read-only cross-pack credential subjects of the same vendor (architecture A3); no root is exposed to handlers. */ ownerReads?: ReadonlyArray<{ owner: string; resource: string; }>; /** the vendor's screens this pack serves or owes (demand decides which exist) */ screens?: ScreenDecl[]; /** The discovery door's facts (`GET /twin`): what the twin is of, what it stores, and how it is authenticated. */ discovery?: { twinOf: string; stores: string; identity?: string; notes?: string; /** a model vendor's: what its scenario scripts (the `on` keys and the `respond` shape), and a handler as an example */ behavior?: string; exampleHandler?: ScenarioHandler; }; /** The World's doors (architecture, "Doors, screens and the gap"): each a method and a path under `/_twin/` (with * `{param}` segments), answered by the export of `semantics/doors.ts` its id names, over the contract's context. */ doors?: Array<{ id: string; method: string; path: string; note?: string; redactBody?: string[]; }>; /** REST refresh binds observed tenant metadata through the root account identity endpoint. */ refreshIdentity?: { operation: string; field: string; }; /** The vendor's GraphQL API beside its REST one (`semantics/graphql.ts` over `generated/graphql-sdl.gen.json`): the * paths it is POSTed to, and the answer to a query selecting a field nothing models (`{field}`, `{type}`). */ graphql?: { paths: ReadonlyArray; unmodeled: { message: string; type?: string; status?: number; }; }; /** The vendor's answer for a path nothing serves and an operation nothing models, `{method}` and `{path}` filled * (OpenAI's `Unknown request URL: {method} {path}`); the manifest's `notFound` when it names none. */ gap?: ErrorSpec; /** The vendor's answer for a path its API serves under other methods than the request's (`405 Method not allowed: * {method} {path}`), `{method}` and `{path}` filled; the gap when it names none. */ wrongMethod?: ErrorSpec; /** The content codings the vendor reads a request's body in (its Content-Encoding: Tinybird's "Gzip or Zstandard" * events) and answers in when the request accepts one (Accept-Encoding), and its answer for a body that does not * decode as its Content-Encoding says. The kernel decodes before routing and encodes the API's answer. */ encodings?: { request?: ReadonlyArray<'gzip' | 'zstd' | 'deflate' | 'br'>; response?: ReadonlyArray<'gzip'>; undecodable?: ErrorSpec; }; /** The content type the vendor labels a JSON answer with, when it is not the runtime's (Clerk's exact * `application/json`, which @clerk/backend reads a body as JSON only on): every JSON answer relabelled. */ jsonContentType?: string; /** The vendor's tenancy (architecture, "The derived core"): each stored subject belongs to the tenant it was made in — * an organization, a team, an account — and a caller reaches only its own tenant's, as a parent's children are * reached under it. `field` holds it on each subject; `semantics/tenant.ts` names the caller's. The core scopes every * read, list, update and delete by it and stamps it on every create, for each resource not `shared`. */ tenant?: { field: string; storage?: 'namespaced'; }; /** The vendor's own lanes behind this manifest's API ("Other wires: lanes"), dispatched by the kernel before the * vendor's own doors, clock and API (LanesDecl). */ lanes?: LanesDecl; /** A host whose first label is part of the path, as a regular expression over the request's vendor host whose first * capture is put in front of the path before routing (S3's virtual-hosted addressing: `./` is * `//`); the host itself is left as it came. */ pathFromHost?: string; /** A prefix the vendor's hosts may put before a path (turbopuffer's region, `/aws-us-east-1`), as a regular expression * matched at the path's start: stripped before routing, so the operation it names is the one served. Its named groups * (Jira's `/ex/jira/(?[^/]+)`) are the operation's parameters as well. */ pathPrefix?: string; /** A prefix the vendor serves as its own base path (Discord answers `/api` and `/api/v9` as `/api/v10`, the spec's), as * a regular expression matched at the path's start: put in place of the surface's base path before routing, so an * operation compiled under the spec's base answers each. Perform and refresh send the spec's base, as the SDK does. */ basePathAlias?: string; /** A pattern over the request's vendor host whose named groups are the operation's parameters (E2B's envd answers each * sandbox at `49983-.e2b.app`: `^\\d+-(?[a-z0-9]+)\\.`). */ hostParams?: string; /** The vendor host a lane's calls go to when it carries the call's parameters (R2's `.r2.cloudflarestorage.com`): * `{name}` filled from the call's parameters, `values` a parameter's literal in the host (the real-system adapters, * "Lanes"). Perform and refresh send to `https://`. */ remoteHost?: { template: string; values?: Record>; }; /** Named operation parameters from vendor routing headers (shared-host compute services). */ headerParams?: Record; /** The persistent wires the vendor's clients hold open (sockets.ts: Discord's Gateway): each served at its path by * the pack's `semantics/sockets.ts`, which the kernel offers every write after its webhooks. */ sockets?: ReadonlyArray; /** The broadcasts the vendor takes over RTMP (architecture, "Other wires": live media): each ingest's id, which names * its engine in the pack's `semantics/live.ts`, and the RTMP app it answers. The pack's fetch carries the ingest * (`fetch.ingest`), which its server serves on a side port. */ live?: ReadonlyArray; /** The vendor speaks gRPC (architecture, "Other wires": gRPC): its server answers HTTP/2 and HTTP/1 on one port, each * rpc (by its proto unit's schema, `src/generated/proto.gen.json`) through the pack's own fetch. */ grpc?: true; /** The vendor runs its customers' images (machines.ts: Fly's Machines): the kernel serves `POST /_twin/machine-pool` * and hands handlers the World's pool as `ctx.machines`. */ machines?: boolean; /** A lane routed by host ("Other wires: lanes"): the hosts it serves, each exact or a suffix. The vendor's server sends * them here, and SHAPE judges the lane on them alone, never on a page or door of the vendor on another host. */ hosts?: ReadonlyArray<{ host?: string; suffix?: string; }>; /** The path parameters whose values span segments where the spec cannot say so (an OpenAPI path has no greedy label: * GitHub's `{ref}`, QStash's `{destination}`); a Smithy model's greedy labels are the surface's own `spanning`. */ spanning?: ReadonlyArray; /** The webhooks the vendor sends for its writes, as data the kernel renders, signs, delivers and records (events.ts); * `render` is the pack's `semantics/events.ts`, how the vendor renders an event's `data` when it is not the written * object. */ events?: EventsDecl & { render?: EventRender; values?: EventValues; }; /** called after every stored write with the rendered resource, its stored type and the kernel operation name */ onWrite?: (write: { operation: string; storedType: string; body: Record; root?: string; occurredAt: string; request: Request; /** the writing call's context, narrow as a handler's, at the write's moment: what the hook reads to render the event * it sends (until `declared-semantics` makes events data the kernel renders) */ context(): Promise; }) => Promise; }; /** A body's fields as a strict vendor checks them (`ctx.fields`, the manifest's `body.strict`). Without `strict`, every * field passes. An object or array field is not typed here: its own shape is the handler's. */ export declare function strictFields(m: DerivedManifest, operation: DerivedOperation, body: Record): { fields: Record; } | { refused: Response; }; /** A value as the vendor reads a boolean (`ctx.flag`, the manifest's `booleans`). */ export declare function flagOf(m: Pick, value: unknown): boolean | undefined; /** A request's parameters, its query's and its body's. With the manifest's `body.form.coerce`, a form's fields the * operation's spec types as numbers or booleans are read as them (parseBracketForm); without an operation (a twin door) * every form value is its text. */ export declare function readParams(manifest: DerivedManifest, request: Request, operation?: DerivedOperation): Promise>; export declare function vendorError(manifest: DerivedManifest, e: ErrorSpec): Response; /** The accounts a namespaced pack holds rows of (each stored type's `::account:` suffix), and the unsuffixed default: whose * catch-up a twin's due work runs (ADR 0036 §4). */ export declare function storedTenants(m: DerivedManifest, root?: string): Array; export declare const storedType: (m: DerivedManifest, resource: string) => string; /** A service's resources of one type, each the reader's own copy: `twinResources` filtered by type, from an index * that follows each write rather than projecting the whole tree per call. */ export declare function resourcesOfType(service: string, type: string, root?: string): TwinResource[]; /** The vendor's view of a stored subject: its own fields, bookkeeping (`_`) left out. */ /** A stored subject as the vendor's object: its id first (the subject's, unless the pack kept an id of its own), then * the fields the pack wrote, bookkeeping (`_`) and the kernel's updatedAt left out. */ export declare function render(r: TwinResource, vendorUnderscored?: readonly string[]): Record; /** Where the core runs: the World root it reads and writes, and its clock (the World's by default; * a caller that pins an instant passes its own). */ /** One call of a protocol-3 pack's default data (`src/semantics/seed.ts` exports `seed: SeedCall[]`): a request to the * vendor's own operation (or the pack's door), made in order against the twin by the runner `volter world init` writes * beside the copied data. An ordinary path is relative to the twin base. A call naming a browser uses the * vendor's absolute URL and is exported separately as `browserSeed`, after the ordinary `seed` calls. */ /** How a refresh list's answer items become subjects' fields where each is not one subject's object (architecture, * "Refresh"): `scalar`, a bare item is that field; `value` (with `keyed`), a scalar map value is that field and, with * `keyAs`, the map key is that field rather than the id; `spread`, an item expands into the array at `path`, each * element an object or a scalar named `as`, beside the item's fields `carry` names (field: path in the item). */ export type RefreshShape = { scalar?: string; value?: string; keyAs?: string; spread?: { path: string; as?: string; carry?: Record; }; /** each item with every item nested under it at this field, however deep (a tree of spans) */ recurse?: string; }; /** A read a root scoped to one of the vendor's own things makes instead of the resource's `refresh` (architecture, * "What the descriptor adds": `scopedRefresh`): `scope`'s `{name}`s capture the root scope's segments, and `each` makes * one read per distinct value at `path` among `from`'s observations of the same refresh, bound to `{as}`. The read itself * is a `refresh` list or get; its `idAs` reads the bindings too. */ export type ScopedRefresh = { scope: string; each?: { from: string; path: string; as: string; }; } & Exclude, { none: string; }> & { graphql?: never; }; export type SeedCall = { browser?: string; method: string; path: string; body?: unknown; headers?: Record; /** the instant the account made it, before the World's time: the call is made with the World clock frozen there */ at?: string; }; /** Where a call is answered: the World's root, its clock, and the managed Postgres the runtime binds to the pack * (`database`, the descriptor's `managedDatabase`), which a handler reaches as `ctx.engine` — READ ONLY in every * transaction when the twin is (`readOnly`) or the request is (x-volter-read-only). */ export type CoreScope = { root?: string; clock?: () => string; database?: string; readOnly?: boolean; resources?: DerivedSurface['resources']; /** `semantics/tenant.ts`: the tenant the caller acts in (the manifest's `tenant`), or undefined for none */ tenant?: (ctx: HandlerContext) => string | undefined | Promise; /** the application a walk stands in for: vendor requests and declared events are answered by it (events.ts) */ application?: ApplicationStandIn; }; /** World-owned generated values use the same private seed and log as pack secrets. */ export declare function worldSecret(service: string, root: string, label: string, at?: string, seedFile?: string): Promise; /** The same retained account primitive for pack doors and private native twin fronts. */ export declare function worldAccount(service: string, root: string | undefined, id?: unknown, at?: string, provisioning?: boolean): Promise; type WorldOrganization = { id: string; label: string; members: string[]; }; type VendorNameRule = { max: number; lower?: boolean; allowed: RegExp; separator?: string; first?: RegExp; }; /** The lane a vendor's router sent a request to (pack-fetch's laneRouter sets it). */ export declare const LANE_HEADER = "x-volter-lane"; /** What a coverage measurement sees of a pack's declared state logic: each move a request made and each refusal a * guard gave, by the transition that decided it. Nothing is observed unless a measurement installs an observer * (`twin-standard coverage`); serving never depends on it. */ export type TransitionEntry = { action: TwinAction; field: string; actor: Actor; }; export type TransitionObserver = (decl: StateField, transition: Transition, outcome: 'moved' | 'refused', from: string, entry?: TransitionEntry) => void; export declare function observeTransitions(observer: TransitionObserver | undefined): void; /** The transition a request asks for on one state field, or the vendor's refusal when none applies. */ /** What a declared machine says to one move: the transition that allows it, or the refusal it gives (and * nothing when it declares neither). The derived core and `legal` ask it; so does an engine that is not * HTTP-shaped (a line protocol's session), so one machine rules every wire. */ export declare function transitionFor(field: string, decl: StateField, operationId: string, current: unknown, requested: unknown, id?: string, actor?: Actor, entry?: TransitionEntry): { move?: Transition; refusal?: ErrorSpec; }; export type CoreOutcome = { served: Response; } | { unmodeled: string; }; export declare function mergeField(rule: ResourceDecl['update'], prior: unknown, next: unknown): unknown; export declare function serveCore(m: DerivedManifest, call: DerivedCall, scope?: CoreScope): Promise; /** Server-sent events in the manifest's framing. The events are known when the answer starts: the * twin decides deterministically, so the stream carries a decided answer, never a model's. */ export declare function sse(m: DerivedManifest, events: Array<{ event?: string; data: unknown; }>, operationId?: string): Response; /** What a semantics handler works with: the request's parameters, the tree through the pack's view, * the write path (which runs the manifest's write hook), and the declared machine. A handler never * imports the kernel; this is its whole interface. */ export type SemanticsContext = { call: DerivedCall; params: Record; /** This unit's generated discriminator requirements; an unknown resource is a derivation defect. */ variants(resource: string): NonNullable[number]['variants']; /** the last path parameter: the subject an item operation names */ id: string | undefined; /** the request body as the vendor reads it (an array, where the vendor takes one), and its text */ body: unknown; text: string; root: string | undefined; occurredAt: string; /** The twin's own base URL as this request reached it (its links and redirects to its own pages carry it). */ publicBase: string; /** What the World's scenario decided for this turn (a model vendor's answer: the handler matched, or the miss), on an * operation the pack's `semantics/scenario.ts` names; undefined elsewhere, or when the World carries no scenario. */ scenario: ScenarioDecision | undefined; /** The vendor's judgement at one of its decision points (a fraud score, an identity check, deliverability), for the * subject it is keyed to: what the World's scenario decided, else `byDefault`, the vendor's normal outcome; recorded in * the twin's log either way (architecture, "Scenarios"). The handler follows it with what the vendor does next. */ decide(point: string, subject: string, byDefault: T): Promise; /** A fault the World's scenario placed at a point of the pack's own (one item of a batch) for `subject`, recorded as * landed; undefined when none is placed. */ fault(point: string, subject: string): Promise<{ kind: string; status?: number; message?: string; errorType?: string; } | undefined>; /** A World fact (an exchange rate, a holiday, a place) as it stands at this request's World time, which the twin answers * with in its own shape; undefined when the World holds none. A read of the World's facts, as any read is: it writes * nothing, and the World's facts and clock give it again. */ fact(kind: string, key: string): Promise; /** A message the vendor sends the application's server and decides by its answer, waited on for at most `within` * milliseconds (a real-time authorization request): its status and body, or why there was none. */ ask(url: string, init: RequestInit, within: number): Promise; /** A git repository of the World, by the pack's name for it (the git plane, world-core git/): its objects in the * World's repository-scoped content-addressed object store, its refs in the World's store. Served over smart HTTP * (`git.serveSmartHttp`), read and written through the library's codecs. */ git(name: string): { store: GitObjectStore; refs: GitRefs; }; /** The git repository of a row of the manifest's `git.repository.resource`, under the one name it keeps through * adoption (`gitNameOf`). */ gitRepository(row: Record): { store: GitObjectStore; refs: GitRefs; }; /** A value the World set for its application (world-env.ts): what the app was given and the vendor must agree with (a * webhook signing secret the app verifies with), never the caller's own shell; undefined when the World sets none. */ worldEnv(name: string): string | undefined; /** Runs `fn` as the vendor's own move, not the caller's: what time makes due (a renewal a read catches up) is * recorded with no caller, wherever a handler reaches it. */ asVendor(fn: () => Promise): Promise; /** A mail the vendor hands on, over SMTP to the World's twin that receives each recipient's domain (smtp.ts, ADR 0032 * §3): each recipient's reply, `250` delivered and `5xx` refused; a domain no twin receives is refused by the kernel. */ mail(mail: Mail): Promise; now(): unknown; /** Render a stored row or vendor view using its resource declaration, retaining the stored subject id fallback. */ render(row: Record, resource?: string): Record; get(resource: string, id: string): Record | undefined; /** One credential subject in a manifest-declared owner's World store. Ambiguous stores refuse the read. */ ownerRow(owner: string, resource: string, id: string): Record | undefined; rows(resource: string): Array>; mint(resource: string): string; /** An id the vendor issues for what it does not keep (a completion's, a request's): minted, and its subject recorded, * so the next is another; a read-only request mints without recording. The resource is a declared bookkeeping type. */ issue(resource: string): Promise; /** The vendor's open sessions of one of its sockets in this World (a request answered by a session: sockets.ts). */ sockets(id: string): SocketSession[]; /** The World's recordings of what was broadcast to this twin (live media, live/access.ts): a recording's facts, and its * playlists, init and segments answered as the vendor's media host answers them. */ live: LiveAccess; /** Hold this read until the World writes (held-reads.ts: HTTP long polling): true when a write of one of the named * resources lands in this World, false when `ms` pass or the client hangs up; at once false in a read-only World. */ awaitWrite(resources: ReadonlyArray, ms: number): Promise; /** Observe a condition until it holds or the caller's timeout/cancellation, waking on writes and pollMs. */ awaitCondition(resources: ReadonlyArray, ms: number, pollMs: number, condition: () => Promise): Promise; /** A secret for `label` (an app's client secret, a store's read token): an HMAC under a seed the World makes once, at * random, and keeps as bookkeeping no door answers. The same label gives the same secret for the World's whole life, * and no one can compute it from ids the World shows, as they can a value derived from them alone. */ secret(label: string): Promise; /** The one door a key or a generated secret is issued through (ADR 0029, "Keys and generated secrets are retained World * state"): an API key, a webhook signing secret, a bot token, each its own `purpose`, for `account` (default: the * account the credential door selects, `ctx.account()`), in the vendor's `format`. Its value is a pure function of the * World's seed identity, the account and the purpose, nothing else (no minted id, no time, no request), so a reset, at * whatever instant, issues the same value and an application holding it stays accepted. The issuance is recorded * (`_world_issued_key`, at `/`, holding only the value's SHA-256), so `issuedKey` accepts it and * nothing else; a read-only request issues without recording. It answers the purpose's live generation: once * `revokeKey` revoked one, the next is issued (its value drawn under `#`), so a rotation is a * revocation and the same call again, and the revoked value stays refused. */ issueKey(purpose: string, format: KeyFormat, account?: string): Promise; /** An id that names an issued key or appears in it or beside it (a dashboard's key id, a DSN's ids, Slack's * `xapp-`, Telegram's `:`, a snowflake, a project id), in the vendor's id `format`: drawn from the same * three inputs as `issueKey` under its own label, of the purpose's live generation, as stable, and revealing nothing * of the key. Not recorded. */ issueKeyId(purpose: string, format: KeyFormat, account?: string): Promise; /** The issuance `value` was issued by in this World, when it is its purpose's live generation: its account and purpose. */ issuedKey(value: string): { account: string; purpose: string; } | undefined; /** Revoke the live generation of `purpose` for `account` (a key deleted, disabled or expired): `issuedKey` refuses its * value, and the next `issueKey` of the purpose issues its next generation. */ revokeKey(purpose: string, account?: string): Promise; /** Select an account at a pack's credential door. Packs retain their own vendor account/key semantics. */ account(field?: string): Promise; /** The selected organization's label and people from the World's organization registry. */ organization(): Promise; /** The selected deployment, or an empty string for the organization's own level. */ deployment(): string; /** A vendor-safe label; retained links keep identity independent of names. */ vendorName(label: string, rule: VendorNameRule, options?: { suffixed?: boolean; identity?: string; }): string; /** Retain the native customer tenant for the selected organization. */ tenant(resource: string, make: (organization: WorldOrganization) => Promise): Promise>; /** Retain one native resource of this kind for the selected organization and deployment. */ deploymentObject(kind: string, resource: string, make: (deployment: string) => Promise): Promise>; /** Reconstruct a live native key, replacing its link when the vendor's reader refuses it. */ accountKey(purpose: string, resource: string, key: { make: () => Promise; read: (row: Record) => Promise; }): Promise<{ id: string; secret: string; }>; /** The World's machine pool (machines.ts), as the pack's `machine-pool` door enrolled it; `none` when none was. */ machines: MachinePool; /** A signing key pair for `label` (an issuer's ID tokens, a provider's JWTs, a CA's or a log's key), PEM: RSA 2048 * (the default) or Ed25519, made once, at random, when the label is first asked for, and kept as bookkeeping no door * answers, so what it signs verifies against the World's published key (ctx.crypto.jwks of the public half) and no * one can forge it from anything the pack or the World shows, as they can with a key written in the pack. */ signingKey(label: string, alg?: 'RS256' | 'Ed25519'): Promise<{ privatePem: string; publicPem: string; }>; /** The signing key for `label` when the World has made it (`signingKey`), else undefined: for code that signs where it * cannot wait (a cookie's token, read everywhere), after a front made the key before anything is answered. */ heldSigningKey(label: string, alg?: 'RS256' | 'Ed25519'): { privatePem: string; publicPem: string; } | undefined; /** Allocate a stored occurrence and append its fields under one action lock. The optional field factory is pure. */ create(resource: string, fields: Record | ((id: string) => Record), operation: string): Promise>; /** Create under declared unique keys and the action lock; a collision returns the existing own-field view without a write. */ createUnique(resource: string, fields: Record | ((id: string) => Record), operation: string, options?: { input?: 'omit'; id?: string; }): Promise<{ created: boolean; row: Record; }>; /** Decide an update from the current live stored row under the action lock; undefined leaves it unchanged. */ change(resource: string, id: string, decide: (row: Record) => Record | undefined, operation: string, options?: { input: 'omit'; }): Promise | undefined>; write(resource: string, id: string, fields: Record, operation: string): Promise>; /** * One command's writes as one group (docs/contributing/architecture.md, "A command's writes as one group"). * Inside `fn`, `write` stages its write and answers the row as it will stand; `row` and `rowsRaw` read the tree with * the staged writes folded over it, as it will be once they land. When `fn` returns or throws, every staged write * lands, in order, as one append; then its value is answered or its error thrown. Every other way to write, or to * wait on a write, lands the staged writes first; any other read of the tree (`get`, `rows`, `tree`, `history`, ...) * while writes are staged is refused, never answered without them. Each write keeps its own action, id, ordinal, * moment and recorded request. Where the pack has write hooks, events, sockets or counts, a state observer is on, * a head performs, or ids are aliased, `fn` simply runs, each write landing as it is made. */ batch(fn: () => Promise): Promise; /** Add numeric deltas to an existing bookkeeping row under the kernel's atomic write seam. */ accumulate(resource: string, id: string, deltas: Record, operation: string): Promise; /** `write`, with what a live vendor answered when the head performed it */ writeDetailed(resource: string, id: string, fields: Record, operation: string): Promise<{ body: Record; id: string; vendorData?: unknown; }>; /** The id a subject has now, for an id a caller may still use from before the vendor minted its own * (a branch naming a message by the ts it minted locally). */ /** The tree's type a resource's rows are kept under (the manifest's `storedAs`, else its name): what an operation on * it is named by (`issuing_card.create`), as the vendor names the events it sends. */ storedType(resource: string): string; resolve(resource: string, id: string): string; /** Answer the vendor's success envelope around several fields (`{ ok: true, ts, channel, message }`). */ ok(fields: Record): Response; /** A stored row as it is kept, bookkeeping (`_`) fields and tombstones included. */ row(resource: string, id: string, opts?: { withDeleted?: boolean; }): Record | undefined; rowsRaw(resource: string, opts?: { withDeleted?: boolean; }): Array>; /** Every stored subject of the pack, of every type, in the tree's order (a projection folding many types at once). */ tree(): Array>; /** The writes that touched a subject, in order: its history. */ history(resource: string, id: string): Array<{ operation?: string; fields?: Record; occurredAt?: string; }>; /** Write bookkeeping without the incoming request; an explicit operation observes its checked state move. Mint an id when none is given. */ record(type: string, fields: Record, id?: string, operation?: string): Promise; /** Decide a write from the tree as it stands and make it, with nothing written between the read * and the write (a minted number, a first poll that moves a subject). `decide` returns the write, * or nothing to write; the answer is its `value`. */ atomically(decide: (rows: (resource: string) => Array>) => { value: T; write?: { resource: string; id: string; fields: Record; operation: string; }; }): Promise; /** Answer bytes or text as they are (a file's content), with the vendor's headers. */ raw(body: BodyInit | null, init?: { status?: number; headers?: Record; }): Response; /** Whether the machine lets `operationId` move `field` from `current` (to `to`): nothing when it * does, the vendor's refusal when it does not. A move the machine does not declare throws. */ legal(resource: string, field: string, operationId: string, current: unknown, to?: string, id?: string, actor?: Actor): ErrorSpec | undefined; /** Validate the request body's top-level derived schema under body.validation, before a write. */ validate(): Response | undefined; refuse(e: ErrorSpec): Response; /** Answer the manifest's declared unserved capability gap. */ gap(): Response; notFound(resource: string, id: string, param?: string): Response; reply(body: unknown, status?: number): Response; /** Answer in the vendor's success envelope under this operation's key (`{ ok: true, channel }`). */ wrap(body: Record, extra?: Record): Response; /** Answer as a server-sent event stream, framed as the manifest says. */ sse(events: Array<{ event?: string; data: unknown; }>): Response; expand(resource: string, body: Record, paths?: string[]): Record; /** This context at another moment of the World clock (ISO): a move time makes is written at the moment it fell due. */ at(when: string): Promise; /** This call's context over another manifest of the same service, at the same moment: a lane over its vendor's * state reads and writes the vendor's resources through the vendor's manifest ("Pack layout"). */ over(other: DerivedManifest): Promise; /** The generic core's answer to this call, or undefined where the core does not serve it. */ core(): Promise; /** A stored row's own fields, as the vendor's object carries them (an `id`, `type` or `updatedAt` of its own restored). */ own(row: Record): Record; /** A handler's own rows (views) answered as the call's list: the resource's filters, search and order, then the * manifest's paging and envelope; the vendor's refusal when the call orders by a field the resource does not take. */ list(resource: string, rows: Array>): Response; /** The vendor's refusal when these fields would make a second live subject where the resource's `unique` rules allow * one (`except`: the subject being updated), or nothing. */ conflict(resource: string, fields: Record, except?: string): Response | undefined; /** A subject deleted as the vendor deletes it: every subject its resource's `cascade` names deleted first, then it, * each through the write path (`operation` names the subject's own delete when it is not `.delete`). */ remove(resource: string, id: string, operation?: string): Promise; /** The subject a key names, by its id (an alias the caller may still use resolved) or one of the resource's * `alternateKeys` (an organization by its slug), as the vendor serves it. */ find(resource: string, key: string): Record | undefined; /** A field's new value as the resource's `update` rule merges it into the stored one (`deep`: Clerk's metadata). */ merge(resource: string, prior: unknown, next: unknown): unknown; /** What a handler signs and hashes with (signing.ts): JWTs with a pack's key, their verification, a JWKS, an HMAC and * a SHA-256, deterministic, so no pack reaches `node:crypto` itself. */ crypto: HandlerCrypto; /** The World's managed Postgres (managed-database.ts): one transaction per batch, as a role with its settings, or a * script. A World that binds none refuses every use with the reason (EngineUnavailableError). */ engine: ManagedDatabase; /** A vendor's Redis (the kernel's Redis library, redis/engine.ts): a request's commands run in order over this call's * tree and clock, in the pack's own service, under its wire's dialect, in one of its databases (`database`: its keys * and scripts apart from the others'); each answered `{result}` or `{error}`, and whether any wrote. A read-only * World raises ReadOnlyError at the first write. `transaction` distinguishes a wire's queued transaction from * a pipeline for script restrictions. The wire around it (Upstash's REST envelope) is the pack's. */ redis(commands: string[][], options: { dialect: RedisDialect; database?: string; transaction?: boolean; }): Promise<{ items: RunItem[]; wrote: boolean; }>; /** Another vendor's own URL answered by the World's twin of it (vendor-call.ts): a vendor's call to another as part of * its behaviour (Clerk exchanging a Google sign-in's code). A vendor the World runs no twin of is refused * (VendorUnreachableError); nothing leaves the World. */ vendorFetch(url: string | URL, init?: RequestInit): Promise; /** A multipart/form-data body's parts in order (multipart.ts: field name, filename, media type, bytes), a part with an * empty field name included; none for any other body. */ parts(): Promise; /** The pack's resource blobs (an object's bytes), by key, on the World's branch: they branch with the World, and a * read falls back to an ancestor's. The row that names a blob is the pack's; the bytes are here. */ blobs: { put(key: string, bytes: Uint8Array): Promise; get(key: string): Promise; remove(key: string): Promise; /** a body written as it arrives (a request's own stream), kept only when `accept` holds for its size and SHA-256: * an upload of a large object never held whole. True when kept */ putStream(key: string, body: ReadableStream | AsyncIterable, accept: (written: { size: number; sha256: string; }) => boolean): Promise; /** a blob's length, or null when there is none: a large object is answered without loading it */ size(key: string): Promise; /** the bytes `start`..`endInclusive` of a blob (a ranged read where the store has one), or null when there is none */ range(key: string, start: number, endInclusive: number): Promise; }; /** A body's fields checked against the operation's declared ones under the manifest's `body.strict`: the fields, or * the vendor's refusal of the first that is unknown, of another type or out of its bounds. */ fields(body: Record): { fields: Record; } | { refused: Response; }; /** A parameter as the vendor reads a boolean (the manifest's `booleans`): true, false, or undefined for a value that * is neither (absent, or text the vendor does not read as one). A boolean passes as itself. */ flag(value: unknown): boolean | undefined; }; export type Semantics = (ctx: SemanticsContext) => Promise; /** The context a derived pack's handler is given ("What an author writes, and how"): the kernel's own members * (`now`, `core`, `atomically`, `tree`, `writeDetailed`) and the tree's location (`root`) are not on it, so a handler * typed `Handler` cannot reach them. Its reads are those the contract lists (`row`, `rowsRaw`, `rows`, `get`, * `history`, `resolve`, `expand`); `at` and `over` give the same narrow context at another moment or over the * vendor's manifest. */ export type HandlerContext = Omit & { /** This context at another moment of the World clock (ISO): a move time makes is written at the moment it fell due. */ at(when: string): Promise; /** This call's context over the manifest of the vendor whose state a lane shares, at the same moment. */ over(other: DerivedManifest): Promise; }; /** What a write hook reads: the writing call's context without its ways to write, so a hook that renders an event * cannot write again (and run itself again). */ export type WriteHookContext = Omit; /** A derived pack's handler: one operation, by its operationId, over the contract's context. */ export type Handler = (ctx: HandlerContext) => Promise; /** What a context consumes the World's scenario through (scenario-consume.ts): its twin's bookkeeping, at its time. */ export declare function scenarioLedgerOf(ctx: object): ScenarioLedger; /** `GET /twin/scenario`: what the World's scenario placed on this vendor, and what the twin consumed of it. */ export declare function scenarioRecords(m: DerivedManifest, root?: string): { vendor: string; placed: unknown[]; consumed: { decisions: unknown[]; faults: unknown[]; }; }; export declare function contextFor(m: DerivedManifest, call: DerivedCall, scope: CoreScope): Promise; /** A pack's semantics handlers as the dispatch's handlers. */ export declare function bindSemantics(m: DerivedManifest, handlers: Record, scope?: CoreScope): Record; /** The first of a request's form parameters whose value is not one its spec lists (DerivedOperation.enums), with the * bracket name a form gives it (`spending_controls[spending_limits][0][interval]`) and the values it takes. */ export declare function valueOutside(params: Record, enums: Readonly>>): { param: string; values: ReadonlyArray; } | undefined; /** Whether a request's parameters ask one of the operation's undemanded variants (DerivedManifest.variants). */ export declare function variantAsked(params: Record, variants: readonly string[], headers?: Headers): boolean; /** The derived core as the dispatch's core: it owns every operation on a resource the manifest declares. */ export declare function coreFor(m: DerivedManifest, scope?: CoreScope): { owns: (o: DerivedOperation) => boolean; serve: (call: DerivedCall) => Promise; }; /** Read-only refusal, API-version validation and idempotent replay, applied once around every * operation a handler or the core serves. */ /** The vendor's refusal of a request's credential under the manifest's `auth`, or undefined when it passes: what the * cross-cutting gate answers for an operation, and what a pack whose vendor checks the credential before routing (an * unknown path answers 401, as Supabase's recording shows) calls in front of its dispatch. */ /** The header the kernel names a scenario's decision in, set by createPackFetch alone (it strips it from every request it * is sent). */ export declare const SCENARIO_DECISION_HEADER = "x-volter-scenario-decision"; /** HTTP field values are bytes; JSON escapes retain Unicode without putting it directly in a header. */ export declare function scenarioDecisionHeader(decision: ScenarioDecision): string; /** The header createPackFetch alone names a placed `failed` fault in (its timeline entry), so it lands where the vendor * fails: inside its idempotency layer (crossCutting). Stripped from every request the twin is sent. */ export declare const SCENARIO_FAULT_HEADER = "x-volter-scenario-fault"; /** A request fault's status answer, in the vendor's own error envelope. */ export declare function faultError(m: DerivedManifest, fault: PlacedFault): Response; /** The credential a request presents where the manifest's `auth` reads it (the first source that holds one), else, for a * manifest that declares none, its Authorization header; '' when it presents none. */ export declare function presentedCredential(m: DerivedManifest, request: Request): string; export declare function authRefusal(m: DerivedManifest, request: Request, root?: string): Response | undefined; export declare function crossCutting(m: DerivedManifest, opts?: CoreScope & { readOnly?: boolean; }): (call: DerivedCall, next: () => Promise) => Promise; /** The vendor's idempotency layer (crossCutting's) around a request no surface operation names: a GraphQL wire's, whose * mutations it keys as the manifest declares. */ export declare function graphqlIdempotency(m: DerivedManifest, opts?: CoreScope & { readOnly?: boolean; }): (request: Request, next: () => Promise) => Promise; /** A derived pack's whole fetch behind the kernel's read scope (twin-fetch.ts withRequestScopes): a * read-only request's writes are refused at the write seam — the ones `crossCutting` cannot see * coming (another wire's mutation, a door, a screen) — and answered with the vendor's own read-only * error; `GET /twin` advertises `requestScopes`. The pack's catch-up runs under `runAsVendorMove` * (request-scope.ts), so time's moves still land when a read-only request is what arrives. */ export declare function derivedRequestScopes Promise>(m: DerivedManifest, fetch: F, readOnly?: boolean): F; /** A semantics context for a request no surface operation names: another wire's (GraphQL) resolvers * get the same interface as a handler, named by the operation id the wire gives. */ export declare function semanticsContext(m: DerivedManifest, request: Request, operation: DerivedOperation, scope?: CoreScope): Promise;