# Project conventions ## Error handling Always use **defined error classes** for caught / expected exceptions — never `throw new Error('some_string')`. - Domain errors live in `packages/functions/src/errors.ts`. Each extends a Pikku core error (`BadRequestError`, `ConflictError`, `ForbiddenError`, `NotFoundError`, …) and is registered with `addError(...)` so it maps to the correct HTTP status and a stable client-facing code. - Raw `throw new Error(...)` is only acceptable for truly unexpected, programmer-error conditions that should surface as a 500. - Validation/contract failures (bad params, illegal state transitions, etc.) must be a defined error so callers can branch on the type and the client receives a meaningful status + message. ## Sessions (optional auth everywhere) `sessionCookieMiddleware` is registered globally (`addHTTPMiddleware('*', …)` in `wirings/middleware.ts`), so the session cookie is resolved on **every** route — including `auth: false` / `pikkuSessionlessFunc` endpoints. - In a sessionless function, read the optional session from the third arg: `func: async (services, input, { session }) => { const s = await session?.get(); … }`. `s` is `undefined` for anonymous callers and the `UserSession` (`{ userId, role }`) for logged-in ones. - This lets a public endpoint vary its response by viewer role (e.g. show admins more than anonymous visitors) without a separate authenticated route. - Use `pikkuFunc` (required session, third arg `{ session }` non-optional) only when the route must reject anonymous callers outright. ## Database changes (Pikku DB-first pipeline) Schema changes go **DB-first**, in this order — doing it code-first breaks the Pikku inspector / generated types: 1. Edit the SQL (`db/sqlite/*.sql`, `db/sqlite-seed.sql`). 2. Regenerate: `yarn db:reset && yarn db:migrate` (`pikku db migrate` refreshes `.pikku/db/schema.d.ts` and the generated zod at `.pikku/db/zod.gen.ts`, imported as `#pikku/db/zod.gen.js`). 3. Update backend function logic against the new types. 4. Regenerate the client SDK: `yarn workspace @project/functions pikku all`. 5. Update the frontend / consumers. This is a pre-production project — edit migrations in place rather than appending compatibility migrations.