fix(contracts): destravar deno check de 15 edge functions (TS2345 em parseContract)#103
fix(contracts): destravar deno check de 15 edge functions (TS2345 em parseContract)#103adm01-debug wants to merge 3 commits into
Conversation
…parseContract)
O job "Edge Functions — Deno typecheck" do CI quebrava em 15 functions que
usam parseContract (bi-copilot, block-ip-temporarily, e2e-cleanup,
force-global-logout, kit-ai-builder, market-intelligence-insights,
ownership-audit, ownership-repair, product-webhook, send-transactional-email,
simulation-orchestrator, step-up-verify, sync-external-db, trends-insights,
webhook-dispatcher) com TS2345:
"The types returned by versions[\"1\"].deepPartial() are incompatible..."
Causa raiz: a assinatura
parseContract<V, S extends Record<V, z.ZodTypeAny>>(
req, schemas: ContractSchemas<V> & { versions: S }, ...)
forcava, via a intersecao `ContractSchemas<V> & { versions: S }`, o tipo de
`versions[k]` a virar `z.ZodTypeAny & ZodObject<...>`. Ao verificar a
atribuicao, o checker recursa no retorno de `ZodObject.deepPartial()`
(metodo cujo tipo de retorno referencia o proprio shape), estourando com
variancia incompativel. So disparava em schemas com shape especifico (por isso
webhook-inbound, com schema diferente, passava).
Fix: generalizar `parseContract` sobre o tipo do objeto de schemas (`C extends
ContractSchemas`) e remover a intersecao. `versions[k]` deixa de ser comparado
contra uma intersecao com ZodTypeAny — some a recursao. `data` e inferido por
indexacao direta do schema da versao default (`InferContractData<C>`),
preservando o comportamento de tipo dos handlers. `version` passa a `string`
(ja era resolvida em runtime). Nenhum call site externo referencia os tipos
`ParseResult`/`ContractSchemas`, entao a mudanca e compativel.
Verificado localmente com `node scripts/typecheck-edge-functions.mjs`:
81/81 edge functions compilam limpo (antes: 15 com erro).
Co-authored-by: Claude <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughParseResult e parseContract foram retipados para derivar ChangesRefatoração de Contrato de Parseamento
🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs:
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Pull request overview
This PR adjusts the TypeScript typings of the shared parseContract helper used by Supabase Edge Functions to avoid a TS+Zod variance recursion (TS2345) that was breaking deno check across multiple functions.
Changes:
- Refactors
parseContractto be generic over the wholeContractSchemasobject (C extends ContractSchemas), removing the problematic intersection type. - Introduces
DefaultSchema/InferContractDatahelper types and updatesParseResultto inferdatafrom the contract’s default schema. - Loosens
versiontyping tostringand adds internal casts to keep runtime behavior unchanged while unblocking Deno typechecking.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: af130d2d2f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| version: version as V, | ||
| data: result.data, | ||
| version, | ||
| data: result.data as InferContractData<C>, |
There was a problem hiding this comment.
Preserve data typing for negotiated contract version
parseContract now always casts result.data to InferContractData<C>, which is derived from defaultVersion rather than the negotiated version. For contracts with divergent schemas across versions (for example several "1"/"2" schema pairs in this repo), a request with accept-version: 2 can return v2-shaped data while the function advertises v1-shaped data, removing type safety and allowing handlers to compile with field assumptions that are false at runtime for non-default versions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@supabase/functions/_shared/contracts/parse.ts`:
- Around line 62-67: ParseResult currently types version as string and data as
the defaultVersion shape (InferContractData<C>), which breaks the runtime
correlation between the resolved version and the parsed data; update the typings
so the returned version and data are linked to the actual resolved schema from
resolveContractVersion/schemas.versions. Concretely, make ParseResult (and
parseContract's return type) parametric or discriminated by V extends keyof
C["versions"] (use that key type instead of string) and type data as
z.infer<C["versions"][V]> (or produce a union of {version: V; data:
z.infer<...>} for each V) so the compile-time type matches the runtime
validation performed in parseContract/resolveContractVersion.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 112535d2-380a-48c0-91ed-778236965648
📒 Files selected for processing (1)
supabase/functions/_shared/contracts/parse.ts
There was a problem hiding this comment.
1 issue found across 1 file
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…pe-safety multi-versao) Atende aos reviews automáticos (Copilot/Codex/CodeRabbit/cubic, P2) no PR #103. Contexto: o fix anterior tipava `data` como `InferContractData<C>` (sempre o shape da defaultVersion). Como TODOS os 16 contratos têm v1 e v2 com shapes DIVERGENTES (strict, discriminated unions, campos obrigatórios distintos), isso apagava a type-safety para a versão não-default: um request com accept-version:2 retornava data v2 em runtime, mas o tipo anunciava v1. Mudança: `ParseResult<C>` passa a ser uma UNIÃO discriminada por versão — `{ version: "1"; data: v1 } | { version: "2"; data: v2 } | ...` — derivada de `C["versions"]`. Agora `version` é `"1" | "2"` (não `string`) e `data` casa com o schema da versão correspondente, mantendo version↔data correlacionados em compile-time. Preserva a correção do TS2345: continuamos indexando os schemas diretamente, sem a interseção `ContractSchemas<V> & { versions: S }` que fazia o checker recursar em `ZodObject.deepPartial()`. O return usa um cast para `ParseResult<C>` (o TS colapsa a união mapeada para `never` sobre `C` não-resolvido dentro do corpo genérico; a validação real é feita por resolveContractVersion+safeParse). Verificado: `node scripts/typecheck-edge-functions.mjs` → 81/81 limpas. Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Fechando como redundante — bug já corrigido na
|
Problema
O workflow CI na
main(run #404, commitca9ca9c) está vermelho. Um dos jobs que falha é Edge Functions — Deno typecheck (node scripts/typecheck-edge-functions.mjs), que quebrava em 15 edge functions que usamparseContract:bi-copilot,block-ip-temporarily,e2e-cleanup,force-global-logout,kit-ai-builder,market-intelligence-insights,ownership-audit,ownership-repair,product-webhook,send-transactional-email,simulation-orchestrator,step-up-verify,sync-external-db,trends-insights,webhook-dispatcher.Erro (TS2345):
Causa raiz
A assinatura do helper era:
A interseção
ContractSchemas<V> & { versions: S }força o tipo deversions[k]a virarz.ZodTypeAny & ZodObject<...>. Ao verificar a atribuição do schema concreto, o checker recursa no tipo de retorno deZodObject.deepPartial()(que referencia o próprio shape com campos tornados opcionais), estourando com variância incompatível. Só dispara em schemas com shape específico — por issowebhook-inbound(shape diferente) passava enquanto os outros 15 falhavam.Fix
Generalizar
parseContractsobre o tipo do objeto de schemas (C extends ContractSchemas), removendo a interseção:versions[k]deixa de ser comparado contra uma interseção comZodTypeAny→ some a recursão emdeepPartial().dataé inferido por indexação direta do schema da versão default (InferContractData<C>), preservando o tipo que os handlers consomem.versionpassa astring(já era resolvida em runtime viaresolveContractVersion).ParseResult/ContractSchemas— mudança compatível. Os 16 handlers só usamparseContract(...), checam.oke desestruturam.data/.version/.responseHeaders.Verificação
Local, com
node scripts/typecheck-edge-functions.mjs(mesmo comando do CI), via Deno 2.7.14:81/81 edge functions compilam limpo (antes: 15 com erro, exit 1).
Diff cirúrgico: 1 arquivo (
supabase/functions/_shared/contracts/parse.ts), apenas tipos + casts internos; zero mudança de comportamento em runtime.Co-authored-by: Claude noreply@anthropic.com
Summary by cubic
Destrava o job “Edge Functions — Deno typecheck” ao corrigir o TS2345 em
parseContractque quebrava 15 funções. O retorno agora preserva a type-safety multi‑versão sem alterar o comportamento em runtime.Bug Fixes
parseContractparaC extends ContractSchemase remove a interseção que forçavaZodTypeAny & ZodObject.schemas.versions[version]diretamente (sem interseção), eliminando a recursão dedeepPartial(); resultado: 81/81 edge functions passam nodeno check.Refactors
ParseResult<C>vira união discriminada porversion;datacasa com o schema da versão retornada.versionpassa a ser"1" | "2" | ...(nãostring).Written for commit c47af9a. Summary will update on new commits. Review in cubic
Summary by CodeRabbit