From 60b66d127447e8a57eb16c8a1abea1bdc95ea1d8 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 08:28:14 -0600 Subject: [PATCH 1/9] =?UTF-8?q?Invalida=20todas=20las=20consultas=20de=20o?= =?UTF-8?q?RPC=20despu=C3=A9s=20de=20cualquier=20mutaci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prototipo: los hooks ya no listan qué entidades refrescar. --- apps/web/src/hooks/use-branches.ts | 29 +++--------------- apps/web/src/hooks/use-contacts.ts | 22 +++----------- apps/web/src/hooks/use-customers.ts | 32 +++----------------- apps/web/src/hooks/use-users.ts | 22 +++----------- apps/web/src/utils/orpc.ts | 46 ++++++++++++++++------------- oxlint.config.ts | 2 ++ 6 files changed, 44 insertions(+), 109 deletions(-) diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts index 5ce7d90..f1ef7cc 100644 --- a/apps/web/src/hooks/use-branches.ts +++ b/apps/web/src/hooks/use-branches.ts @@ -2,12 +2,7 @@ import type { AppRouterInputs, AppRouterOutputs, } from "@suni/api/routers/index"; -import { - keepPreviousData, - useMutation, - useQuery, - useQueryClient, -} from "@tanstack/react-query"; +import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query"; import type { skipToken } from "@tanstack/react-query"; import { toast } from "sonner"; @@ -27,13 +22,10 @@ export function useListBranches( } export function useCreateBranch() { - const queryClient = useQueryClient(); - return useMutation( orpc.branches.create.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Sucursal creada"); - await queryClient.invalidateQueries({ queryKey: orpc.branches.key() }); }, onError: (error) => toast.error(error.message), }) @@ -41,16 +33,10 @@ export function useCreateBranch() { } export function useUpdateBranch() { - const queryClient = useQueryClient(); - return useMutation( orpc.branches.update.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Sucursal actualizada"); - await Promise.all([ - queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), - queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), - ]); }, onError: (error) => toast.error(error.message), }) @@ -58,20 +44,13 @@ export function useUpdateBranch() { } export function useArchiveBranch() { - const queryClient = useQueryClient(); - return useMutation({ mutationFn: ({ id, archived, }: Pick & { archived: boolean }) => client.branches.setArchived({ id, archived }), - onSuccess: async (_data, { archived, name }) => { - // Contacts embed `branch.archived` to show the archived-branch label. - await Promise.all([ - queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), - queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), - ]); + onSuccess: (_data, { archived, name }) => { toast.success(archived ? "Sucursal archivada" : "Sucursal desarchivada", { description: `Se ${archived ? "archivó" : "desarchivó"} ${name} con éxito.`, }); diff --git a/apps/web/src/hooks/use-contacts.ts b/apps/web/src/hooks/use-contacts.ts index 0ffdb4c..d6c1456 100644 --- a/apps/web/src/hooks/use-contacts.ts +++ b/apps/web/src/hooks/use-contacts.ts @@ -2,12 +2,7 @@ import type { AppRouterInputs, AppRouterOutputs, } from "@suni/api/routers/index"; -import { - keepPreviousData, - useMutation, - useQuery, - useQueryClient, -} from "@tanstack/react-query"; +import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query"; import { toast } from "sonner"; import { client, orpc } from "@/utils/orpc"; @@ -24,13 +19,10 @@ export function useListContacts(params: AppRouterInputs["contacts"]["list"]) { } export function useCreateContact() { - const queryClient = useQueryClient(); - return useMutation( orpc.contacts.create.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Contacto creado"); - await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); }, onError: (error) => toast.error(error.message), }) @@ -38,13 +30,10 @@ export function useCreateContact() { } export function useUpdateContact() { - const queryClient = useQueryClient(); - return useMutation( orpc.contacts.update.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Contacto actualizado"); - await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); }, onError: (error) => toast.error(error.message), }) @@ -52,16 +41,13 @@ export function useUpdateContact() { } export function useArchiveContact() { - const queryClient = useQueryClient(); - return useMutation({ mutationFn: ({ id, archived, }: Pick & { archived: boolean }) => client.contacts.setArchived({ id, archived }), - onSuccess: async (_data, { archived, name }) => { - await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); + onSuccess: (_data, { archived, name }) => { toast.success(archived ? "Contacto archivado" : "Contacto desarchivado", { description: `Se ${archived ? "archivó" : "desarchivó"} a ${name} con éxito.`, }); diff --git a/apps/web/src/hooks/use-customers.ts b/apps/web/src/hooks/use-customers.ts index ccfb0a0..14ea834 100644 --- a/apps/web/src/hooks/use-customers.ts +++ b/apps/web/src/hooks/use-customers.ts @@ -2,12 +2,7 @@ import type { AppRouterInputs, AppRouterOutputs, } from "@suni/api/routers/index"; -import { - keepPreviousData, - useMutation, - useQuery, - useQueryClient, -} from "@tanstack/react-query"; +import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query"; import type { skipToken } from "@tanstack/react-query"; import { toast } from "sonner"; @@ -27,13 +22,10 @@ export function useListCustomers( } export function useCreateCustomer() { - const queryClient = useQueryClient(); - return useMutation( orpc.customers.create.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Cliente creado"); - await queryClient.invalidateQueries({ queryKey: orpc.customers.key() }); }, onError: (error) => toast.error(error.message), }) @@ -41,18 +33,10 @@ export function useCreateCustomer() { } export function useUpdateCustomer() { - const queryClient = useQueryClient(); - return useMutation( orpc.customers.update.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Cliente actualizado"); - // Branches and contacts embed `customer.name`. - await Promise.all([ - queryClient.invalidateQueries({ queryKey: orpc.customers.key() }), - queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), - queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), - ]); }, onError: (error) => toast.error(error.message), }) @@ -60,8 +44,6 @@ export function useUpdateCustomer() { } export function useArchiveCustomer() { - const queryClient = useQueryClient(); - return useMutation({ // `archived` is the state the user confirmed in the dialog, sent as-is so a // stale list cannot flip the customer the wrong way. @@ -70,13 +52,7 @@ export function useArchiveCustomer() { archived, }: Pick & { archived: boolean }) => client.customers.setArchived({ id, archived }), - onSuccess: async (_data, { archived, name }) => { - // Branches and contacts embed `customer.archived` to show the archived-customer label. - await Promise.all([ - queryClient.invalidateQueries({ queryKey: orpc.customers.key() }), - queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), - queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), - ]); + onSuccess: (_data, { archived, name }) => { toast.success(archived ? "Cliente archivado" : "Cliente desarchivado", { description: `Se ${archived ? "archivó" : "desarchivó"} a ${name} con éxito.`, }); diff --git a/apps/web/src/hooks/use-users.ts b/apps/web/src/hooks/use-users.ts index 94cf8de..7597dfa 100644 --- a/apps/web/src/hooks/use-users.ts +++ b/apps/web/src/hooks/use-users.ts @@ -2,12 +2,7 @@ import type { AppRouterInputs, AppRouterOutputs, } from "@suni/api/routers/index"; -import { - keepPreviousData, - useMutation, - useQuery, - useQueryClient, -} from "@tanstack/react-query"; +import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query"; import { toast } from "sonner"; import { authClient } from "@/lib/auth-client"; @@ -25,13 +20,10 @@ export function useListUsers(params: AppRouterInputs["users"]["list"]) { } export function useCreateUser() { - const queryClient = useQueryClient(); - return useMutation( orpc.users.create.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Usuario creado"); - await queryClient.invalidateQueries({ queryKey: orpc.users.key() }); }, onError: (error) => toast.error(error.message), }) @@ -39,13 +31,10 @@ export function useCreateUser() { } export function useUpdateUser() { - const queryClient = useQueryClient(); - return useMutation( orpc.users.update.mutationOptions({ - onSuccess: async () => { + onSuccess: () => { toast.success("Usuario actualizado"); - await queryClient.invalidateQueries({ queryKey: orpc.users.key() }); }, onError: (error) => toast.error(error.message), }) @@ -53,8 +42,6 @@ export function useUpdateUser() { } export function useChangeUserStatus() { - const queryClient = useQueryClient(); - return useMutation({ mutationFn: async (user: Pick) => { const { error } = user.banned @@ -68,8 +55,7 @@ export function useChangeUserStatus() { throw new Error(error.message ?? "Error desconocido"); } }, - onSuccess: async (_data, user) => { - await queryClient.invalidateQueries({ queryKey: orpc.users.key() }); + onSuccess: (_data, user) => { toast.success(user.banned ? "Usuario activado" : "Usuario suspendido", { description: `Se ${user.banned ? "activó" : "suspendió"} el usuario de ${user.name} con éxito.`, }); diff --git a/apps/web/src/utils/orpc.ts b/apps/web/src/utils/orpc.ts index 34c2dd9..8df9527 100644 --- a/apps/web/src/utils/orpc.ts +++ b/apps/web/src/utils/orpc.ts @@ -2,30 +2,11 @@ import { createORPCClient } from "@orpc/client"; import { RPCLink } from "@orpc/client/fetch"; import { createTanstackQueryUtils } from "@orpc/tanstack-query"; import type { AppRouterClient } from "@suni/api/routers/index"; -import { QueryCache, QueryClient } from "@tanstack/react-query"; +import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import { ENV } from "../env"; -function createQueryClient() { - return new QueryClient({ - queryCache: new QueryCache({ - onError: (error, query) => { - toast.error(`Error: ${error.message}`, { - action: { - label: "Reintentar", - onClick: () => { - query.invalidate(); - }, - }, - }); - }, - }), - }); -} - -export const queryClient = createQueryClient(); - function getServerUrl(url: string) { // SAFETY: server-side runtimes expose process.env on globalThis when SERVER_URL is available. const processEnv = ( @@ -56,3 +37,28 @@ const link = new RPCLink({ export const client: AppRouterClient = createORPCClient(link); export const orpc = createTanstackQueryUtils(client); + +function createQueryClient() { + const queryClient = new QueryClient({ + // Every successful mutation refetches the mounted queries, so no hook lists which entities it touches. + mutationCache: new MutationCache({ + onSuccess: () => queryClient.invalidateQueries({ queryKey: orpc.key() }), + }), + queryCache: new QueryCache({ + onError: (error, query) => { + toast.error(`Error: ${error.message}`, { + action: { + label: "Reintentar", + onClick: () => { + query.invalidate(); + }, + }, + }); + }, + }), + }); + + return queryClient; +} + +export const queryClient = createQueryClient(); diff --git a/oxlint.config.ts b/oxlint.config.ts index 2e12901..92b7d40 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -108,6 +108,8 @@ export default defineConfig({ ], rules: { "oxc/no-accumulating-spread": "error", + // The QueryClient in apps/web/src/utils/orpc.ts invalidates every oRPC query after any mutation. + "react-doctor/query-mutation-missing-invalidation": "off", "suni/require-seller-scope": "error", "suni/require-suppression-reason": "error", "no-restricted-imports": ["error", { paths: [REACT_HOOK_FORM_BAN] }], From 4be77eecdb05cbe2b277bf2a79575d3dd4ad1991 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 09:00:41 -0600 Subject: [PATCH 2/9] =?UTF-8?q?Actualiza=20los=20AGENTS.md=20con=20los=20m?= =?UTF-8?q?=C3=B3dulos=20y=20procedures=20actuales?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La raíz decía que no había módulos de dominio y omitía scopedProcedure. Los hooks ya no invalidan consultas a mano. --- AGENTS.md | 8 ++++---- apps/web/AGENTS.md | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8c6a6a5..97bc1c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,8 +3,8 @@ Suni manufactures cleaning and sanitation products for homes and businesses. This repo is Suni's internal operations system: inventory, orders, production, and related operations. The public company landing page will be added here later. - Users are staff from four areas: administration, production (plant), warehouse, and sales. -- Access will be role-based, so each area sees only its own part of the system. The per-area role system is not built yet. Today Better Auth's admin plugin gives each user the `user` or `admin` role: `protectedProcedure` checks for a session and `adminProcedure` also requires `admin`. Until per-area roles exist, ask how a new route or procedure should be scoped instead of adding ad hoc role checks. -- The domain modules are not built yet; today the code is the scaffold, auth, and admin user management. +- Access will be role-based, so each area sees only its own part of the system. The per-area role system is not built yet. Today Better Auth's admin plugin gives each user the `user` or `admin` role: `protectedProcedure` checks for a session, `scopedProcedure` adds `context.userId` and `context.admin` for handlers that branch on the role, and `adminProcedure` also requires `admin`. Non-admin sellers reach only their own customers and branches and the contacts under them. Until per-area roles exist, ask how a new route or procedure should be scoped instead of adding ad hoc role checks. +- Built so far: auth, admin user management, and the sales modules for customers, their branches, and their contacts. This is a TypeScript monorepo with a React/Vite web app, a Hono/oRPC server, and shared UI, API, auth, and database packages. @@ -51,8 +51,8 @@ A change is not done until it reaches every surface it touches. Before calling w - Drizzle table and enums. - Zod validation in `@suni/db/validation/*`, shared by the API and the form. -- oRPC procedure and its access scoping (`protectedProcedure` or `adminProcedure`, per the role note above). -- Hook with query invalidation. +- oRPC procedure and its access scoping (`protectedProcedure`, `scopedProcedure`, or `adminProcedure`, per the role note above). +- Hook in `apps/web/src/hooks/`. Every successful mutation refreshes all oRPC queries (see `apps/web/src/utils/orpc.ts`), so hooks never list query keys. - Route with loading, empty and error states. - Reverse actions: archive needs unarchive, and a way in needs a way out and a way to see it. - Nav items and actions hidden from users who cannot use them. diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index 573908e..fd90314 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -22,7 +22,7 @@ See [package.json](package.json) for available scripts. From the repo root, run ## Conventions - Import shared UI from `@suni/ui/components/*`; keep app-specific components in `src/components/`, grouped by feature (for example `src/components/users/`). -- Put oRPC queries and mutations in `src/hooks/` and have mutations await query invalidation. Load a single record for a route in its `loader`. +- Put oRPC queries and mutations in `src/hooks/`. Do not invalidate queries in a hook: the `QueryClient` in `src/utils/orpc.ts` refreshes every oRPC query after any successful mutation. Load a single record for a route in its `loader`. - Name hooks verb plus resource (`useListCustomers`, `useCreateCustomer`). Type data with `AppRouterInputs` and `AppRouterOutputs`, never by redeclaring shapes. - Build forms with TanStack Form (`@tanstack/react-form`) and the Zod schemas from `@suni/db/validation/*`. Do not use react-hook-form. - Use `Link` for buttons that only navigate. From b5844d3136970b0b28b98a1cc6c1f9209753e76d Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 09:08:28 -0600 Subject: [PATCH 3/9] Encuentra las rutas de verify-suni por su proceso y no por su URL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Desde un worktree, portless get devuelve la URL con prefijo y los servidores usan la URL sin prefijo, así que doctor fallaba y el chequeo de otra instancia corriendo podía no ver la del operador. --- .../skills/verify-suni/scripts/verify-suni.sh | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/.agents/skills/verify-suni/scripts/verify-suni.sh b/.agents/skills/verify-suni/scripts/verify-suni.sh index b62550d..b627e14 100755 --- a/.agents/skills/verify-suni/scripts/verify-suni.sh +++ b/.agents/skills/verify-suni/scripts/verify-suni.sh @@ -10,8 +10,8 @@ MAILPIT="http://localhost:8025" die() { echo "verify-suni: $*" >&2; exit 1; } ab() { agent-browser --session "$SESSION" "$@"; } -web_url() { pnpm --silent --dir "$ROOT" exec portless get suni; } -api_url() { pnpm --silent --dir "$ROOT" exec portless get api.suni; } +web_url() { app_url suni; } +api_url() { app_url api.suni; } root_pid() { [[ -f "$STATE/pid" ]] && cat "$STATE/pid"; } alive() { local p; p="$(root_pid)" && kill -0 "$p" 2>/dev/null; } # Turbo and bun start their own process groups, so ownership is the process tree under our pnpm. @@ -24,10 +24,30 @@ owns() { [[ -n "$1" ]] && alive && tree "$(root_pid)" | grep -qx "$1"; } run_id() { cat "$STATE/run_id" 2>/dev/null || die "no run started; run: $0 up"; } evidence_dir() { echo "$BASE/evidence/$(run_id)"; } -route_pid() { - local host="${1#https://}" +# " " for every portless route whose process runs `portless `. +# Matched by command, not URL: from a worktree, `portless get` adds a prefix the dev servers may not use. +app_routes() { + local url pid pnpm --silent --dir "$ROOT" exec portless list 2>/dev/null | - awk -v h="$host" '$1 == "https://" h { gsub(/[()]/, "", $NF); print $NF }' + awk '$2 == "->" { gsub(/[()]/, "", $NF); print $1, $NF }' | + while read -r url pid; do + ps -ww -o command= -p "$pid" 2>/dev/null | grep -q "portless[^ ]* $1 " && echo "$url $pid" + done +} +# The URL our run serves on; before launch, the URL portless would assign. +app_url() { + local url pid + while read -r url pid; do + owns "$pid" && { echo "$url"; return; } + done < <(app_routes "$1") + pnpm --silent --dir "$ROOT" exec portless get "$1" +} +# A pid serving that this run did not start, on any URL. +foreign_pid() { + local url pid + while read -r url pid; do + owns "$pid" || { echo "$pid"; return; } + done < <(app_routes "$1") } ready() { @@ -41,8 +61,8 @@ cmd_up() { return fi local foreign - foreign="$(route_pid "$(web_url)")" - [[ -z "$foreign" ]] || die "$(web_url) is served by pid $foreign, which this run did not start. Stop it or verify against it by hand; never double-drive it." + foreign="$(foreign_pid suni)" + [[ -z "$foreign" ]] || die "the Suni web app is served by pid $foreign, which this run did not start. Stop it or verify against it by hand; never double-drive it." command -v agent-browser >/dev/null || die "agent-browser missing: npm i -g agent-browser && agent-browser install" mkdir -p "$STATE" @@ -87,8 +107,8 @@ cmd_doctor() { local fail=0 check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; fail=1; fi; } check "dev server started by this run is alive (pid $(root_pid || echo none))" alive - check "web route $(web_url) is served by our process tree" 'owns "$(route_pid "$(web_url)")"' - check "api route $(api_url) is served by our process tree" 'owns "$(route_pid "$(api_url)")"' + check "web route $(web_url) is served by our process tree" '[[ -z "$(foreign_pid suni)" ]] && [[ -n "$(app_routes suni)" ]]' + check "api route $(api_url) is served by our process tree" '[[ -z "$(foreign_pid api.suni)" ]] && [[ -n "$(app_routes api.suni)" ]]' check "web answers and api /api/auth/ok answers" ready check "postgres and mailpit containers are healthy" \ '[[ "$(docker inspect -f "{{.State.Health.Status}}" suni-dev-postgres-1 suni-dev-mailpit-1 2>/dev/null | sort -u)" == "healthy" ]]' From 0f0c6691a09ff2d77e59a627e5d618b36555c596 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 09:04:04 -0600 Subject: [PATCH 4/9] Agrega lint con tipos para condiciones y aserciones innecesarias MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit oxlint-tsgolint queda fijado en 7.0.2006 para respetar la antigüedad mínima de paquetes. Corre en CI y en pre-push, y noUncheckedIndexedAccess se activa en la web. --- .github/workflows/check.yml | 17 ++++- apps/server/src/index.ts | 4 +- .../customers/contacts/contact-grid.tsx | 2 +- apps/web/tsconfig.json | 1 + docs/agents/code-quality.md | 3 +- lefthook.yml | 5 ++ oxlint-type-aware.config.ts | 23 ++++++ package.json | 4 +- packages/api/src/routers/index.ts | 2 +- packages/api/src/util/scope.ts | 2 +- pnpm-lock.yaml | 75 +++++++++++++++++-- 11 files changed, 124 insertions(+), 14 deletions(-) create mode 100644 oxlint-type-aware.config.ts diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 9a29370..6df7f48 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -30,6 +30,21 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm run check + type-aware-lint: + name: Type-aware lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm run check:type-aware + check-types: name: Check types runs-on: ubuntu-latest @@ -102,7 +117,7 @@ jobs: check: name: Check if: always() - needs: [lint-format, check-types, build, knip, migrations] + needs: [lint-format, type-aware-lint, check-types, build, knip, migrations] runs-on: ubuntu-latest steps: # Single required check for branch protection: fails unless every job succeeded. diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index e166de4..9bec60a 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -6,7 +6,6 @@ import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4"; import { appRouter } from "@suni/api/routers/index"; import { initLogger } from "evlog"; import { createAuthMiddleware } from "evlog/better-auth"; -import type { BetterAuthInstance } from "evlog/better-auth"; import { createFsDrain } from "evlog/fs"; import { evlog } from "evlog/hono"; import type { EvlogVariables } from "evlog/hono"; @@ -22,8 +21,7 @@ initLogger({ env: { service: "suni-server" }, }); -// SAFETY: auth is created by Better Auth and implements the evlog BetterAuthInstance contract. -const identifyUser = createAuthMiddleware(auth as BetterAuthInstance, { +const identifyUser = createAuthMiddleware(auth, { exclude: ["/api/auth/**"], maskEmail: true, }); diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx index f0d9e63..3a68799 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -90,7 +90,7 @@ export function ContactsList({ {visibleContacts.map((contact) => ( ))} diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4c1a002..11201af 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -2,6 +2,7 @@ "references": [{ "path": "../../packages/api" }], "compilerOptions": { "strict": true, + "noUncheckedIndexedAccess": true, "esModuleInterop": true, "jsx": "react-jsx", "target": "ESNext", diff --git a/docs/agents/code-quality.md b/docs/agents/code-quality.md index 746a750..a485f3b 100644 --- a/docs/agents/code-quality.md +++ b/docs/agents/code-quality.md @@ -3,7 +3,8 @@ The repository uses Ultracite with Oxlint and Oxfmt. Treat `oxlint.config.ts` and `oxfmt.config.ts` as the source of truth for enforced rules and formatting. - Run `pnpm run check` to check lint and formatting; run `pnpm run fix` to apply available fixes. -- Before committing code changes, run `pnpm run fix` and review the resulting diff. Before pushing, run `pnpm run check:changed` (lint and format, types for affected packages, knip). +- Before committing code changes, run `pnpm run fix` and review the resulting diff. Before pushing, run `pnpm run check:changed` (lint and format, type-aware lint, types for affected packages, knip). - For named functions, follow the declaration style required by `oxlint.config.ts`. Use arrow functions for callbacks. The config has scoped exceptions for web routes and components. - Name complex conditions, use early returns for error cases, and avoid nested ternaries. - Remove `console.log`, `debugger`, and `alert` from production code. +- `pnpm run check:type-aware` runs the type-aware rules (`no-unnecessary-condition`, `no-unnecessary-type-assertion`) with `oxlint-type-aware.config.ts`. It also runs in CI and on pre-push. diff --git a/lefthook.yml b/lefthook.yml index 1f1fbc4..20f58f1 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -5,3 +5,8 @@ pre-commit: run: pnpm exec oxfmt --no-error-on-unmatched-pattern {staged_files} && pnpm exec oxlint --fix --no-error-on-unmatched-pattern {staged_files} glob: "*.{js,jsx,ts,tsx,json,jsonc,css}" stage_fixed: true + +pre-push: + jobs: + - name: type-aware lint + run: pnpm run check:type-aware diff --git a/oxlint-type-aware.config.ts b/oxlint-type-aware.config.ts new file mode 100644 index 0000000..19e3e68 --- /dev/null +++ b/oxlint-type-aware.config.ts @@ -0,0 +1,23 @@ +import { defineConfig } from "oxlint"; + +// Type-aware rules need the TypeScript program, so they run apart from `pnpm run check` +// (`pnpm run check:type-aware`). The preset's other type-aware rules stay off on purpose. +export default defineConfig({ + categories: { correctness: "off" }, + plugins: ["typescript"], + options: { typeAware: true }, + ignorePatterns: [ + "**/node_modules/**", + "**/dist/**", + "apps/web/src/routeTree.gen.ts", + "packages/ui/**", + "packages/db/src/migrations/**", + ".agents/**", + ".claude/**", + "tools/**", + ], + rules: { + "typescript/no-unnecessary-condition": "error", + "typescript/no-unnecessary-type-assertion": "error", + }, +}); diff --git a/package.json b/package.json index c9afcef..613be5c 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,8 @@ "check": "ultracite check", "fix": "ultracite fix", "knip": "knip", - "check:changed": "ultracite check && turbo run check-types --affected && knip", + "check:type-aware": "oxlint -c oxlint-type-aware.config.ts", + "check:changed": "ultracite check && pnpm run check:type-aware && turbo run check-types --affected && knip", "prepare": "lefthook install" }, "devDependencies": { @@ -50,6 +51,7 @@ "oxfmt": "^0.70.0", "oxlint": "^1.85.0", "oxlint-plugin-react-doctor": "^0.9.14", + "oxlint-tsgolint": "7.0.2006", "portless": "^0.15.6", "turbo": "^2.11.2", "typescript": "catalog:", diff --git a/packages/api/src/routers/index.ts b/packages/api/src/routers/index.ts index 7dbffa0..7804daa 100644 --- a/packages/api/src/routers/index.ts +++ b/packages/api/src/routers/index.ts @@ -14,7 +14,7 @@ export const appRouter = { healthCheck: publicProcedure.handler(() => "OK"), privateData: protectedProcedure.handler(({ context }) => ({ message: "This is private", - user: context.session?.user, + user: context.session.user, })), users: usersRouter, customers: customersRouter, diff --git a/packages/api/src/util/scope.ts b/packages/api/src/util/scope.ts index 3e7c4e8..5b16a50 100644 --- a/packages/api/src/util/scope.ts +++ b/packages/api/src/util/scope.ts @@ -61,6 +61,6 @@ export function sellerRelation({ admin }: Pick) { export function withSeller( { admin }: Pick, row: T -) { +): T | (Omit & { seller: null }) { return admin ? row : { ...row, seller: null }; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ece20c4..f8ca71e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -263,10 +263,13 @@ importers: version: 0.70.0 oxlint: specifier: ^1.85.0 - version: 1.85.0 + version: 1.85.0(oxlint-tsgolint@7.0.2006) oxlint-plugin-react-doctor: specifier: ^0.9.14 version: 0.9.14 + oxlint-tsgolint: + specifier: 7.0.2006 + version: 7.0.2006 portless: specifier: ^0.15.6 version: 0.15.6 @@ -278,7 +281,7 @@ importers: version: 7.0.2 ultracite: specifier: 7.12.0 - version: 7.12.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(oxfmt@0.70.0)(oxlint@1.85.0)(prettier@3.9.8) + version: 7.12.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(oxfmt@0.70.0)(oxlint@1.85.0(oxlint-tsgolint@7.0.2006))(prettier@3.9.8) varlock: specifier: 'catalog:' version: 1.20.0 @@ -1740,6 +1743,36 @@ packages: cpu: [x64] os: [win32] + '@oxlint-tsgolint/darwin-arm64@7.0.2006': + resolution: {integrity: sha512-uc0MEHXZUDW23Zmo5X28eSNeSnP17jKnh9GiehpVZqhfy99ks8spyXT5Llar3tjDN7ppnQN0Qd9FK6WNkdD+fQ==} + cpu: [arm64] + os: [darwin] + + '@oxlint-tsgolint/darwin-x64@7.0.2006': + resolution: {integrity: sha512-+x1/pa3S3VMC9cif8XKTOCQUuqRT+wu1Ix+FK5svXa2xbXCuE7+4S0SfmuSnK/mk9AI5+xBxZFhILxmCPUZ1hA==} + cpu: [x64] + os: [darwin] + + '@oxlint-tsgolint/linux-arm64@7.0.2006': + resolution: {integrity: sha512-90v7HX8m54kHXn5DpjNEN18Fb7xwJMREe/wji3USyAf9pTMv7a3qZ3cPoLViIcIzxPLmkcYZIs1j1H3Z2gbVLA==} + cpu: [arm64] + os: [linux] + + '@oxlint-tsgolint/linux-x64@7.0.2006': + resolution: {integrity: sha512-/k0wsEqHiA5dWBJYuld3Vecv6bIhKCasxpho/aFkvh870Qox33MuTkKUGWIVm/njAxw7W4pu1a/Xfa3jwuKuPQ==} + cpu: [x64] + os: [linux] + + '@oxlint-tsgolint/win32-arm64@7.0.2006': + resolution: {integrity: sha512-CQT5sqcLZLNZSWLzUUEjQmp74UX8h1agp3ZJ8pfRktHbx6gfBa8a7CjrnRrZ9VXlwnXVkpw7m5KBO6y+S5MQRA==} + cpu: [arm64] + os: [win32] + + '@oxlint-tsgolint/win32-x64@7.0.2006': + resolution: {integrity: sha512-VZsGowXcp3vQNkjoGeVCOTf4aGrRpRk6bBJWhefnJVPr6z+dX+LKqqHfwaqnFvg66Q2iJpXqklRW38YO21ee+Q==} + cpu: [x64] + os: [win32] + '@oxlint/binding-android-arm-eabi@1.85.0': resolution: {integrity: sha512-q2KO/Zso9UT+OMn0NF9ywn4E4t0MI3yxiDhNyhsQ7DyQJrC4FhFE4TXOi4bktFnOWXTMds8qZSbpv2XwRaNOBg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -4712,6 +4745,10 @@ packages: resolution: {integrity: sha512-YGdwFmQXGQulT63SnVD9JI1hV2EwGnZHrgSlUMQaOkvnhYA200QwDeb7DfVT8UBt34lBvbkjtz8VRFJugHjsRQ==} engines: {node: ^20.19.0 || >=22.13.0} + oxlint-tsgolint@7.0.2006: + resolution: {integrity: sha512-5B3UtH71kycPHUC1kFEIffivEAs49SUmkJuHZOZnTY0NPj4legp0bcsCQucuLVNCoJzDucS68P2C4WIhP+LypQ==} + hasBin: true + oxlint@1.85.0: resolution: {integrity: sha512-bc26s97nuvPj1ViyPsqmKecVkUWFMEdtayO8MaQ6oiLfs1pj94cQlZZhrh4BPNlr9HQosjhIlwgZKsfcwmcNgg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -6778,6 +6815,24 @@ snapshots: '@oxfmt/binding-win32-x64-msvc@0.70.0': optional: true + '@oxlint-tsgolint/darwin-arm64@7.0.2006': + optional: true + + '@oxlint-tsgolint/darwin-x64@7.0.2006': + optional: true + + '@oxlint-tsgolint/linux-arm64@7.0.2006': + optional: true + + '@oxlint-tsgolint/linux-x64@7.0.2006': + optional: true + + '@oxlint-tsgolint/win32-arm64@7.0.2006': + optional: true + + '@oxlint-tsgolint/win32-x64@7.0.2006': + optional: true + '@oxlint/binding-android-arm-eabi@1.85.0': optional: true @@ -9467,7 +9522,16 @@ snapshots: lightningcss: 1.33.0 oxc-parser: 0.148.0 - oxlint@1.85.0: + oxlint-tsgolint@7.0.2006: + optionalDependencies: + '@oxlint-tsgolint/darwin-arm64': 7.0.2006 + '@oxlint-tsgolint/darwin-x64': 7.0.2006 + '@oxlint-tsgolint/linux-arm64': 7.0.2006 + '@oxlint-tsgolint/linux-x64': 7.0.2006 + '@oxlint-tsgolint/win32-arm64': 7.0.2006 + '@oxlint-tsgolint/win32-x64': 7.0.2006 + + oxlint@1.85.0(oxlint-tsgolint@7.0.2006): optionalDependencies: '@oxlint/binding-android-arm-eabi': 1.85.0 '@oxlint/binding-android-arm64': 1.85.0 @@ -9488,6 +9552,7 @@ snapshots: '@oxlint/binding-win32-arm64-msvc': 1.85.0 '@oxlint/binding-win32-ia32-msvc': 1.85.0 '@oxlint/binding-win32-x64-msvc': 1.85.0 + oxlint-tsgolint: 7.0.2006 p-limit@2.3.0: dependencies: @@ -10314,7 +10379,7 @@ snapshots: ufo@1.6.4: {} - ultracite@7.12.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(oxfmt@0.70.0)(oxlint@1.85.0)(prettier@3.9.8): + ultracite@7.12.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(oxfmt@0.70.0)(oxlint@1.85.0(oxlint-tsgolint@7.0.2006))(prettier@3.9.8): dependencies: '@clack/prompts': 1.8.1 cli-truncate: 6.1.1 @@ -10336,7 +10401,7 @@ snapshots: optionalDependencies: eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) oxfmt: 0.70.0 - oxlint: 1.85.0 + oxlint: 1.85.0(oxlint-tsgolint@7.0.2006) prettier: 3.9.8 unbash@6.0.3: {} From e5c2a5177543bf7ef12da5a3edeee8cf20a66c42 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 09:05:29 -0600 Subject: [PATCH 5/9] =?UTF-8?q?Activa=20React=20Compiler=20en=20la=20web?= =?UTF-8?q?=20y=20proh=C3=ADbe=20memoizar=20a=20mano?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit useMemo, useCallback y memo quedan prohibidos en la web. React Compiler omite UsersDataTable por useReactTable, así que sus columnas pasan a nivel de módulo: antes se recreaban en cada render y flexRender remontaba las celdas, cerrando ChangeUserStatusDialog al refrescar la lista. El id del usuario actual llega a las celdas por el meta de la tabla. --- apps/web/package.json | 4 + .../components/customers/branches/grid.tsx | 7 +- .../customers/contacts/contact-grid.tsx | 7 +- .../customers/new-entity-button.tsx | 22 +-- apps/web/src/components/users/users-table.tsx | 142 ++++++++++-------- apps/web/src/routes/_auth/customers/index.tsx | 6 +- apps/web/vite.config.ts | 4 +- oxlint.config.ts | 52 ++++--- pnpm-lock.yaml | 85 ++++++++++- 9 files changed, 212 insertions(+), 117 deletions(-) diff --git a/apps/web/package.json b/apps/web/package.json index 13ef6c9..90f5aa1 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -32,11 +32,15 @@ "zod": "catalog:" }, "devDependencies": { + "@babel/core": "7.29.7", + "@rolldown/plugin-babel": "0.2.4", "@tanstack/router-plugin": "^1.168.35", + "@types/babel__core": "7.20.5", "@types/node": "^26.4.1", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@vitejs/plugin-react": "^6.1.1", + "babel-plugin-react-compiler": "1.0.0", "typescript": "catalog:", "vite": "^8.2.2" } diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx index 7b6d707..332e8d5 100644 --- a/apps/web/src/components/customers/branches/grid.tsx +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -1,7 +1,7 @@ import { skipToken } from "@tanstack/react-query"; import { Building2 } from "lucide-react"; import type { ReactNode } from "react"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; @@ -52,10 +52,7 @@ export function BranchesList({ customerId ? skipToken : { status: "all" } ); - const rowsByStatus = useMemo( - () => byStatus(matchingName(query.data ?? [], filters.name)), - [query.data, filters.name] - ); + const rowsByStatus = byStatus(matchingName(query.data ?? [], filters.name)); const visibleBranches = rowsByStatus[filters.status]; diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx index 3a68799..8ce3449 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -1,6 +1,6 @@ import { Users } from "lucide-react"; import type { ReactNode } from "react"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; @@ -45,10 +45,7 @@ export function ContactsList({ branchId, }); - const rowsByStatus = useMemo( - () => byStatus(matchingName(query.data ?? [], filters.name)), - [query.data, filters.name] - ); + const rowsByStatus = byStatus(matchingName(query.data ?? [], filters.name)); const visibleContacts = rowsByStatus[filters.status]; diff --git a/apps/web/src/components/customers/new-entity-button.tsx b/apps/web/src/components/customers/new-entity-button.tsx index 906cfaf..6144b28 100644 --- a/apps/web/src/components/customers/new-entity-button.tsx +++ b/apps/web/src/components/customers/new-entity-button.tsx @@ -10,7 +10,7 @@ import { import { ReactSelect } from "@suni/ui/components/react-select"; import { skipToken } from "@tanstack/react-query"; import { Plus } from "lucide-react"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { BranchFormDialog } from "@/components/customers/branches/branch-form-dialog"; import { ContactFormDialog } from "@/components/customers/contacts/contact-form-dialog"; @@ -28,13 +28,9 @@ function CustomerPicker({ value, onValueChange }: PickerProps) { status: "active", }); - const options = useMemo( - () => - customers - .toSorted(byName) - .map((customer) => ({ value: customer.id, label: customer.name })), - [customers] - ); + const options = customers + .toSorted(byName) + .map((customer) => ({ value: customer.id, label: customer.name })); return ( - branches - .toSorted(byName) - .map((branch) => ({ value: branch.id, label: branch.name })), - [branches] - ); + const options = branches + .toSorted(byName) + .map((branch) => ({ value: branch.id, label: branch.name })); return ( { + currentUserId?: string; + } +} + const columnHelper = createColumnHelper(); function RoleBadge({ role }: { role: string | null }) { @@ -72,7 +79,7 @@ function ImpersonateUserButton({ currentUserId, }: { user: UserRow; - currentUserId: string; + currentUserId?: string; }) { const impersonate = useImpersonateUser(); // Better Auth rejects impersonating admins by default. @@ -101,68 +108,72 @@ function ImpersonateUserButton({ ); } -function createColumns(currentUserId: string) { - return [ - columnHelper.accessor("name", { - header: "Usuario", - cell: (info) => ( - - {info.getValue()} - {info.row.original.id === currentUserId && ( - - Tú - - )} - - ), - }), - columnHelper.accessor("email", { - header: "Correo", - cell: (info) => ( - {info.getValue()} - ), - }), - columnHelper.accessor("role", { - header: "Rol", - cell: (info) => , - }), - columnHelper.accessor("banned", { - id: "status", - header: "Estado", - cell: (info) => , - }), - columnHelper.display({ - id: "actions", - cell: ({ row }) => { - const user = row.original; +// Module-level so cell renderers keep one identity: flexRender mounts them as +// component types, and a new identity per render would remount the row actions +// (and close an open ChangeUserStatusDialog). Per-render values go through `meta`. +const columns = [ + columnHelper.accessor("name", { + header: "Usuario", + cell: (info) => ( + + {info.getValue()} + {info.row.original.id === info.table.options.meta?.currentUserId && ( + + Tú + + )} + + ), + }), + columnHelper.accessor("email", { + header: "Correo", + cell: (info) => ( + {info.getValue()} + ), + }), + columnHelper.accessor("role", { + header: "Rol", + cell: (info) => , + }), + columnHelper.accessor("banned", { + id: "status", + header: "Estado", + cell: (info) => , + }), + columnHelper.display({ + id: "actions", + cell: ({ row, table }) => { + const user = row.original; - return ( -
- - - - - -
- ); - }, - }), - ]; -} + return ( +
+ + + + + +
+ ); + }, + }), +]; // Referencia estable para que TanStack Table no trate cada render como datos nuevos. const EMPTY: UserRow[] = []; @@ -201,8 +212,6 @@ export function UsersDataTable({ currentUserId }: UsersDataTableProps) { const total = users.data?.total ?? 0; const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize)); - const columns = useMemo(() => createColumns(currentUserId), [currentUserId]); - // TanStack Table devuelve funciones no memoizables; React Compiler ya omite // este componente y no pasamos `table` a hijos memoizados. // oxlint-disable-next-line react/incompatible-library @@ -210,6 +219,7 @@ export function UsersDataTable({ currentUserId }: UsersDataTableProps) { data: users.data?.items ?? EMPTY, columns, manualPagination: true, + meta: { currentUserId }, pageCount, onPaginationChange: setPagination, getCoreRowModel: getCoreRowModel(), diff --git a/apps/web/src/routes/_auth/customers/index.tsx b/apps/web/src/routes/_auth/customers/index.tsx index a2b477a..a074adb 100644 --- a/apps/web/src/routes/_auth/customers/index.tsx +++ b/apps/web/src/routes/_auth/customers/index.tsx @@ -9,7 +9,6 @@ import { stripSearchParams, } from "@tanstack/react-router"; import { ContactRound, Plus } from "lucide-react"; -import { useMemo } from "react"; import { z } from "zod"; import CustomerFilters from "@/components/customers/customer-filters"; @@ -53,10 +52,7 @@ function RouteComponent() { isPending, } = useListCustomers({ status: "all" }); - const rowsByStatus = useMemo( - () => byStatus(matchingName(customers ?? [], name)), - [customers, name] - ); + const rowsByStatus = byStatus(matchingName(customers ?? [], name)); const inTab = rowsByStatus[status]; diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 3dad83b..4dc2eb7 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -1,7 +1,8 @@ +import babel from "@rolldown/plugin-babel"; import tailwindcss from "@tailwindcss/vite"; import { tanstackRouter } from "@tanstack/router-plugin/vite"; import { varlockVitePlugin } from "@varlock/vite-integration"; -import react from "@vitejs/plugin-react"; +import react, { reactCompilerPreset } from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ @@ -19,5 +20,6 @@ export default defineConfig({ autoCodeSplitting: true, }), react(), + babel({ presets: [reactCompilerPreset()] }), ], }); diff --git a/oxlint.config.ts b/oxlint.config.ts index 92b7d40..42816cb 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -11,6 +11,31 @@ const REACT_HOOK_FORM_BAN = { message: "Use TanStack Form with the Zod schemas from @suni/db/validation/*.", }; +const WEB_RESTRICTED_PATTERNS = [ + { + group: ["@suni/auth", "@suni/auth/**"], + message: + "@suni/auth is the server package. Use the client in @/lib/auth-client.", + }, + { + group: [ + "@suni/db", + "@suni/db/**", + "!@suni/db/validation/*", + "!@suni/db/schema/*-enums", + ], + message: + "The web app must not pull table definitions or the DB client. Import shared rules from @suni/db/validation/* or enums from @suni/db/schema/*-enums.", + }, +]; + +const MANUAL_MEMO_BAN = { + name: "react", + importNames: ["useMemo", "useCallback", "memo"], + message: + "The React Compiler memoizes components in apps/web. Write plain code; do not memoize by hand.", +}; + const jsPlugins = selectJsPlugins(["github", "sonarjs", "react-doctor"]); export default defineConfig({ @@ -42,24 +67,8 @@ export default defineConfig({ "no-restricted-imports": [ "error", { - paths: [REACT_HOOK_FORM_BAN], - patterns: [ - { - group: ["@suni/auth", "@suni/auth/**"], - message: - "@suni/auth is the server package. Use the client in @/lib/auth-client.", - }, - { - group: [ - "@suni/db", - "@suni/db/**", - "!@suni/db/validation/*", - "!@suni/db/schema/*-enums", - ], - message: - "The web app must not pull table definitions or the DB client. Import shared rules from @suni/db/validation/* or enums from @suni/db/schema/*-enums.", - }, - ], + paths: [REACT_HOOK_FORM_BAN, MANUAL_MEMO_BAN], + patterns: WEB_RESTRICTED_PATTERNS, }, ], }, @@ -103,6 +112,13 @@ export default defineConfig({ files: ["apps/web/src/components/**/*.{ts,tsx}"], rules: { "func-style": "off", + "no-restricted-imports": [ + "error", + { + paths: [REACT_HOOK_FORM_BAN, MANUAL_MEMO_BAN], + patterns: WEB_RESTRICTED_PATTERNS, + }, + ], }, }, ], diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f8ca71e..460b368 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -389,9 +389,18 @@ importers: specifier: 'catalog:' version: 4.6.5 devDependencies: + '@babel/core': + specifier: 7.29.7 + version: 7.29.7(supports-color@7.2.0) + '@rolldown/plugin-babel': + specifier: 0.2.4 + version: 0.2.4(@babel/core@7.29.7(supports-color@7.2.0))(@babel/runtime@7.29.7)(rolldown@1.2.9)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1)) '@tanstack/router-plugin': specifier: ^1.168.35 version: 1.168.40(@tanstack/react-router@1.170.38(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(rolldown@1.2.9)(supports-color@7.2.0)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1)) + '@types/babel__core': + specifier: 7.20.5 + version: 7.20.5 '@types/node': specifier: ^26.4.1 version: 26.6.2 @@ -403,7 +412,10 @@ importers: version: 19.3.0(@types/react@19.3.0) '@vitejs/plugin-react': specifier: ^6.1.1 - version: 6.1.1(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1)) + version: 6.1.1(@rolldown/plugin-babel@0.2.4(@babel/core@7.29.7(supports-color@7.2.0))(@babel/runtime@7.29.7)(rolldown@1.2.9)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1)) + babel-plugin-react-compiler: + specifier: 1.0.0 + version: 1.0.0 typescript: specifier: 'catalog:' version: 7.0.2 @@ -2006,6 +2018,23 @@ packages: cpu: [x64] os: [win32] + '@rolldown/plugin-babel@0.2.4': + resolution: {integrity: sha512-ygmm2j/mN+aCvstHo0x3IOu4uc6LqXT9SJ3q4kpfG/+Yhfz0B+E47FITcC0FljZADwUFARP6E2kiE+Lc26D8wg==} + engines: {node: '>=22.12.0 || ^24.0.0'} + peerDependencies: + '@babel/core': ^7.29.0 || ^8.0.0-rc.1 + '@babel/plugin-transform-runtime': ^7.29.0 || ^8.0.0-rc.1 + '@babel/runtime': ^7.27.0 || ^8.0.0-rc.1 + rolldown: ^1.0.0-rc.5 + vite: ^8.0.0 + peerDependenciesMeta: + '@babel/plugin-transform-runtime': + optional: true + '@babel/runtime': + optional: true + vite: + optional: true + '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} @@ -2282,6 +2311,18 @@ packages: '@tybys/wasm-util@0.10.4': resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==} + '@types/babel__core@7.20.5': + resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} + + '@types/babel__generator@7.27.0': + resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==} + + '@types/babel__template@7.4.4': + resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==} + + '@types/babel__traverse@7.28.0': + resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} + '@types/bun@1.4.2': resolution: {integrity: sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ==} @@ -2809,6 +2850,9 @@ packages: resolution: {integrity: sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==} engines: {node: '>=10', npm: '>=6'} + babel-plugin-react-compiler@1.0.0: + resolution: {integrity: sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw==} + balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} @@ -6949,6 +6993,15 @@ snapshots: '@rolldown/binding-win32-x64-msvc@1.2.9': optional: true + '@rolldown/plugin-babel@0.2.4(@babel/core@7.29.7(supports-color@7.2.0))(@babel/runtime@7.29.7)(rolldown@1.2.9)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1))': + dependencies: + '@babel/core': 7.29.7(supports-color@7.2.0) + picomatch: 4.0.7 + rolldown: 1.2.9 + optionalDependencies: + '@babel/runtime': 7.29.7 + vite: 8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1) + '@rolldown/pluginutils@1.0.1': {} '@rtsao/scc@1.1.0': {} @@ -7194,6 +7247,27 @@ snapshots: tslib: 2.8.1 optional: true + '@types/babel__core@7.20.5': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + '@types/babel__generator': 7.27.0 + '@types/babel__template': 7.4.4 + '@types/babel__traverse': 7.28.0 + + '@types/babel__generator@7.27.0': + dependencies: + '@babel/types': 7.29.8 + + '@types/babel__template@7.4.4': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + + '@types/babel__traverse@7.28.0': + dependencies: + '@babel/types': 7.29.8 + '@types/bun@1.4.2': dependencies: bun-types: 1.4.2 @@ -7444,10 +7518,13 @@ snapshots: varlock: 1.20.0 vite: 8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1) - '@vitejs/plugin-react@6.1.1(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1))': + '@vitejs/plugin-react@6.1.1(@rolldown/plugin-babel@0.2.4(@babel/core@7.29.7(supports-color@7.2.0))(@babel/runtime@7.29.7)(rolldown@1.2.9)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1))': dependencies: '@rolldown/pluginutils': 1.0.1 vite: 8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1) + optionalDependencies: + '@rolldown/plugin-babel': 0.2.4(@babel/core@7.29.7(supports-color@7.2.0))(@babel/runtime@7.29.7)(rolldown@1.2.9)(vite@8.3.0(@types/node@26.6.2)(jiti@2.7.0)(yaml@2.9.1)) + babel-plugin-react-compiler: 1.0.0 '@yuku-codegen/binding-android-arm64@0.10.2': optional: true @@ -7661,6 +7738,10 @@ snapshots: cosmiconfig: 7.1.0 resolve: 1.22.13 + babel-plugin-react-compiler@1.0.0: + dependencies: + '@babel/types': 7.29.8 + balanced-match@1.0.2: {} balanced-match@4.0.4: {} From 5d63326c159c800cfc61f7644ac05091238d1dd5 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 09:06:58 -0600 Subject: [PATCH 6/9] =?UTF-8?q?Agrega=20reglas=20de=20lint=20propias=20par?= =?UTF-8?q?a=20las=20correcciones=20repetidas=20en=20revisi=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit prefer-router-types exige AppRouterInputs y AppRouterOutputs en lugar de ReturnType o Parameters sobre los hooks y el cliente del router. require-string-bound pide un límite en cada z.string() y no-nullable-text prohíbe campos y columnas de texto nulos. Los componentes de la web ya no importan zod, a ninguna profundidad de subruta, y los ids de las validaciones tienen tope. --- .../components/customers/customer-filters.tsx | 8 +- apps/web/src/components/sign-in-form.tsx | 4 +- docs/agents/code-quality.md | 1 + oxlint.config.ts | 37 +++++- packages/db/src/validation/branches.ts | 4 +- packages/db/src/validation/contacts.ts | 6 +- packages/db/src/validation/ids.ts | 2 + tools/oxlint/suni/index.ts | 6 + tools/oxlint/suni/rules/no-nullable-text.ts | 49 +++++++ .../oxlint/suni/rules/prefer-router-types.ts | 92 +++++++++++++ .../oxlint/suni/rules/require-string-bound.ts | 39 ++++++ tools/oxlint/suni/shared/call-chain.ts | 20 +++ tools/oxlint/suni/shared/scope.ts | 125 ++++++++++++++++++ tools/oxlint/suni/shared/tanstack-router.ts | 13 ++ 14 files changed, 395 insertions(+), 11 deletions(-) create mode 100644 packages/db/src/validation/ids.ts create mode 100644 tools/oxlint/suni/rules/no-nullable-text.ts create mode 100644 tools/oxlint/suni/rules/prefer-router-types.ts create mode 100644 tools/oxlint/suni/rules/require-string-bound.ts create mode 100644 tools/oxlint/suni/shared/call-chain.ts create mode 100644 tools/oxlint/suni/shared/scope.ts create mode 100644 tools/oxlint/suni/shared/tanstack-router.ts diff --git a/apps/web/src/components/customers/customer-filters.tsx b/apps/web/src/components/customers/customer-filters.tsx index 06c3fcd..7f51b8c 100644 --- a/apps/web/src/components/customers/customer-filters.tsx +++ b/apps/web/src/components/customers/customer-filters.tsx @@ -7,9 +7,9 @@ import { SegmentedControl } from "@/components/customers/shared/segmented-contro const routeApi = getRouteApi("/_auth/customers/"); -type Search = ReturnType; +type TypeFilter = "all" | (typeof CUSTOMER_TYPES)[number]; -const TYPE_OPTIONS: { value: Search["type"]; label: string }[] = [ +const TYPE_OPTIONS: { value: TypeFilter; label: string }[] = [ { value: "all", label: "Todos" }, ...CUSTOMER_TYPES.map((value) => ({ value, label: value })), ]; @@ -23,10 +23,10 @@ export default function CustomerFilters({ customers }: CustomerFiltersProps) { const { name, type } = routeApi.useSearch(); const navigate = routeApi.useNavigate(); - const setFilters = (filters: Partial) => + const setFilters = (filters: { name?: string; type?: TypeFilter }) => navigate({ search: (prev) => ({ ...prev, ...filters }), replace: true }); - const countOf = (value: Search["type"]) => + const countOf = (value: TypeFilter) => value === "all" ? customers.length : customers.filter((customer) => customer.type === value).length; diff --git a/apps/web/src/components/sign-in-form.tsx b/apps/web/src/components/sign-in-form.tsx index 0f413db..41c6e77 100644 --- a/apps/web/src/components/sign-in-form.tsx +++ b/apps/web/src/components/sign-in-form.tsx @@ -1,10 +1,10 @@ +import { userSchema } from "@suni/db/validation/users"; import { Button } from "@suni/ui/components/button"; import { Input } from "@suni/ui/components/input"; import { Label } from "@suni/ui/components/label"; import { useForm } from "@tanstack/react-form"; import { useState } from "react"; import { toast } from "sonner"; -import { z } from "zod"; import { authClient } from "@/lib/auth-client"; @@ -51,7 +51,7 @@ function EmailSignInForm({ onSent }: { onSent: () => void }) { toast.error("No pudimos enviar el enlace. Intenta de nuevo."); } }, - validators: { onSubmit: z.object({ email: z.email("Correo inválido") }) }, + validators: { onSubmit: userSchema.pick({ email: true }) }, }); return ( diff --git a/docs/agents/code-quality.md b/docs/agents/code-quality.md index a485f3b..2ac6e47 100644 --- a/docs/agents/code-quality.md +++ b/docs/agents/code-quality.md @@ -7,4 +7,5 @@ The repository uses Ultracite with Oxlint and Oxfmt. Treat `oxlint.config.ts` an - For named functions, follow the declaration style required by `oxlint.config.ts`. Use arrow functions for callbacks. The config has scoped exceptions for web routes and components. - Name complex conditions, use early returns for error cases, and avoid nested ternaries. - Remove `console.log`, `debugger`, and `alert` from production code. +- Project rules live in `tools/oxlint/suni/` (the `suni/*` rules in `oxlint.config.ts`). They cover bounded `z.string()`, no nullable text, and router types from `AppRouterInputs`/`AppRouterOutputs`. Fix the code; do not disable the rule. - `pnpm run check:type-aware` runs the type-aware rules (`no-unnecessary-condition`, `no-unnecessary-type-assertion`) with `oxlint-type-aware.config.ts`. It also runs in CI and on pre-push. diff --git a/oxlint.config.ts b/oxlint.config.ts index 42816cb..91334c5 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -36,6 +36,22 @@ const MANUAL_MEMO_BAN = { "The React Compiler memoizes components in apps/web. Write plain code; do not memoize by hand.", }; +const ZOD_MESSAGE = + "Components do not define schemas. Use the shared schema from @suni/db/validation/*; `import type { z }` is fine."; + +const ZOD_VALUE_BAN = { + name: "zod", + allowTypeImports: true, + message: ZOD_MESSAGE, +}; + +// Subpaths at any depth (`zod/v4`, `zod/v4/mini`, ...) build schemas just like the root import. +const ZOD_SUBPATH_BAN = { + group: ["zod/**"], + allowTypeImports: true, + message: ZOD_MESSAGE, +}; + const jsPlugins = selectJsPlugins(["github", "sonarjs", "react-doctor"]); export default defineConfig({ @@ -71,8 +87,25 @@ export default defineConfig({ patterns: WEB_RESTRICTED_PATTERNS, }, ], + "suni/prefer-router-types": "error", }, }, + { + files: ["packages/db/src/validation/**/*.ts"], + rules: { "suni/require-string-bound": "error" }, + }, + { + files: [ + "packages/db/src/validation/**/*.ts", + "packages/db/src/schema/**/*.ts", + ], + rules: { "suni/no-nullable-text": "error" }, + }, + { + // auth:generate owns this file; its columns follow Better Auth, not our text rule. + files: ["packages/db/src/schema/auth.ts"], + rules: { "suni/no-nullable-text": "off" }, + }, { files: ["packages/db/src/index.ts", "packages/db/src/schema/index.ts"], rules: { @@ -115,8 +148,8 @@ export default defineConfig({ "no-restricted-imports": [ "error", { - paths: [REACT_HOOK_FORM_BAN, MANUAL_MEMO_BAN], - patterns: WEB_RESTRICTED_PATTERNS, + paths: [REACT_HOOK_FORM_BAN, MANUAL_MEMO_BAN, ZOD_VALUE_BAN], + patterns: [...WEB_RESTRICTED_PATTERNS, ZOD_SUBPATH_BAN], }, ], }, diff --git a/packages/db/src/validation/branches.ts b/packages/db/src/validation/branches.ts index 70c95bf..8c349be 100644 --- a/packages/db/src/validation/branches.ts +++ b/packages/db/src/validation/branches.ts @@ -1,5 +1,7 @@ import { z } from "zod"; +import { ID_LENGTH } from "./ids"; + const MAX_100_MESSAGE = "Máximo 100 caracteres"; export const branchSchema = z.object({ @@ -40,5 +42,5 @@ export const branchSchema = z.object({ }); export const createBranchSchema = branchSchema.extend({ - customerId: z.string().min(1, "El cliente es requerido"), + customerId: z.string().length(ID_LENGTH, "El cliente es requerido"), }); diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts index db8b9dd..50d5e3e 100644 --- a/packages/db/src/validation/contacts.ts +++ b/packages/db/src/validation/contacts.ts @@ -1,5 +1,7 @@ import { z } from "zod"; +import { ID_LENGTH } from "./ids"; + export const contactSchema = z.object({ name: z .string() @@ -13,6 +15,6 @@ export const contactSchema = z.object({ }); export const createContactSchema = contactSchema.extend({ - customerId: z.string().min(1, "El cliente es requerido"), - branchId: z.string().min(1, "La sucursal es requerida"), + customerId: z.string().length(ID_LENGTH, "El cliente es requerido"), + branchId: z.string().length(ID_LENGTH, "La sucursal es requerida"), }); diff --git a/packages/db/src/validation/ids.ts b/packages/db/src/validation/ids.ts new file mode 100644 index 0000000..a4c3d9f --- /dev/null +++ b/packages/db/src/validation/ids.ts @@ -0,0 +1,2 @@ +// Ids are cuid2: createId() always returns 24 characters. +export const ID_LENGTH = 24; diff --git a/tools/oxlint/suni/index.ts b/tools/oxlint/suni/index.ts index dfab8b1..ab1f9fb 100644 --- a/tools/oxlint/suni/index.ts +++ b/tools/oxlint/suni/index.ts @@ -1,12 +1,18 @@ import { definePlugin } from "@oxlint/plugins"; +import noNullableText from "./rules/no-nullable-text.ts"; +import preferRouterTypes from "./rules/prefer-router-types.ts"; import requireSellerScope from "./rules/require-seller-scope.ts"; +import requireStringBound from "./rules/require-string-bound.ts"; import requireSuppressionReason from "./rules/require-suppression-reason.ts"; export default definePlugin({ meta: { name: "suni" }, rules: { + "no-nullable-text": noNullableText, + "prefer-router-types": preferRouterTypes, "require-seller-scope": requireSellerScope, + "require-string-bound": requireStringBound, "require-suppression-reason": requireSuppressionReason, }, }); diff --git a/tools/oxlint/suni/rules/no-nullable-text.ts b/tools/oxlint/suni/rules/no-nullable-text.ts new file mode 100644 index 0000000..3e6cfc7 --- /dev/null +++ b/tools/oxlint/suni/rules/no-nullable-text.ts @@ -0,0 +1,49 @@ +import { defineRule } from "@oxlint/plugins"; + +import { chainedMethods } from "../shared/call-chain.ts"; + +const NULLABLE_METHODS = new Set(["nullable", "nullish"]); +const NOT_NULL_METHODS = ["notNull", "primaryKey", "references"]; + +export default defineRule({ + meta: { + type: "problem", + docs: { + description: + "Store empty text as an empty string: no nullable Zod fields and no nullable text columns.", + }, + }, + create(context) { + return { + CallExpression(node) { + const { callee } = node; + + // Zod: `.nullable()` / `.nullish()` anywhere in a validation file. + if ( + callee.type === "MemberExpression" && + callee.property.type === "Identifier" && + NULLABLE_METHODS.has(callee.property.name) + ) { + context.report({ + node: callee.property, + message: + 'Do not make fields nullable: an empty value is `""`, so the form and the API share one schema.', + }); + return; + } + + // Drizzle: a `text(...)` column chain without `.notNull()`. + if (callee.type !== "Identifier" || callee.name !== "text") return; + + const methods = chainedMethods(node); + if (NOT_NULL_METHODS.some((name) => methods.includes(name))) return; + + context.report({ + node, + message: + 'Text columns are `.notNull()`: store `""` instead of NULL (primary keys and foreign keys with `.references()` are the exception).', + }); + }, + }; + }, +}); diff --git a/tools/oxlint/suni/rules/prefer-router-types.ts b/tools/oxlint/suni/rules/prefer-router-types.ts new file mode 100644 index 0000000..63fe934 --- /dev/null +++ b/tools/oxlint/suni/rules/prefer-router-types.ts @@ -0,0 +1,92 @@ +import { defineRule, type ESTree } from "@oxlint/plugins"; + +import { + derivesFromImport, + isImportOf, + type ImportSpec, +} from "../shared/scope.ts"; +import { fromRouter, ROUTE_OBJECT } from "../shared/tanstack-router.ts"; + +// oRPC query and mutation hooks live in `hooks/use-.ts` and are named after what they call on the +// router (`useListCustomers`, `useCreateUser`, `useChangeUserStatus`). Other hooks there (`useIsAdmin`, +// `useAddressLookup`) return plain values and have no router type to use. +const ROUTER_HOOK: ImportSpec = { + source: /(?:^|\/)hooks\/use-[^/]+$/u, + name: /^use(?:List|Get|Create|Update|Archive|Change)[A-Z]/u, +}; +// Route hooks whose return is the route's search, params or loader data. +const ROUTE_DATA_HOOKS = "useSearch|useLoaderData|useParams"; +const ROUTE_DATA_HOOK = fromRouter(ROUTE_DATA_HOOKS); +const ROUTE_DATA_MEMBER = new RegExp(`^(?:${ROUTE_DATA_HOOKS})$`, "u"); + +function rootOfIndexedAccess(type: ESTree.Node): ESTree.Node { + let current = type; + while (current.type === "TSIndexedAccessType") current = current.objectType; + return current; +} + +export default defineRule({ + meta: { + type: "suggestion", + docs: { + description: + "Type router inputs and outputs with AppRouterInputs / AppRouterOutputs.", + }, + }, + create(context) { + const isRouterDataHook = (name: ESTree.TSTypeQuery["exprName"]) => { + const { sourceCode } = context; + + if (name.type === "Identifier") + return ( + isImportOf(sourceCode, name, ROUTER_HOOK) || + isImportOf(sourceCode, name, ROUTE_DATA_HOOK) + ); + + // `Route.useSearch`: only when `Route` is a route API or a route built by TanStack Router. + return ( + name.type === "TSQualifiedName" && + name.left.type === "Identifier" && + ROUTE_DATA_MEMBER.test(name.right.name) && + derivesFromImport(sourceCode, name.left, ROUTE_OBJECT) + ); + }; + + return { + TSTypeReference(node) { + if (node.typeName.type !== "Identifier") return; + + const [argument] = node.typeArguments?.params ?? []; + if (!argument) return; + + const { name } = node.typeName; + const root = rootOfIndexedAccess(argument); + + if ( + name === "Parameters" && + root.type === "TSTypeReference" && + root.typeName.type === "Identifier" && + root.typeName.name === "AppRouterClient" + ) { + context.report({ + node, + message: + "Use `AppRouterInputs[...]` from `@suni/api/routers/index` instead of `Parameters`.", + }); + } + + if ( + name === "ReturnType" && + argument.type === "TSTypeQuery" && + isRouterDataHook(argument.exprName) + ) { + context.report({ + node, + message: + "Use `AppRouterOutputs[...]` from `@suni/api/routers/index` (or the route's own types) instead of `ReturnType` on a router hook.", + }); + } + }, + }; + }, +}); diff --git a/tools/oxlint/suni/rules/require-string-bound.ts b/tools/oxlint/suni/rules/require-string-bound.ts new file mode 100644 index 0000000..afadf71 --- /dev/null +++ b/tools/oxlint/suni/rules/require-string-bound.ts @@ -0,0 +1,39 @@ +import { defineRule } from "@oxlint/plugins"; + +import { chainedMethods } from "../shared/call-chain.ts"; + +const BOUNDING_METHODS = new Set(["max", "length", "regex"]); + +export default defineRule({ + meta: { + type: "problem", + docs: { + description: + "Require every z.string() to set its own limit with .max(), .length() or .regex().", + }, + }, + create(context) { + return { + CallExpression(node) { + const { callee } = node; + if ( + callee.type !== "MemberExpression" || + callee.object.type !== "Identifier" || + callee.object.name !== "z" || + callee.property.type !== "Identifier" || + callee.property.name !== "string" + ) + return; + + if (chainedMethods(node).some((name) => BOUNDING_METHODS.has(name))) + return; + + context.report({ + node, + message: + "Every field defines its own limit: add `.max(n)`, `.length(n)` or `.regex(...)` to this z.string(). `.min(1)` alone is not a bound.", + }); + }, + }; + }, +}); diff --git a/tools/oxlint/suni/shared/call-chain.ts b/tools/oxlint/suni/shared/call-chain.ts new file mode 100644 index 0000000..004d244 --- /dev/null +++ b/tools/oxlint/suni/shared/call-chain.ts @@ -0,0 +1,20 @@ +import type { ESTree } from "@oxlint/plugins"; + +/** Names of the methods chained onto `start`: `z.string().trim().max(5)` gives `["trim", "max"]`. */ +export function chainedMethods(start: ESTree.Node): string[] { + const methods: string[] = []; + let current: ESTree.Node = start; + + while ( + current.parent?.type === "MemberExpression" && + current.parent.object === current && + current.parent.property.type === "Identifier" && + current.parent.parent?.type === "CallExpression" && + current.parent.parent.callee === current.parent + ) { + methods.push(current.parent.property.name); + current = current.parent.parent; + } + + return methods; +} diff --git a/tools/oxlint/suni/shared/scope.ts b/tools/oxlint/suni/shared/scope.ts new file mode 100644 index 0000000..2d90f14 --- /dev/null +++ b/tools/oxlint/suni/shared/scope.ts @@ -0,0 +1,125 @@ +import type { ESTree, Scope, SourceCode, Variable } from "@oxlint/plugins"; + +type Identifier = Extract; + +/** Resolve an identifier to its binding by walking lexical scopes upward. */ +function resolveVariable( + sourceCode: SourceCode, + identifier: Identifier +): Variable | null { + let scope: Scope | null = sourceCode.getScope(identifier); + + while (scope !== null) { + const variable = scope.set.get(identifier.name); + if (variable !== undefined) return variable; + scope = scope.upper; + } + + return null; +} + +interface ImportBinding { + source: string; + /** Imported name; `default` for a default import, `*` for a namespace import. */ + name: string; +} + +function importBindingOf(variable: Variable): ImportBinding | null { + const [definition] = variable.defs; + + if ( + definition?.type !== "ImportBinding" || + definition.parent?.type !== "ImportDeclaration" + ) + return null; + + const { node } = definition; + const source = definition.parent.source.value; + + if (node.type === "ImportNamespaceSpecifier") return { source, name: "*" }; + if (node.type === "ImportDefaultSpecifier") + return { source, name: "default" }; + if (node.type !== "ImportSpecifier") return null; + + const { imported } = node; + return { + source, + name: + imported.type === "Identifier" ? imported.name : String(imported.value), + }; +} + +/** What an import must look like: the module, and optionally the imported name (the local alias never matters). */ +export interface ImportSpec { + source: RegExp; + name?: RegExp; +} + +function matchesSpec(binding: ImportBinding, spec: ImportSpec) { + return ( + spec.source.test(binding.source) && + (!spec.name || (binding.name !== "*" && spec.name.test(binding.name))) + ); +} + +/** True when `identifier` resolves to an import matching `spec`, whatever local name it has. */ +export function isImportOf( + sourceCode: SourceCode, + identifier: Identifier, + spec: ImportSpec +): boolean { + const variable = resolveVariable(sourceCode, identifier); + const binding = variable && importBindingOf(variable); + + return !!binding && matchesSpec(binding, spec); +} + +/** Initializer of a `const x = ` binding, or `null` for any other kind of binding. */ +function initializerOf(variable: Variable): ESTree.Expression | null { + const [definition] = variable.defs; + + if ( + definition?.type === "Variable" && + definition.node.type === "VariableDeclarator" && + definition.node.id.type === "Identifier" + ) + return definition.node.init; + + return null; +} + +/** Leftmost identifier of `a.b.c(...).d`, or `null` when the chain starts elsewhere (`new X()`, a literal). */ +function rootIdentifier(node: ESTree.Node): Identifier | null { + let current = node; + + while ( + current.type === "MemberExpression" || + current.type === "CallExpression" + ) + current = + current.type === "MemberExpression" ? current.object : current.callee; + + return current.type === "Identifier" ? current : null; +} + +/** + * True when the leftmost identifier of `node` is an import matching `spec`, or a binding initialized + * from such a chain: `z.object()` after `import { z } from "zod"`, `Route` after `Route = createFileRoute()()`. + */ +export function derivesFromImport( + sourceCode: SourceCode, + node: ESTree.Node, + spec: ImportSpec, + seen = new Set() +): boolean { + const root = rootIdentifier(node); + const variable = root && resolveVariable(sourceCode, root); + if (!variable || seen.has(variable)) return false; + seen.add(variable); + + const binding = importBindingOf(variable); + if (binding) return matchesSpec(binding, spec); + + const init = initializerOf(variable); + return !!init && derivesFromImport(sourceCode, init, spec, seen); +} diff --git a/tools/oxlint/suni/shared/tanstack-router.ts b/tools/oxlint/suni/shared/tanstack-router.ts new file mode 100644 index 0000000..0912afb --- /dev/null +++ b/tools/oxlint/suni/shared/tanstack-router.ts @@ -0,0 +1,13 @@ +import type { ImportSpec } from "./scope.ts"; + +const ROUTER_MODULE = /^@tanstack\/react-router$/u; + +/** A hook (or function) imported from TanStack Router, whatever alias it has locally. */ +export function fromRouter(name: string): ImportSpec { + return { source: ROUTER_MODULE, name: new RegExp(`^(?:${name})$`, "u") }; +} + +/** What builds a route API or Route object, the receiver of `.useSearch()` and `.useNavigate()`. */ +export const ROUTE_OBJECT = fromRouter( + "getRouteApi|createFileRoute|createRoute|createRootRoute|createRootRouteWithContext|createLazyFileRoute|createLazyRoute" +); From 459af599586500f114affd3a017b3d5fdb3811a6 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 09:07:15 -0600 Subject: [PATCH 7/9] Documenta las reglas que no se pueden lintear y las pasa a CodeRabbit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cubre el UPDATE atómico de entidades hijas, el texto de la interfaz en español, el React Compiler, min-w-0 en tablas anchas, finalFocus en diálogos y los ajustes tras shadcn add. --- .coderabbit.config.ts | 14 ++++++++++++++ AGENTS.md | 5 +++++ apps/web/AGENTS.md | 3 +++ packages/ui/AGENTS.md | 2 ++ 4 files changed, 24 insertions(+) diff --git a/.coderabbit.config.ts b/.coderabbit.config.ts index 8811b0a..4d9c2e7 100644 --- a/.coderabbit.config.ts +++ b/.coderabbit.config.ts @@ -4,6 +4,10 @@ const SOURCE_FILES = "{apps,packages}/**/*.{ts,tsx}"; const REACT_FILES = "{apps/web,packages/ui}/src/**/*.tsx"; +const API_ROUTERS = "packages/api/src/routers/**/*.ts"; + +const WEB_COMPONENTS = "apps/web/src/**/*.tsx"; + export default defineConfig({ reviews: { high_level_summary: false, @@ -33,6 +37,16 @@ export default defineConfig({ instructions: "Hold changed code to the rules in docs/agents/react-accessibility.md.", }, + { + path: API_ROUTERS, + instructions: + "A mutation on a child entity (branch, contact) must check, in the same `UPDATE ... WHERE`, that neither it nor its parents are archived. State changes are one atomic `UPDATE ... WHERE ... RETURNING`, not a read followed by a write. Fields only admins may see are removed in the query, not hidden in the UI.", + }, + { + path: WEB_COMPONENTS, + instructions: + "UI copy and accessibility text (`aria-label`, `sr-only`, `title`) must be in Spanish. A flex container that holds a wide table needs `min-w-0`. When a dialog's trigger can disappear on close, set `finalFocus`.", + }, ], }, knowledge_base: { diff --git a/AGENTS.md b/AGENTS.md index 97bc1c5..41640a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,6 +59,11 @@ A change is not done until it reaches every surface it touches. Before calling w - Migration or `.env.schema` change needed? The user generates migrations, never you. - Docs, only if existing guidance became inaccurate. +## Rules the linter cannot check + +- A mutation on a child entity checks, in the same `UPDATE ... WHERE`, that neither it nor its parents are archived. +- UI copy and accessibility text (`aria-label`, `sr-only`, `title`) are in Spanish. + ## Context files - [apps/web/AGENTS.md](apps/web/AGENTS.md) (web routes, client setup, and local commands) diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index fd90314..9f56594 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -29,6 +29,9 @@ See [package.json](package.json) for available scripts. From the repo root, run - Every page that fetches data renders loading, empty, and error states. - Hide navigation and actions the current user cannot use, matching the procedure each one calls (`useIsAdmin` for admin-only ones). - Keep a component's props type, constants, and labels in the same file as the component. +- The React Compiler is on. Do not use `useMemo`, `useCallback` or `memo`; lint rejects them. +- A flex container that holds a wide table needs `min-w-0`, or the table stretches the page. +- When a dialog's trigger can disappear on close (it is archived, removed or filtered out), set `finalFocus` so focus lands somewhere sensible. ## Generated files diff --git a/packages/ui/AGENTS.md b/packages/ui/AGENTS.md index e3be2ce..e7383a7 100644 --- a/packages/ui/AGENTS.md +++ b/packages/ui/AGENTS.md @@ -20,3 +20,5 @@ See [package.json](package.json) for available scripts. From the repo root, run * Place reusable primitives in `src/components/` and import them as `@suni/ui/components/`. * Adjust shared design tokens in `src/styles/globals.css`. +* After `shadcn add`, restore `button.tsx`, `input.tsx` and `tooltip.tsx` from Git (they carry Suni variants), and translate any English labels the new component brings. +* Variant names are kebab-case (`outline-destructive`). From 0bfadfd16f31b2ddcd3bf188efa35695df072258 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 09:40:06 -0600 Subject: [PATCH 8/9] Agrega la tabla de reglas y lo que las hace cumplir MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cada corrección repetida queda con su verificación, o marcada como revisión manual cuando todavía no tiene una. --- AGENTS.md | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 41640a7..242eee2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,10 +59,22 @@ A change is not done until it reaches every surface it touches. Before calling w - Migration or `.env.schema` change needed? The user generates migrations, never you. - Docs, only if existing guidance became inaccurate. -## Rules the linter cannot check - -- A mutation on a child entity checks, in the same `UPDATE ... WHERE`, that neither it nor its parents are archived. -- UI copy and accessibility text (`aria-label`, `sr-only`, `title`) are in Spanish. +## Rules and what enforces them + +When the operator corrects a repeated mistake, fix it and add a row here. If the rule was already here with no enforcer, that is a repeat: enforce it in the same change. Drop a row once its mistake can no longer be written. + +| Rule | Enforced by | +| --- | --- | +| Hooks never list query keys to invalidate. | The `MutationCache` in `apps/web/src/utils/orpc.ts` | +| Customer and branch reads hide seller identity from non-admins. | `suni/require-seller-scope` | +| No unnecessary conditions or type assertions. | `pnpm run check:type-aware` (pre-push and CI) | +| No manual memoization. | React Compiler plus a `no-restricted-imports` ban | +| Web types come from `AppRouterInputs`/`AppRouterOutputs`, not hand-derived. | `suni/prefer-router-types` | +| Validation strings are bounded; text is never nullable. | `suni/require-string-bound`, `suni/no-nullable-text` | +| Zod schemas live in `@suni/db/validation/*`, not in components. | `no-restricted-imports` of `zod/**` in components | +| Forms use TanStack Form; the web never imports server packages. | `no-restricted-imports` | +| A mutation on a child entity checks, in the same `UPDATE ... WHERE`, that neither it nor its parents are archived. | Review only | +| UI copy and accessibility text (`aria-label`, `sr-only`, `title`) are in Spanish. | Review only | ## Context files From e9de3f20164941065924f23d08335004b9484ae5 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 17 Nov 2026 16:29:07 -0600 Subject: [PATCH 9/9] =?UTF-8?q?Evita=20que=20require-string-bound=20cuente?= =?UTF-8?q?=20el=20l=C3=ADmite=20del=20arreglo=20como=20el=20del=20string?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/oxlint/suni/rules/require-string-bound.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tools/oxlint/suni/rules/require-string-bound.ts b/tools/oxlint/suni/rules/require-string-bound.ts index afadf71..38cfd99 100644 --- a/tools/oxlint/suni/rules/require-string-bound.ts +++ b/tools/oxlint/suni/rules/require-string-bound.ts @@ -25,8 +25,12 @@ export default defineRule({ ) return; - if (chainedMethods(node).some((name) => BOUNDING_METHODS.has(name))) - return; + const methods = chainedMethods(node); + // After `.array()`, `.max()` and `.length()` bound the array, not the string. + const arrayAt = methods.indexOf("array"); + const stringMethods = + arrayAt === -1 ? methods : methods.slice(0, arrayAt); + if (stringMethods.some((name) => BOUNDING_METHODS.has(name))) return; context.report({ node,