Files
FlockPal/backend/src/docs/openapi.ts
T
blaisadmin c8eb9bc862
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 4m3s
Merge remote-tracking branch 'origin/main'
2026-10-09 23:42:16 -04:00

135 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { unassignedBirdMatchSchema, claimBirdSchema } from '../birdMembershipSchemas.js';
import { behaviorTypeSchema, behaviorOccurrenceSchema } from '../behaviorSchemas.js';
import { z } from 'zod';
import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV3, type RouteConfig } from '@asteasolutions/zod-to-openapi';
import { birdSchema, workspaceMemberSchema, workspaceRoleSchema, flockNoteSchema, locationSearchSchema,
weightSchema, vetVisitSchema, medicationSchema, medicationAdministrationSchema } from '../schemas.js';
import * as responses from './responses.js';
extendZodWithOpenApi(z);
const registry = new OpenAPIRegistry();
registry.registerComponent('securitySchemes', 'IntegrationToken', {
type: 'http', scheme: 'bearer', bearerFormat: 'flpt_…',
description: 'Paste your integration token, without the Bearer prefix. Create it in FlockPal Settings → Integration tokens.',
});
const models = Object.fromEntries(Object.entries(responses).map(([name, schema]) => [name, registry.register(name.replace('Response', ''), schema)]));
const error = registry.register('Error', z.object({
error: z.string(), code: z.string().optional(),
details: z.object({ formErrors: z.array(z.string()), fieldErrors: z.record(z.array(z.string())) }).optional(),
}));
const json = (schema: z.ZodTypeAny, example?: unknown) => ({ 'application/json': { schema, ...(example ? { example } : {}) } });
const errors: Record<number, string> = {
400: 'Invalid request.', 401: 'Missing, expired, revoked, or invalid integration token.',
402: 'Workspace is read-only: subscription must be active/trialing, or rescue verification approved.',
403: 'Insufficient token scope or workspace role.', 404: 'Resource not found in this workspace, or cannot be changed.',
409: 'Conflict: duplicate band/tag ID, duplicate weight date, or memorialized bird is read-only.',
500: 'Internal server error.', 502: 'Location provider request failed.', 503: 'Location search is not configured.',
};
type Endpoint = {
method: 'get' | 'post' | 'put' | 'delete'; path: string; summary: string; tag: string;
response?: z.ZodTypeAny; body?: z.ZodTypeAny; example?: unknown; query?: z.AnyZodObject;
description?: string; status?: number; errors?: number[]; roles?: string[];
};
const careRoles = ['owner', 'assistant', 'caregiver'];
function endpoint(config: Endpoint) {
const write = config.method !== 'get';
const params = Object.fromEntries([...config.path.matchAll(/\{(\w+)\}/g)].map((match) => [match[1], z.string().uuid()]));
const responseMap: RouteConfig['responses'] = {
[config.status ?? (config.method === 'delete' ? 204 : config.method === 'post' ? 201 : 200)]: {
description: config.method === 'delete' ? 'Deleted successfully. No response body.' : 'Success.',
...(config.response ? { content: json(config.response) } : {}),
},
429: { description: 'Rate limit exceeded. General limit: 300 requests per 15 minutes per IP; location search additionally allows 40 per 15 minutes.',
headers: { 'Retry-After': { schema: { type: 'string' }, description: 'Seconds until retry.' } },
content: { 'text/html': { schema: { type: 'string' } }, 'application/json': { schema: error } } },
};
for (const status of new Set([401, 500, ...(write ? [402, 403] : []), ...(config.body || config.query ? [400] : []), ...(config.errors ?? [])])) {
responseMap[status] = { description: errors[status], content: json(error) };
}
registry.registerPath({
method: config.method, path: config.path, summary: config.summary, tags: [config.tag],
operationId: `${config.method}_${config.path.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_/, '')}`,
description: [config.description, write ? `Requires a read_write token and an active writable workspace. Allowed roles: ${(config.roles ?? careRoles).join(', ')}.` : 'Accepts read_only or read_write integration tokens.'].filter(Boolean).join('\n\n'),
security: [{ IntegrationToken: [] }],
request: {
...(Object.keys(params).length ? { params: z.object(params) } : {}),
...(config.query ? { query: config.query } : {}),
...(config.body ? { body: { required: true, content: json(config.body, config.example) } } : {}),
},
responses: responseMap,
});
}
const one = (name: string, model: z.ZodTypeAny) => z.object({ [name]: model });
const many = (name: string, model: z.ZodTypeAny) => one(name, z.array(model));
endpoint({ method: 'get', path: '/workspace', summary: 'Get the token’s workspace', tag: 'Workspace', response: one('workspace', models.workspaceResponse) });
endpoint({ method: 'get', path: '/workspace/members', summary: 'List workspace members', tag: 'Workspace', response: many('members', models.memberResponse) });
endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: z.object({ member: models.memberResponse, invitation: z.object({ sent: z.boolean(), message: z.string() }) }), roles: ['owner', 'assistant'], description: 'Saves access and attempts to send a branded invitation email. Check invitation.sent for email submission status; access remains saved if email delivery fails.' });
endpoint({ method: 'put', path: '/workspace/members/{memberId}', summary: 'Change a member’s role', tag: 'Workspace', body: z.object({ role: workspaceRoleSchema }), response: one('member', models.memberResponse), roles: ['owner', 'assistant'], errors: [404], description: 'Only the billing owner can promote collaborators to owner. Additional protections apply to changing your own or the billing owner’s membership.' });
endpoint({ method: 'delete', path: '/workspace/members/{memberId}', summary: 'Remove a workspace member', tag: 'Workspace', roles: ['owner', 'assistant'], errors: [404], description: 'Protected memberships cannot be removed.' });
endpoint({ method: 'get', path: '/notes', summary: 'List flock notes', tag: 'Notes', response: many('notes', models.noteResponse) });
endpoint({ method: 'post', path: '/notes', summary: 'Create a flock note', tag: 'Notes', body: registry.register('NoteInput', flockNoteSchema), response: one('note', models.noteResponse), errors: [404], example: { body: 'Enjoyed a new enrichment activity today.' } });
endpoint({ method: 'delete', path: '/notes/{noteId}', summary: 'Delete a flock note', tag: 'Notes', errors: [404] });
endpoint({ method: 'get', path: '/locations/search', summary: 'Search for a location', tag: 'Locations', query: locationSearchSchema, response: many('results', models.locationResponse), errors: [502, 503], description: 'Search cities, regions, and countries. Requires 3–120 characters; returns up to three matches. Additional rate limit: 40 requests per 15 minutes per IP.' });
endpoint({ method: 'get', path: '/birds/unassigned-match', summary: 'Check for an unassigned bird by band ID', tag: 'Birds', query: unassignedBirdMatchSchema, response: z.object({ available: z.boolean() }), errors: [403], description: 'Requires owner, assistant, or caregiver role. Returns only availability, not profile details. Matching ignores case and surrounding whitespace; partial and unknown IDs do not match.' });
endpoint({ method: 'post', path: '/birds/claim', summary: 'Add an unassigned bird with its existing history', tag: 'Birds', body: claimBirdSchema, response: z.object({ bird: models.birdResponse, historyImported: z.literal(true) }), status: 200, errors: [409], description: 'Requires confirmHistory: true. Atomically assigns the existing bird to the current flock, preserving its ID, profile, photo, and history. Existing profile details are used. Birds already in a flock cannot be claimed.' });
endpoint({ method: 'get', path: '/birds', summary: 'List active and memorialized birds', tag: 'Birds', response: z.object({ birds: z.array(models.birdResponse), memorializedBirds: z.array(models.birdResponse) }) });
const birdInput = registry.register('BirdInput', birdSchema);
const birdDescription = 'motivators and demotivators each allow up to three non-empty lines. hatchDay takes precedence over the legacy dateOfBirth field. photoDataUrl accepts an image data URL or HTTP(S) URL; returned photo links may expire.';
endpoint({ method: 'post', path: '/birds', summary: 'Create a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [409], description: birdDescription, example: { name: 'Yoda', species: 'African grey' } });
endpoint({ method: 'put', path: '/birds/{birdId}', summary: 'Update a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [404, 409], description: `Submit the full editable profile: omitted optional fields may be cleared or reset. ${birdDescription}` });
endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', roles: ['owner', 'assistant'], tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' });
endpoint({ method: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] });
for (const resource of [
{ path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse },
{ path: 'vet-visits', single: 'vetVisit', plural: 'vetVisits', id: 'visitId', tag: 'Vet visits', input: vetVisitSchema, model: models.vetVisitResponse },
{ path: 'medications', single: 'medication', plural: 'medications', id: 'medicationId', tag: 'Medications', input: medicationSchema, model: models.medicationResponse },
]) {
const path = `/birds/{birdId}/${resource.path}`;
const body = registry.register(`${resource.single}Input`, resource.input);
const description = resource.path === 'medications' ? 'endDate must be on or after startDate. Supply 1–8 doseSchedule entries with unique application-defined keys; use a key as administrationSlot when recording a dose.' : undefined;
endpoint({ method: 'get', path, summary: `List ${resource.tag.toLowerCase()}`, tag: resource.tag, response: many(resource.plural, resource.model),
...(resource.path === 'weights' ? { query: z.object({ days: z.coerce.number().min(1).max(425).default(30) }), description: 'Lookback window in days; defaults to 30. Numeric values are clamped to 1–425. Returns an empty list when no matching records exist.' } : {}) });
endpoint({ method: 'post', path, summary: `Create ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409], description,
...(resource.path === 'weights' ? { example: { weightGrams: 425, recordedOn: '2026-09-27', notes: 'Morning weight' } } : {}) });
endpoint({ method: 'put', path: `${path}/{${resource.id}}`, summary: `Update ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409],
description: resource.path === 'weights' ? 'Only the three most recent weight records are editable. Older records return 404. One weight entry is allowed per bird per date.' : `Submit the full editable record; omitted optional fields may be reset. ${description ?? ''}` });
if (resource.path !== 'weights') endpoint({ method: 'delete', path: `${path}/{${resource.id}}`, summary: `Delete ${resource.single === 'vetVisit' ? 'a vet visit' : 'a medication'}`, tag: resource.tag, errors: [404, 409] });
}
endpoint({ method: 'get', path: '/birds/{birdId}/medication-administrations', summary: 'List medication administrations', tag: 'Medications', response: many('administrations', models.administrationResponse) });
endpoint({ method: 'post', path: '/birds/{birdId}/medications/{medicationId}/administrations', summary: 'Record or update a medication dose', tag: 'Medications', body: registry.register('AdministrationInput', medicationAdministrationSchema), response: one('administration', models.administrationResponse), errors: [404, 409], description: 'Creates or updates the record for this medication, date, and administrationSlot. Use a doseSchedule key for administrationSlot; it defaults to dose-1. Returns 201 for both creation and update.' });
const behaviorTypeResponse = registry.register('BehaviorType', z.object({
id: z.string().uuid(), name: z.string(), description: z.string().nullable(), createdAt: z.string().datetime(),
}));
const behaviorResponse = registry.register('BehaviorOccurrence', z.object({
id: z.string().uuid(), birdId: z.string().uuid(), behaviorTypeId: z.string().uuid(), behaviorName: z.string(),
occurredAt: z.string().datetime(), durationSeconds: z.number().nullable(), severity: z.number().int().min(1).max(5).nullable(),
notes: z.string().nullable(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
}));
endpoint({ method: 'get', path: '/birds/{birdId}/behavior-types', summary: 'List available behavior types', tag: 'Behavior Journal', response: many('behaviorTypes', behaviorTypeResponse), errors: [400, 404], description: 'Includes common behaviors, flock custom behaviors, and behaviors in this bird’s transferred history.' });
endpoint({ method: 'post', path: '/birds/{birdId}/behavior-types', summary: 'Create a reusable flock behavior type', tag: 'Behavior Journal', body: behaviorTypeSchema, response: one('behaviorType', behaviorTypeResponse), errors: [404, 409], description: 'Names are unique within the flock, ignoring case. An existing type is returned for a duplicate name.' });
endpoint({ method: 'get', path: '/birds/{birdId}/behaviors', summary: 'List behavior occurrences in a date range', tag: 'Behavior Journal', response: many('occurrences', behaviorResponse), query: z.object({ from: z.string().datetime({ offset: true }), to: z.string().datetime({ offset: true }), behaviorTypeId: z.string().uuid().optional() }), errors: [404], description: 'From is inclusive; to is exclusive. The range must be positive and at most 366 days. Send local date boundaries with their UTC offsets or converted to UTC. Results are newest first; individual events are never aggregated.' });
endpoint({ method: 'post', path: '/birds/{birdId}/behaviors', summary: 'Record a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409], description: 'Duration is optional and measured in seconds. Intensity is optional, from 1 to 5. Occurrence timestamps require a time zone offset.' });
endpoint({ method: 'put', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Edit a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409] });
endpoint({ method: 'delete', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Delete a behavior occurrence', tag: 'Behavior Journal', errors: [400, 404, 409] });
export const customerOpenApi = new OpenApiGeneratorV3(registry.definitions).generateDocument({
openapi: '3.0.3',
info: { title: 'FlockPal Customer API', version: '0.1.0', description: `Connect your flock to scripts and automation tools such as n8n.
### Getting started
1. Sign in to FlockPal and open Settings → Integration tokens.
2. Create a read_only token for reading, or read_write for changes. Copy the secret when shown; it is only displayed once.
3. Click Authorize and paste the token (without the Bearer prefix). Requests send Authorization: Bearer flpt_….
Tokens are scoped to the workspace where they were created and use the creating user’s current membership permissions. Create separate tokens for other workspaces. Expired or revoked tokens return 401.
Writes require read_write scope, an allowed role, and an active/trialing subscription or approved rescue workspace. Memorialized birds are read-only. Try it out sends real requests to this FlockPal instance, including changes and deletions; authorization is not persisted across reloads.
This reference covers customer integration endpoints. Manage tokens, authentication, billing, transfers, and memorialization in the FlockPal application. Photo URLs returned by the API can be used directly and may expire.
The general rate limit is 300 requests per 15 minutes per IP; location search also has a 40-request limit. On 429, wait for Retry-After before retrying.` },
servers: [{ url: '/api', description: 'This FlockPal instance' }],
tags: ['Workspace', 'Birds', 'Weights', 'Vet visits', 'Medications', 'Notes', 'Locations', 'Behavior Journal'].map((name) => ({ name })),
});