AGENT SKILL

saasaloy-api

Runbook for the api capability — Hono on Cloudflare Workers with a statically chained, RPC-typed route table. Use when adding, changing, or debugging routes in apps/api, building a typed client with hc<AppType>, wiring bindings (c.env), logging from a route (c.get("log")), running the Worker locally, testing a route with Vitest in Node (app.request), or deploying it. Covers the chained-route registration convention, the mount-relative path rule, explicit status codes, and how features add their own wrangler bindings.

License 许可
MIT
所属仓库
mimukit/saasaloy
最近更新
2026-11-13
Stars
★ 4
Forks
0

01 前言 Front Matter

name
saasaloy-api
description
Runbook for the api capability — Hono on Cloudflare Workers with a statically chained, RPC-typed route table. Use when adding, changing, or debugging routes in apps/api, building a typed client with hc<AppType>, wiring bindings (c.env), logging from a route (c.get("log")), running the Worker locally, testing a route with Vitest in Node (app.request), or deploying it. Covers the chained-route registration convention, the mount-relative path rule, explicit status codes, and how features add their own wrangler bindings.

03 SKILL.md 正文

api — Hono on Cloudflare Workers

apps/api is the backend spine, shared by web and admin. It's a Hono app running on Cloudflare Workers, built and served with Vite via @cloudflare/vite-plugin (so vite dev runs the real workerd runtime locally). Its defining convention is the statically chained route table: every mounted route is one .route() link in a single expression in src/index.ts, and the type of that expression is exported as AppType.

The chain is what makes the api typed end to end. A client built with hc<AppType> reads every path, request body, and per-status response shape straight off that type. A route discovered at build time by scanning a folder carries none of that, which is why registration is an edit to the chain rather than a file drop.

The entry, in shape

// src/index.ts
export const base: Hono<{ Bindings: Bindings; Variables: Variables }> = new Hono<{
  Bindings: Bindings;
  Variables: Variables;
}>()
  .use("*", cors({ /* … */ }))
  .use("*", requestCorrelation) // binds c.get("log") — see Logging, below
  .onError((err, c) => { /* every thrown error leaves as the error envelope */ });

const app = base.route("/health", health);

export type AppType = typeof app;
export default app;

src/index.ts is the Hono app and nothing else. The Worker entry is src/worker.ts, which is what wrangler.jsonc's main points at:

// src/worker.ts
import app from "./index";

export function defineWorker(config: WorkerConfig): ExportedHandler<never> {
  /* folds every handler set's queue and scheduled hooks into one object */
}

export const worker: ExportedHandler<never> = defineWorker({
  fetch: app.fetch,
  handlers: [],
});

export default worker;

Two bindings, and the split between them is the point:

  • base carries app-wide middleware and anything whose routes must stay opaque to the client, such as a catch-all auth handler. Its type annotation is written out on purpose. That freezes base at Hono<{ Bindings: Bindings; Variables: Variables }>, so mounting on it cannot widen AppType.
  • app is the typed chain. Everything a caller should see through hc goes here.

Keep every app-wide middleware as a link in base's chain, not as a base.use("*", …) statement underneath. A chained-route patch with exportName: "base" appends to that initializer, and Hono runs the handlers a request matches in registration order. Written as a statement, the middleware would register after the catch-all it is meant to wrap: /auth responses would come back with no CORS headers, and c.get("log") would be undefined inside that handler.

/auth and /admin/auth are the auth module's

The auth module mounts two catch-all forwards on base, one per Better Auth instance: authRoute at /auth for the client session and adminAuthRoute at /admin/auth for the admin session. The second sits under /admin on purpose, so one edge rule (WAF, Access, a log filter) covers the whole admin group. That makes /admin/auth/* a reserved prefix. Do not mount a route under it, and a middleware a project adds on /admin/* (an IP allowlist, an audit log, a session check) must skip /admin/auth/*, or the admin sign-in endpoint itself demands what it exists to hand out:

.use("/admin/*", async (c, next) => {
  if (c.req.path.startsWith("/admin/auth/")) return next();
  // ... the project's own check
  return next();
})

An /admin/* route that admin or another module registers on the typed chain (GET /admin/users) is a normal route and goes through such a middleware. See the saasaloy-auth skill for the two sessions and the x-auth-audience header.

Add a route

Two steps. The handler is still a file; only its registration changed.

1. Write src/routes/<feature>.ts as one chained expression, under a named export that matches the file:

// src/routes/widgets.ts  →  mounted at /widgets
import { Hono } from "hono";

export const widgets = new Hono()
  .get("/", (c) => c.json({ widgets: [] }, 200)) //         GET  /widgets
  .post("/", (c) => c.json({ created: true }, 201)) //      POST /widgets
  .get("/:id", (c) => c.json({ id: c.req.param("id") }, 200)); // GET /widgets/:id

Named, not default. The chained-route codemod writes a named import for the handler and refuses to wire a link whose binding resolves to a default import, so export default widgets leaves the route unmountable by patch.

2. Add the link to the chain in src/index.ts:

import { widgets } from "./routes/widgets";

const app = base.route("/health", health).route("/widgets", widgets);

A module does step 2 through a chained-route patch in its registry-item.json, not by hand:

{
  "kind": "chained-route",
  "file": "apps/api/src/index.ts",
  "exportName": "default",
  "path": "/widgets",
  "call": "widgets",
  "import": { "name": "widgets", "from": "./routes/widgets" }
}

saasaloy add appends the link and its import; saasaloy remove takes both back out, leaving the file byte-identical to its pre-add state. exportName: "default" resolves through export default app to the const app = … declarator, so the chain is edited and the export line is untouched. Use exportName: "base" for a handler that must stay out of AppType.

Keep the chain unbroken

The chain is a type, not a style. These two are not equivalent:

const widgets = new Hono().get("/", handler); // ✅ the type carries GET /widgets
const widgets = new Hono();
widgets.get("/", handler); // ❌ `typeof widgets` forgot the route

The second form still serves the request at runtime and still typechecks. It just hands the client an empty type, so api.widgets.$get() stops existing with no error anywhere in apps/api. The same holds in src/index.ts: a route mounted with a bare app.route(...) statement is invisible to AppType.

Pass the status code explicitly

c.json(body, 200) and c.json(body) differ on the client. hc keys the response type by status, so an omitted code leaves the caller with a looser type than the route actually has. Write the code every time, on the success path as well as the error path.

The one rule that trips people up: paths are relative to the mount

A route file is mounted at the path its chain link gives, so its internal paths are relative to that mount:

  • widgets.get("/") → GET /widgets ✅
  • widgets.get("/widgets") → GET /widgets/widgets ❌ (double prefix)

Name the Hono instance after the file (const widgets = new Hono()) so the file reads clearly. The folder is flat, one level of routes/*.ts. To nest, nest inside a sub-app (.route("/archived", archivedSub)), not with subdirectories.

The typed client

apps/api exposes one type-only export, @repo/api/client, which re-exports AppType and nothing else. package.json maps it under a types condition alone, so there is no runtime entry and the Worker never enters a browser bundle.

Each consumer owns its own three-line client:

import { hc } from "hono/client";
import type { AppType } from "@repo/api/client";

const api = hc<AppType>(import.meta.env.PUBLIC_API_URL ?? "http://localhost:4000");

const res = await api.health.$get();
const body = await res.json(); // { status: string }

A consumer needs hono and @repo/api in its package.json. A module that adds a caller adds both through package-json-dependency patches.

What a wide chain costs to typecheck

Measured 2026-08-28 on the reference dev box (6-core Intel Haswell container, Node 24.19.0, TypeScript 7.0.2), with 30 synthetic routes generated alongside health. Each synthetic route chains a GET /, a GET /:id, and a zValidator("json", …) POST /, so the numbers include zod inference rather than bare handlers.

What 1 route 31 routes
apps/api alone (tsc --noEmit) 0.59 s 1.02 s
Whole project (pnpm exec turbo run typecheck --force) 6.6 s 7.2 s

Roughly 14 ms per route, and adding a file that calls hc<AppType> against the 31-route chain cost nothing measurable on top (1.05 s). Reproduce it by generating the routes and their chain links in apps/api, then timing tsc --noEmit in that workspace.

So a single shared AppType is the right default, and it stays right well past the route count any of these projects has. If a chain ever does get expensive, the mitigation is a per-feature client: export a narrower type for one slice of the chain and point that feature's hc at it, rather than splitting the api. Reach for it on a measured number, not a hunch.

Bindings: use c.env, never process.env

Cloudflare bindings (D1, R2, KV, Queues, secrets) arrive on the Worker's env and are threaded through Hono context as c.env. Never reach for process.env — it doesn't exist on Workers.

const app = new Hono<{ Bindings: { DB: D1Database } }>();
app.get("/", (c) => c.env.DB.prepare("select 1").first());

Base api ships zero bindings. A capability or feature that needs one:

  1. Patches wrangler.jsonc to add its binding (via the jsonc-parser patch engine) — e.g. a d1_databases entry from database, an r2_buckets entry from storage.
  2. Extends the Bindings type where its code reads the binding.

Adding a binding is a structural edit to api's scaffold, the same class of edit as adding a link to the chain.

A nested binding is patched by the same wrangler-binding kind with a dotted bindingType. queues.producers, queues.consumers and triggers.crons all live under a parent object, so the patch names the full path; the engine creates the missing parent on add and takes it away again on remove, leaving the file byte-identical. There is no separate patch kind for it (ADR 0033).

The handler table: non-fetch exports register in src/worker.ts

A Worker exports more than fetch. A queue consumer is a queue export, a Cron Trigger is a scheduled export, and both are the Worker's, not any one route's. They register in the handlers array in src/worker.ts, which is a registration table for the same reason the route chain is one: a table yields a type, and a remove that takes the line back out.

A module that owns such an export ships a function returning a HandlerSet, then appends the call with a plugin-array patch:

{
  "kind": "plugin-array",
  "file": "apps/api/src/worker.ts",
  "exportName": "worker",
  "arrayProp": "handlers",
  "call": "cloudflareQueueHandlers",
  "import": { "name": "cloudflareQueueHandlers", "from": "@repo/queue/providers/cloudflare" },
}

Four rules hold here:

  • The import.from is the package export, not a scaffold alias. apps/api reaches into another workspace, so the specifier is @repo/queue/providers/cloudflare, resolved by the "./providers/*" entry in packages/queue's exports map. @queue is a descriptor-target alias the CLI uses to place files; it is not a TypeScript path and does not resolve at runtime.
  • HandlerSet is declared in worker.ts, not imported from a capability. api depends on no capability, and every capability that registers a handler depends on api. An import the other way would invert that.
  • defineWorker exports a hook only when a set declares it. Cloudflare reads a queue export as a promise that the Worker consumes a queue, so an empty stub would claim a consumer that does not exist.
  • The deploy tooling is not the registration path. A provider patches wrangler.jsonc and worker.ts directly. pnpm deploy:production hands that config to wrangler deploy as it is, and wrangler creates the resources the bindings name.

Logging: c.get("log"), never console.log

api depends on logger, so every project gets packages/logger and the logger-console provider from saasaloy add api — nothing to install, nothing to wire. src/index.ts mounts a correlation middleware right after CORS that binds a request id to a child logger and puts it on the context:

const requestId = c.req.header("cf-ray") ?? crypto.randomUUID();
c.set("log", createLogger(c.env).child({ requestId }));

Read it in a route with c.get("log"). Compose LoggerVariables into the sub-app's generic so it's typed — the same move database asks for with DbBindings, and for the same reason: a route can't import the entry's types without creating a cycle.

// src/routes/widgets.ts
import { Hono } from "hono";
import type { LoggerVariables } from "@repo/logger";

const widgets = new Hono<{ Variables: LoggerVariables }>().post("/", async (c) => {
  const log = c.get("log");
  log.info("creating widget", { plan: "pro" }); // → one line, carrying this request's requestId
  try {
    // …
  } catch (err) {
    log.error("widget creation failed", { err }); // `err` is serialized, not `{}`
    throw err;
  }
  return c.json({ ok: true }, 201);
});

export default widgets;

Every line from one request shares its requestId, so a single query in Workers Logs reconstructs the whole request. The message comes first and the structured data second — log.info(msg, fields?) — and the fields are what get indexed, so put values in fields rather than interpolating them into the message.

createLogger(c.env) (from @repo/logger) is the uncorrelated escape hatch for code that runs outside a request — a module-scope singleton, a scheduled handler, a queue consumer. Inside a route, prefer c.get("log"); a fresh createLogger there loses the request id.

LOG_LEVEL sets the threshold (default info), and wrangler.jsonc's observability block is what makes the output queryable in the dashboard — head_sampling_rate is its cost dial. The saasaloy-logger skill covers levels, redaction, reading logs, and writing another provider.

Request validation lives in @repo/validators

A route does not define its own input shape inline. The schema belongs in packages/validators (@repo/validators/<feature>), which the validators capability scaffolds, and the route wraps it with zValidator from @hono/zod-validator. c.req.valid("json") then carries the inferred type into the handler, with the target matching the one zValidator was given. Error bodies use the shared { error: { code, message } } envelope from @repo/validators/common. See the saasaloy-validators skill for the full convention.

Keep the three layers apart: request shapes in @repo/validators, database column shapes in packages/db, HTTP wiring here in apps/api.

On an admin route, adminGate from @repo/auth/server goes before the validator: .put("/:key", adminGate, validateValue, handler). Hono runs the handlers in the order they are listed, so a validator listed first answers a caller with no session with a 400 that names the rejected field. With the gate first, that caller gets a 401 whatever the body says. The handler still calls requireAdmin for the session value. The admin module's apps/api/src/routes/admin-gate.test.ts checks every /admin/* route for this; see the saasaloy-admin skill.

Errors: one envelope, including the ones you did not throw

base ends in an onError handler, and it is there because a route cannot cover every error it answers with. A zValidator failure hook returns the envelope for a body that parses and fails the schema. A body that does not parse never reaches the hook: Hono's json validator throws HTTPException(400, "Malformed JSON in request body") first, and an unhandled HTTPException answers as plain text. That is a second 400 shape behind one declared type, and hc publishes only the first — a caller branching on res.status === 400 and calling res.json() would throw.

The handler converts every HTTPException to { error: { code, message } } with the status it carried, and any other throw to a 500 with a fixed message (the real error goes to console.error, because it can carry a binding value or a query). A sub-app mounted with .route() inherits the handler, so a route module writes no error plumbing of its own.

apps/api writes the envelope out by hand instead of importing errorBody from @repo/validators/common, because validators declares dependsOn: ["api"] — the dependency runs one way. The two shapes are identical and each names the other. Change one, change the other.

A handler that returns a response is untouched by onError; only throws land there.

A miss has its own slot. base also ends in a notFound handler, and it answers the same envelope with status 404 and code not_found, so a caller parses one body shape for every failure this api can produce. A wrong method on a real path answers 404 too, not 405: Hono matches on the (method, path) pair, so POST /health matches nothing, and distinguishing the two would tell an unauthenticated caller which paths exist.

A feature module inherits that handler and must not register a second one. notFound, like onError, is a single slot: a sub-app mounted with .route() uses base's handler as long as it sets none of its own, and a notFound on your own sub-app takes over every miss under its mount for no gain. Nothing in a route module needs miss plumbing.

One mount is outside all of this, and it is worth knowing before you test a miss. A sub-app that mounts a catch-all answers every path under its prefix itself, so nothing under that prefix is ever a Hono miss and base's notFound never runs there. The auth module is the case in the base: it mounts .on(["GET", "POST"], "/*", ...) at /auth and again at /admin/auth, and hands each subtree to better-auth, so GET /auth/nope and GET /admin/auth/nope come back as a bare 404 with an empty body rather than the envelope. Every other mount answers the envelope on a miss.

Run it locally

pnpm --filter @repo/api dev       # vite dev → serves on workerd, hot-reloads routes
curl http://localhost:4000/health # → {"status":"ok"}

vite dev runs the actual Workers runtime, so local behavior matches the edge closely. Editing a route file is picked up on the next request with no restart.

Test it: Vitest in Node

pnpm test from the repo root runs the api's tests with Vitest, in Node rather than in workerd. Put a *.test.ts file beside the route, or under apps/api/test/, and call the app directly:

import { describe, expect, it } from "vitest";
import app from "../index";

describe("GET /health", () => {
  it("answers", async () => {
    const res = await app.request("/health", {}, {});
    expect(res.status).toBe(200);
  });
});

The third argument to app.request is c.env for that request, so the test decides every binding. apps/api/vitest.config.ts is what makes this work, and it is why Vitest never reads vite.config.ts, whose Cloudflare plugin would boot the whole Worker first:

  • cloudflare:workers resolves to test/cloudflare-workers.ts. Code that imports env from it at module scope, such as Better Auth's options in @repo/auth, loads unchanged. The stand-in's env holds the values in apps/api/.env, so run pnpm env:setup when a test fails on a missing key.
  • Every file in test/setup/ is a Vitest global setup, run once per pnpm test. A module drops one there rather than editing the config. The database driver ships test/setup/database.ts, which prepares a seeded test database; read the driver skill's "Route tests" section for testDatabase(), the helper a route test that touches the database uses.

Do not add a test script to apps/api/package.json: the root vitest.config.ts already runs this workspace, and a second script would run every file twice.

Ports are fixed, on purpose

Service Port Pinned in
apps/web (Astro) 3000 astro.config.mjs (server.port + vite.server.strictPort)
apps/admin (Vite SPA) 3001 vite.config.ts (server.port + strictPort), allowlisted in DEV_ORIGINS
apps/app (Vite SPA) 3002 vite.config.ts (server.port + strictPort), allowlisted in DEV_ORIGINS
apps/api (Worker) 4000 vite.config.ts (server.port + strictPort) and wrangler.jsonc (dev.port)

Frontends take 3xxx, backends 4xxx. These aren't cosmetic: DEV_ORIGINS in src/index.ts (and auth's trustedOrigins, and waitlist's PUBLIC_API_URL fallback) hardcode them as the keyless dev fallback, so a drifting port turns into a CORS rejection that looks like a code bug. strictPort makes a busy port fail loudly instead of quietly shifting to the next one.

Because wrangler.jsonc pins the same 4000, wrangler dev is a drop-in swap for the Vite loop.

CORS lives here, in the spine

src/index.ts mounts credentialed hono/cors on base for the whole app: the origin callback reflects the caller's origin only if it's in CORS_ORIGINS (comma-separated) or, when that's unset, in DEV_ORIGINS. It never answers *, because credentials: true and * are incompatible.

cors() sets no allowHeaders, so a preflight's Access-Control-Request-Headers is echoed back. That is what lets the admin app send x-auth-audience: admin with no CORS change. Keep it that way, or add x-auth-audience to the list if you ever pin allowHeaders.

Keep server.cors: false in vite.config.ts. Vite's own dev CORS middleware otherwise intercepts CORS in two ways that both mislead: it reflects Access-Control-Allow-Origin for every loopback origin (Vite 8's default server.cors.origin is a localhost regex), so a disallowed http://localhost:9999 looks allowed; and it terminates every OPTIONS preflight itself without emitting Access-Control-Allow-Credentials, which breaks any credentials: "include" fetch under vite dev while the identical request works under wrangler dev. With the middleware off, hono/cors is the only responder and both dev paths agree.

curl -i -H 'Origin: http://localhost:3000' http://localhost:4000/health # → header reflected
curl -i -H 'Origin: http://localhost:9999' http://localhost:4000/health # → no ACAO header

Deploy

pnpm deploy:production at the repository root deploys this Worker with every other one. Its deploy script is env-deploy api: it loads the api service's production values and the Cloudflare credentials from the value source, builds with them, and runs wrangler deploy --secrets-file, so the secrets land in the same Worker version as the code. A key the wrangler.jsonc vars block already sets stays a plain var and is not sent as a secret.

The api deploys first. saasaloy add api appends { service: "api", order: 10 } to DEPLOY_TARGETS in packages/tooling/src/targets.ts, so a frontend never goes live ahead of the route it calls. It also appends the api-health smoke check: GET /health must answer 200 with "ok" in the body. The check runs only once apps/api/wrangler.jsonc has a routes[] entry with custom_domain: true, and the dry run says so while it has none. pnpm deploy:production --only api deploys this Worker alone after the gates, and writes no deploy tag. Do not deploy it with pnpm --filter @repo/api run deploy, which skips the gates and the smoke checks. No deploy migrates the database unless you pass --migrate. See the saasaloy-deploy and saasaloy-env skills.

Conventions to honor

  • Register a route with a chained-route patch, not a file drop. The entry is edited on purpose, and saasaloy remove reverses the edit.
  • Build every sub-app as one unbroken chain. A statement-per-route file typechecks and serves correctly while handing the client an empty type.
  • Pass the status code to c.json on every path, success included.
  • One route file = one mounted prefix, named after the file, under a named export const. Keep the folder flat.
  • Internal paths are mount-relative (get("/") for the index of the mount).
  • Mount on base, not on the chain, when a handler must stay out of AppType.
  • c.env for bindings, never process.env.
  • c.get("log") for logging, never console.log — a bare console call is unlevelled and uncorrelated, and it bypasses redaction.
  • Inherit base's onError and notFound. A feature module registers neither of its own; a miss under a normally mounted sub-app already answers the 404 envelope. A mount with a catch-all route (auth at /auth and /admin/auth) answers its own misses and never reaches that handler.
  • /admin/auth/* is reserved for the admin auth instance. Mount nothing under it, and make any /admin/* middleware skip it.
  • A new binding patches wrangler.jsonc; it does not hand-edit another module's files.
  • Request validation belongs in @repo/validators, not in an inline schema in the route.
  • Test a route in Node with app.request(path, init, env). A setup step goes in test/setup/, not in vitest.config.ts.

Next

Run saasaloy-app to add the customer screens that call these routes, or saasaloy-admin for staff screens.

04 同仓库更多 Skills

mimukit
mimukit/saasaloy

saasaloy-subscription

Runbook for the subscription capability — provider-agnostic subscriptions in packages/subscription, with a plan file, a projection table, a billable-subject file, plan entitlements and per-provider modules. Use when adding a plan, adding a plan feature or a numeric limit, gating an API route with requireFeature or requireWithinLimit, reading the 402 it returns, working out why a subject resolves to the free plan, wiring a checkout or portal route, reading a SubscriptionError, choosing or switching SUBSCRIPTION_PROVIDER, registering a webhook in the vendor's dashboard, writing a third subscription provider, or upgrading a project that still has `billing` installed.

★ 4
mimukit
mimukit/saasaloy

saasaloy-notification

Runbook for the notification module, in-app notifications for apps/app. It owns the notifications and notification_opt_outs tables, notify() in apps/api/src/lib/notify.ts, the /notifications api routes, the bell in the app header, the sidebar badge, the /notifications page with Inbox and Preferences tabs, the notification config section, and the daily prune. Use when sending a notification from an api route, adding or changing a category, changing retention, debugging a badge or bell count that does not move, or removing the module.

★ 4
mimukit
mimukit/saasaloy

saasaloy-cms

Runbook for the cms module, the in-house CMS behind apps/admin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps/web and its 60-second cache. Use when adding a collection or a field, rendering a stored body, reusing the editor, renderer or media field from another module, moving the blog to another path, re-rendering live posts after a renderer upgrade or a STORAGE_PUBLIC_URL change, or working out why a published post is not live yet.

★ 4
mimukit
mimukit/saasaloy

saasaloy-beta

The beta module's own procedure.

★ 4
mimukit
mimukit/saasaloy

helper

暂无简介

★ 4
mimukit
mimukit/saasaloy

saasaloy-update

Runbook for an AI agent that updates this project to a newer Saasaloy CLI and newer module versions with saasaloy update. Use when the owner says "update saasaloy", "upgrade the CLI", "pull the latest modules", "update the base template", "work the merge plan", "clear the update notes", when saasaloy update or saasaloy outdated --check exits 3 or 2, when a merge plan or .saasaloy/merge-plan.md is handed to you, or when an adopted project takes its first update. Covers the CLI upgrade, the preview, --out, the file merges, the update notes and "Notes that may apply", --resolved and --done, a file deleted locally and --restore, a three-way or two-way base, an update that skips releases, --from, the verify commands, and the exit codes.

★ 4