Skip to Content

Generating Types

foir types produces the module the data client is built on. It is not a convenience step: the generated file carries both halves of what the client needs — the types that shape your calls, and the selection trees it prints documents from.

npx foir types --out src/foir.generated.ts

Run it when you set the project up, and again whenever the schema moves. Commit the result: it is a deterministic build input, and CI should not need a network call to your project. --check writes nothing and exits non-zero when the committed file differs from a fresh generation, which is the shape you want in a pipeline.

Note: the client also works with no generated file at all, by fetching the same description at construction. That is a fallback, not the deployed path.

GET /v1/manifest

The manifest is the per-caller description of your project: the models, their fields and relations, the operations your key may call, the resolved selection behind each one, and the two versions it carries. It contains only what your credential may do, so there is no client-side filtering anywhere.

curl -H "x-api-key: foir_pub_..." https://api.foir.dev/v1/manifest
{ "schemaVersion": 204, "surfaceVersion": "5b0c9f3e1d2a4c6e8f7a9b1c3d5e7f90", "surfaceHashes": { "models.cost_breakdown": "4e0b6a5c3f7b8d9e1a2c3b4f5e6a7c8d", "namespaces.auth": "6a2d8c7e5b9d0f1a3c4e5d6b7a8c9e0f", "selectionUnions.Block": "ae6b2a1c9f3b4d5e7a8c9b0f1e2a3c4d", "subscriptions": "0f1e2d3c4b5a69788796a5b4c3d2e1f0" }, "channel": "published", "models": { "cost_breakdown": { "typeName": "CostBreakdown", "kind": "record", "ops": { "findUnique": { "field": "costBreakdown", "args": ["contexts", "id", "locale", "naturalKey", "preview"], "argTypes": { "id": "String", "naturalKey": "String", "locale": "String" }, "payload": { "kind": "record", "model": "cost_breakdown" } }, "findMany": { "field": "costBreakdowns", "args": ["after", "before", "first", "last", "orderBy", "where"], "argTypes": { "first": "Int", "where": "CostBreakdownWhereInput" }, "payload": { "kind": "object", "fields": [{ "key": "edges", "fields": [] }] } } }, "selection": { "fields": [ { "key": "_id" }, { "key": "heading" }, { "key": "sections", "fields": [{ "key": "cost" }, { "key": "label" }] } ] }, "relations": [], "cacheControl": { "scope": "PRIVATE", "maxAge": 60 } } }, "namespaces": { "auth": { "ops": { "currentUser": { "field": "currentUser", "payload": { "kind": "object", "fields": [] } }, "deleteMyAccount": { "field": "deleteMyAccount", "mutation": true, "args": ["confirm", "password"], "argTypes": { "confirm": "Boolean!", "password": "String" }, "payload": { "kind": "object", "fields": [] } } } } }, "selectionUnions": { "Block": { "members": [{ "typeName": "CostBreakdownBlock", "fields": [] }] } }, "subscriptions": [ { "field": "recordChanged", "args": ["modelKey"], "argTypes": { "modelKey": "String!" }, "argScope": { "arg": "modelKey", "prefix": "records:read:", "values": ["page", "product"] }, "selection": { "fields": [{ "key": "recordId" }, { "key": "action" }, { "key": "seq" }] } } ] }

Three parts of that are worth naming, because they are what makes a document printable without a schema on the client:

  • schemaVersion and surfaceVersion are two versions of different things. schemaVersion is the invalidation counter, which moves on every write that could change a response and keys the ETag below. surfaceVersion is a hash over exactly the sections foir types reads, so it moves only when regenerating would write a different file, and surfaceHashes holds its components, one per model, namespace, union and the subscriptions. Your generated module is pinned to the surface; see schema drift.
  • ops.<name>.field — the GraphQL root field the operation compiles to. findMany on cost_breakdown becomes costBreakdowns. You address the operation by its canonical name; the root field is what the response is keyed by.
  • ops.<name>.argTypes — each argument’s declared GraphQL type. Arguments travel as variables typed from this, which is why an enum argument is coerced by the executor rather than guessed from its JavaScript value.
  • selection and selectionUnions — the resolved complete-by-default tree, with unions already expanded per member and colliding response keys already renamed. Nothing on the client re-derives a name.
  • subscriptions — the streams this credential may open, each with its own resolved selection. argScope names the values the server will accept for the gating argument, which for recordChanged is the set of models your key may watch.
  • unclassified: root fields your credential can reach that the projection did not attribute to any model operation or namespace, so they get no generated operation. It should be empty; a name here is a gap between the schema and the manifest, and foir.raw() still reaches it. The untyped record, records and recordVersions are the records namespace, and locales and resolvedLocale are in project; see Choosing an API Style.

Caching

The manifest is Cache-Control: private, no-cache with a weak ETag that encodes the invalidation counter (schemaVersion) and channel:

etag: W/"204-published-98b3bf463c69032e" vary: x-api-key, …, X-Foir-Schema-Channel, Origin

If-None-Match returns 304 while the counter stands still, so polling is cheap. A 200 means only that the counter moved: whether your generated types are stale is the surfaceVersion in the body. It varies on the API key, so two credentials never share a cached manifest.

The generated module

The output is a single .ts module — not a .d.ts, because part of it has to survive to runtime.

// foir.generated.ts — DO NOT EDIT. Generated by `foir types`. import type { FoirManifestSelectionUnion, FoirSchemaDefinition, FoirSelectionModel, FoirSelectionNamespace, } from '@foir/sdk/data'; export const foirSurfaceVersion = '5b0c9f3e1d2a4c6e8f7a9b1c3d5e7f90'; export const foirSurfaceHashes: Record<string, string> = { /* … */ }; export const foirSchemaChannel = 'published'; export interface CostBreakdown { _id: string; _createdAt: string; heading: string | null; salesPrice: number | null; sections: Array<CostSection | null> | null; } export interface FoirSchema extends FoirSchemaDefinition { surfaceVersion: typeof foirSurfaceVersion; channel: 'published'; models: { cost_breakdown: { typeName: 'CostBreakdown'; fields: CostBreakdown; relations: {}; ops: { findUnique: { args: CostBreakdownFindUniqueArgs; returns: { kind: 'record'; nullable: true } }; findMany: { args: CostBreakdownFindManyArgs; returns: { kind: 'connection' } }; }; }; }; namespaces: { auth: { ops: { whoami: { args: Record<string, unknown>; result: unknown } } }; }; } export const foirSelections: Record<string, FoirSelectionModel> = { /* … */ }; export const foirNamespaceSelections: Record<string, FoirSelectionNamespace> = { /* … */ }; export const foirSelectionUnions: Record<string, FoirManifestSelectionUnion> = { /* … */ }; // Type carrier: `FoirSchema` is an interface and erases, so this is what lets // the client infer it from the module. Its runtime value is `undefined`. export const foirSchemaType = undefined as unknown as FoirSchema;

The const exports are the runtime half. Pass the module, not the exports:

import * as generated from './foir.generated'; const foir = createFoirClient({ apiUrl, apiKey, generated });
ExportWhat it is
foirSurfaceVersionThe surface these types came from: a hash over exactly what foir types read. Enables the drift check
foirSurfaceHashesThe components that version is folded from, so a drift names the models that moved
foirSelectionsOne entry per model: its type name, its ops, its complete selection, its relations
foirNamespaceSelectionsThe same for namespace operations
foirSelectionUnionsEach union’s expansion, per member, with renamed keys resolved
foirSubscriptionsThe Subscription root fields this credential reaches, each with its resolved payload selection. Lets a subscribing client print without fetching the manifest
foirSchemaTypeCarries FoirSchema to a value, so the type parameter is inferred rather than restated. Never read at runtime

foirSubscriptions is the one exception to the rule below: it is optional, and a module generated before it existed is not refused. Such a module simply does not answer the subscription question, and the client falls back to the manifest fetch it was already making — so nothing breaks at construction for a round trip it was happy to pay. Re-run foir types to pick it up.

There is no case where a subset of the rest is wanted, so a module missing one of those is a compile error naming it, and a refusal at construction for a JavaScript caller. That is the point rather than strictness for its own sake: each export has its own failure, and none of them used to be loud. A missing foirNamespaceSelections makes every foir.ns.* call an error naming the namespace; a missing foirSelectionUnions fails the first time a tree names a union; and a foirSelections in the wrong shape printed nothing at all and sent every call to the manifest instead, which looked exactly like success.

The individual fields still exist and still win where both are given:

const foir = createFoirClient<FoirSchema>({ apiUrl, apiKey, surfaceVersion: foirSurfaceVersion, surfaceHashes: foirSurfaceHashes, selections: foirSelections, namespaceSelections: foirNamespaceSelections, selectionUnions: foirSelectionUnions, });

Use that form only to override one piece of a module you are otherwise passing whole, or when your server publishes no selection trees at all — in which case foir types says so, and the generated file’s own header tells you to wire it this way.

Four things about the shape are worth knowing, because they explain behaviour you would otherwise find surprising:

  • fields is the complete scalar set, none optional. That is what makes the model type unconditionally true — see Selection and Responses.
  • Relations are not in fields. They exist on a result only when include asks for them.
  • Model and operation keys are verbatim. cost_breakdown, not costBreakdown; findMany, not costBreakdowns.
  • Polymorphic fields are written out as a static discriminated union on __typename, with any renamed keys already applied. There is no inference step, so a switch over one narrows exactly as the generator emitted it.

Argument types

Most arguments are platform-fixed and typed exactly (first is a number, contexts is an object, and so on). Two are shaped by your own models, and they are handled differently:

  • orderBy is a closed type. The manifest publishes each model’s sort vocabulary, so foir types emits a <Model>OrderBy beside the model and both the field and the direction are checked at build time. orderBy: { createdAt: 'NOPE' } and orderBy: { noSuchField: 'DESC' } are compile errors, not 400s. It takes a single entry or an array of them, sorted in order.

    The keys are not the model’s fields. Sortable fields are a server-side subset: the record carries _createdAt and _id while the sort keys are createdAt and id, and a field of a non-orderable type — an image, a prose field, a soft-deleted field — cannot be sorted by at all. The generator prints what the server published rather than deriving it, which is why the two cannot disagree.

  • where is unknown. Its shape is not published, so the generated types offer no help and no obstruction. See Filtering.

A server that predates the published vocabulary leaves orderBy unknown too — the generated file’s own header says which of the two you have.

Namespace results

The manifest describes a namespace op’s root field and its result shape, but not its argument or result types, so foir types emits args: Record<string, unknown>; result: unknown for each one. An awaited namespace call is unknown and you narrow it at the call site — see namespace operations.

Per-key shaping

The manifest is per-credential, so the generated module is too. Generate once per credential that calls Foir: your app’s publishable key, and its server key where a server renders its pages. Name each by its id and your signed-in session reads its surface, so no secret is handled to generate types:

npx foir types --api-key-id $PUBLIC_KEY_ID --out src/foir.public.ts npx foir types --api-key-id $SYNC_KEY_ID --out sync/foir.sync.ts

In CI, with no session, pass the key itself with --api-key or FOIR_API_KEY; the module is the same.

The public module will have no create/update/delete on any model, so calling one in your app’s code fails to compile rather than failing at runtime. Your app’s own writes belong in an operation, whose endpoint’s module is generated per operation, below.

Per-operation shaping

An operation’s endpoint calls Foir with the dispatch token it is handed, not a key, so its types are the surface that token is served: what the operation declared in its grants. --operation generates them, from GET /v1/manifest?operation=<key>:

npx foir types --operation checkout --out src/checkout.generated.ts

Your session must be able to author the operation (operations:write); the surface is refused to anyone else. The module exports foirCredential = { operation: 'checkout' }, and it is for a client built from that operation’s dispatch token alone: createFoirClient({ apiUrl, dispatch, generated }) requires it, a key client refuses it, and a dispatch whose context names another operation is refused. See Writing an Operation Endpoint.

The manifest fallback

If you construct a client without generated and without selections, it fetches GET /v1/manifest once at first use and reads the same trees off the response. Every call then behaves identically — same documents, same responses.

What it costs is a round trip in front of your first query, on every cold start, to learn something a generated file already knows. On an edge runtime that is the request your user is waiting on.

So: keep it for a REPL, a one-off script, or the first five minutes with the client. Pass the generated module for anything you deploy.

It is a fallback you choose, never one you land in. A client built without either says so once, on console.info:

[foir] no generated module passed, so this client fetches `GET /v1/manifest` once at first use and prints from the trees it publishes. …

Silence it with announceManifestFallback: false when the fallback is what you meant. A module that is passed but cannot be printed from is refused outright rather than quietly becoming this path.

Schema drift

Generated types are a snapshot, and under build-time selection they are more than a snapshot of the types: they are the snapshot of the selection. A field added upstream is not in your document until you regenerate.

The module carries foirSurfaceVersion, so the client can compare it with the surface the server is serving and tell you, naming what moved. Ask for that with checkSchemaDrift: true:

const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, apiKey: process.env.PLATFORM_API_KEY!, generated, checkSchemaDrift: true, });
[foir] schema drift: the types were generated from surface 5b0c9f3e1d2a4c6e8f7a9b1c3d5e7f90, and the server is serving c4e1a7b90d2f3e5a6b8c9d0e1f2a3b4c (published). Changed since: model `page`. Everything the generated module describes is still served as generated, so every typed call keeps working. The surface has grown: re-run `foir types` to pick up what is new, because a field added since is not merely untyped, it is not requested.

How it behaves, all of it deliberate:

  • Once per client instance, not per request.
  • Never awaited. It is a developer warning, not part of your response — a second round trip on the critical path to say “your types are stale” would be a worse trade than occasionally losing the warning on an edge runtime that ends the invocation early.
  • Never rejects into your app. A failed drift check is swallowed.
  • Per-instance, never module-level. On a stateless multi-tenant worker a module-level flag would let the first project to check silence the warning for every other tenant in the isolate.
  • Free in fallback mode, where the manifest is already in hand.

The check is off unless you ask for it, because it reads GET /v1/manifest once per client. A Worker, a serverless function or a page load builds a new client every time, so a check on by default would add that read to every start, for an answer that only changes when you release. Run foir types --check in CI to catch drift before it ships, and call checkFoirSchemaDrift where a running app should find out at a moment you choose. It resolves to the drift, or null when your module matches:

import { checkFoirSchemaDrift } from '@foir/sdk/data'; const drift = await checkFoirSchemaDrift({ apiUrl, apiKey, generated }); if (drift) logger.warn({ changed: drift.changed }, 'foir types are stale');

Route what a checking client finds somewhere useful with onSchemaDrift:

onSchemaDrift: ({ generated, server, channel, changed, incompatible }) => { logger.warn({ generated, server, channel, changed, incompatible }, 'foir types are stale'); },

changed lists the components that moved, as the manifest keys them: models.page, namespaces.operations, selectionUnions.Block, subscriptions.

incompatible lists what your module describes that the server no longer serves that way, as paths: models.order.selection.status, models.order.ops.update, namespaces.search.ops.searchRecords.args.query. It is empty when the surface has only grown, which is the usual drift, and it is what the next section is about.

Omitting surfaceVersion disables the check entirely.

Note: the check compares the surface, never the counter. Pushing an operation, a role or a key moves schemaVersion and leaves every byte of your generated file where it was, so it is not drift and the client says nothing. A field published on a model your types include moves the surface, and the client names the model. Every drift it reports is real: regenerate, and read the diff, which is the point of committing the file.

Refusing a call the server can no longer answer

Drift and incompatibility are different things, and the client treats them differently.

Drift is the surface version having moved. It moves when the surface grows: a field published on a model, an op added to a namespace, a mutation the platform adds to every model. None of those changes a document your module prints, because the document names the fields and arguments the module knew about and the server still has all of them. So drift is reported once, and it never refuses a call.

Incompatibility is something a call depends on no longer being served the way your module describes it. In a client built with checkSchemaDrift: true, once the manifest has arrived the client compares its generated trees with the served ones, and from then on a typed call throws FoirSchemaDriftError when:

what changedwhich calls are refused
the op is gone, or its root field or result kind changedcalls to that op
an argument the module declares is gone, or its type no longer accepts the generated onecalls to that op
the op now requires an argument the module does not knowcalls to that op
a field the selection names is gone, or changed shape (a leaf became an object, a field became a relation)every call whose result carries that model’s record: findUnique, findMany, the writes, and a namespace op that returns it
a union member lost a field, or left the unionevery call whose result carries a model that embeds the union
a relation changed target, became a list, or its target model lost a fieldcalls that include that relation

Anything added refuses nothing: a new model, namespace, op, optional argument, field, relation, union member or subscription. An argument that went from required to optional refuses nothing either.

Two things to know about how far a refusal reaches. A relation’s target counts only for a call that includes the relation, so a broken author does not stop page.findMany(), only page.findMany({ include: { author: true } }). And a refusal is not narrowed by pick or omit: a call that omits the one field that is gone is still refused.

The error carries the drift, so you can tell “your generated module is stale” from “this request failed”, and its message names what the refused call depends on:

[foir] refusing order.findMany: the types were generated from surface 5b0c9f3e1d2a4c6e8f7a9b1c3d5e7f90, and the server is serving c4e1a7b90d2f3e5a6b8c9d0e1f2a3b4c (published). Changed since: model `order`. This call depends on models.order.selection.status (no longer served), which the server no longer serves as the generated module describes. Re-run `foir types`.

It is the default because the alternative is worse to debug. A call that depends on a removed field is answered with a server error about the field, and one whose relation became a list is answered in a shape your types do not describe. Neither says the generated module is the thing to fix.

strictSchemaDrift: false is never the remedy. A refusal names something that really is no longer served as generated, so the fix is foir types. The opt-out exists for an app that would rather send the call and handle the server’s answer, and it is written at the call site, where a reader can see it:

const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, apiKey: process.env.PLATFORM_API_KEY!, generated, strictSchemaDrift: false, });

Two things it deliberately does not do:

  • It does not fail the first call. Drift is only known once the manifest comes back, and that request is made off the response path after a call has already been served. Refusing retroactively would mean blocking every first call on a second round trip, which is the cost the warning exists to avoid.
  • It does not touch raw(). A hand-written document is not printed from the generated trees, so nothing the comparison finds says anything about it.

A client with no generated module prints from the manifest it fetched, so it has nothing older to compare and is never refused.

To stop a stale module reaching production at all, foir types --check exits non-zero when the committed file differs from a fresh generation. That is the CI gate; strictSchemaDrift is the runtime one.

Last updated on