Documentation menuMenu da documentação

$ cat docs/openapi.md

OpenAPI 3.1OpenAPI 3.1

The generator turns the routes registered in the app into an OpenAPI 3.1.0 document.O gerador converte as rotas registradas no app em um documento OpenAPI 3.1.0.

GenerationGeração

generateOpenApiDocument(app, options) reads method, path and schema from each route. :id parameters become {id} and are listed as path parameters (typed by the params schema when present, else string); the properties of the query and headers schemas become query and header parameters. Each operation gets a stable, unique operationId and a tag from the first path segment (override with tags).

generateOpenApiDocument(app, options) lê method, path e schema de cada rota. Parâmetros :id viram {id} e entram como parâmetros de path (com o tipo do schema de params, se houver, senão string); as propriedades dos schemas de query e headers viram parâmetros de query e de header. Cada operação ganha um operationId estável e único e uma tag pelo primeiro segmento do path (troque com tags).

openapi.ts
import { createApp, createModule } from '@tupik/core';
import { generateOpenApiDocument } from '@tupik/openapi';

const routes = createModule('/api')
  .get('/health', { access: 'public', handler: (ctx) => ctx.json({ ok: true }) })
  .get('/users/:id', { access: 'authenticated', handler: (ctx) => ({ id: ctx.params.id }) });

const app = createApp({ authenticate: (ctx) => findUser(ctx.req.headers.get('authorization')) }).register(routes);

const document = generateOpenApiDocument(app, {
  info: { title: 'Tupik API', version: '1.0.0' },
  securitySchemes: { bearer: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } },
});
openapi.json
{
  "openapi": "3.1.0",
  "info": { "title": "Tupik API", "version": "1.0.0" },
  "paths": {
    "/api/health": {
      "get": {
        "operationId": "getApiHealth",
        "tags": ["api"],
        "x-access": "public",
        "security": [],
        "responses": { "200": { "description": "Successful response" } }
      }
    },
    "/api/users/{id}": {
      "get": {
        "operationId": "getApiUsersById",
        "tags": ["api"],
        "x-access": "authenticated",
        "security": [{ "bearer": [] }],
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Successful response" },
          "401": { "description": "Unauthorized", "content": { "application/problem+json": { "...": "code: UNAUTHORIZED" } } }
        }
      }
    }
  },
  "components": { "securitySchemes": { "bearer": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" } } }
}

schemaConverter

Standard Schema does not expose structure, so the JSON Schema conversion is pluggable. Without a converter, the generator uses the schema's jsonSchema property and throws when it is missing (Zod, Valibot), naming the route; onMissingConverter: 'warn' logs a warning and emits {} instead.

Standard Schema não expõe estrutura, então a conversão para JSON Schema é plugável. Sem conversor, o gerador usa a propriedade jsonSchema do schema e lança erro, com o nome da rota, quando ela falta (Zod, Valibot); onMissingConverter: 'warn' só avisa e emite {}.

converter.ts
import { z } from 'zod';
import { generateOpenApiDocument, type SchemaConverter } from '@tupik/openapi';

// Turns any Standard Schema into JSON Schema (here, with Zod 4).
const schemaConverter: SchemaConverter = (schema) =>
  schema instanceof z.ZodType ? z.toJSONSchema(schema) : {};

const document = generateOpenApiDocument(app, { schemaConverter });
import { z } from 'zod';
import { generateOpenApiDocument, type SchemaConverter } from '@tupik/openapi';

// Converte qualquer Standard Schema em JSON Schema (aqui, com Zod 4).
const schemaConverter: SchemaConverter = (schema) =>
  schema instanceof z.ZodType ? z.toJSONSchema(schema) : {};

const document = generateOpenApiDocument(app, { schemaConverter });

SecuritySegurança

Each operation takes its security from the route's access: [] on public routes, the scheme when a principal is required, [{}, { bearer: [] }] for auth: 'optional'. The scheme is securityScheme, or the only entry of securitySchemes. Operations also get x-access (public, authenticated, policy, owner), x-data-class on fields marked with classify, and one application/problem+json response per status with the code enum (declared errors plus the 401, 403 and 404 of the access rule). routeSecurity overrides a single operation. The audit page covers the CI checks built on the same metadata.

Cada operação tira o security do access da rota: [] em rota pública, o esquema quando exige principal, [{}, { bearer: [] }] com auth: 'optional'. O esquema é o securityScheme, ou a única entrada de securitySchemes. As operações também ganham x-access (public, authenticated, policy, owner), x-data-class nos campos marcados com classify e uma resposta application/problem+json por status com o enum de code (os errors declarados mais o 401, 403 e 404 da regra de acesso). O routeSecurity sobrescreve uma operação. A página de auditoria cobre as checagens de CI feitas com os mesmos metadados.

security.ts
const document = generateOpenApiDocument(app, {
  securitySchemes: {
    bearer: { type: 'http', scheme: 'bearer' },
    apiKey: { type: 'apiKey', in: 'header', name: 'x-api-key' },
  },
  securityScheme: 'bearer', // with two schemes, say which one access uses
  // override one route; undefined keeps what access gives
  routeSecurity: (route) => (route.path.startsWith('/partners') ? [{ apiKey: [] }] : undefined),
});
const document = generateOpenApiDocument(app, {
  securitySchemes: {
    bearer: { type: 'http', scheme: 'bearer' },
    apiKey: { type: 'apiKey', in: 'header', name: 'x-api-key' },
  },
  securityScheme: 'bearer', // com dois esquemas, diga qual o access usa
  // sobrescreve uma rota; undefined mantém o que o access dá
  routeSecurity: (route) => (route.path.startsWith('/partners') ? [{ apiKey: [] }] : undefined),
});

One contract, end to endUm contrato, de ponta a ponta

The route schema is the single source. At runtime, the body, query, params and headers schemas validate the request and failures answer 400 as problem details. On the way out, a schema.response cuts fields it does not declare ('strip', the default of createApp({ response }); 'validate' also runs the schema) and a secret field never leaves. The generator emits one OpenAPI response per status declared in schema.response, converted with the schemaConverter (204 has no body); an explicit 400 replaces the default validation error, and without a declared 2xx status the default 200 is kept. The typed client reads the 200 (or 201) schema output, so result.data has the same type.

O schema da rota é a fonte única. Em runtime, os schemas de body, query, params e headers validam a requisição e falhas respondem 400 como problem details. Na saída, um schema.response corta os campos que não declara ('strip', padrão do createApp({ response }); 'validate' também roda o schema) e um campo secret nunca sai. O gerador emite uma resposta OpenAPI por status declarado em schema.response, convertida pelo schemaConverter (204 não tem corpo); um 400 explícito substitui o erro de validação padrão, e sem status 2xx declarado o 200 padrão é mantido. O cliente tipado lê a saída do schema 200 (ou 201), então result.data tem o mesmo tipo.

contract.ts
import { z } from 'zod';

const User = z.object({ id: z.string(), name: z.string() });
const NewUser = z.object({ name: z.string() });

export const users = createModule('/users').post('/', {
  access: 'authenticated',
  // validates the body, cuts undeclared response fields, documents 201
  schema: { body: NewUser, response: { 201: User } },
  handler: (ctx) => ctx.status(201).json({ id: '1', name: ctx.body.name }),
});

// client side: result.data is { id: string; name: string }
const result = await createTypedClient<typeof app>({ baseUrl }).post('/users', { body: { name: 'Tupi' } });
import { z } from 'zod';

const User = z.object({ id: z.string(), name: z.string() });
const NewUser = z.object({ name: z.string() });

export const users = createModule('/users').post('/', {
  access: 'authenticated',
  // valida o body, corta campos não declarados da resposta, documenta 201
  schema: { body: NewUser, response: { 201: User } },
  handler: (ctx) => ctx.status(201).json({ id: '1', name: ctx.body.name }),
});

// no cliente: result.data é { id: string; name: string }
const result = await createTypedClient<typeof app>({ baseUrl }).post('/users', { body: { name: 'Tupi' } });

Contract driftDrift de contrato

tupik contract (also the tupik-contract bin) snapshots the runtime contract of a built app and diffs it against a baseline. A removed route, a removed response status, a newly required request schema or body field, or a route that now asks for more access fails CI as breaking. A new 4xx/5xx status or a new sensitive field in a response is a WARNING. The snapshot records routes, methods, declared statuses, which request schemas exist, the access kind and auth level, data classes and required body fields (when the body schema exposes a JSON Schema). Type-level shapes are erased at runtime and are not compared.

O tupik contract (e o bin tupik-contract) grava um snapshot do contrato em runtime de um app já compilado e compara com uma baseline. Rota removida, status de resposta removido, schema ou campo obrigatório novo na requisição, ou rota que passou a exigir mais acesso falham o CI como breaking. Um novo status 4xx/5xx ou um novo campo sensível na resposta sai como WARNING. O snapshot grava rotas, métodos, status declarados, quais schemas de requisição existem, o tipo de acesso e o nível de auth, classes de dado e campos obrigatórios do corpo (quando o schema expõe JSON Schema). Formas de tipo somem em runtime e não são comparadas.

terminal
$ npx tupik contract snapshot ./dist/app.js --out contract.json
snapshot written: contract.json (12 routes)

$ npx tupik contract check ./dist/app.js --baseline contract.json --fail-on-breaking
BREAKING route-removed DELETE /users/:id
BREAKING access-changed GET /users/:id (public/none -> authenticated/required)
exit code 1

Serving the documentServir o documento

docs-route.ts
const docs = createModule().get('/openapi.json', {
  access: 'public',
  handler: (ctx) => ctx.json(document),
});