fix(ci): CI verde — corrige typecheck (TS2556), vps:check e deno (TS2345) - #150
fix(ci): CI verde — corrige typecheck (TS2556), vps:check e deno (TS2345)#150adm01-debug wants to merge 19 commits into
Conversation
- instanceHealthGate.test.ts: fromMock com rest-param resolve TS2556 - vite.config.ts: build.target es2020 + sourcemap por modo (gate vps:check) Co-authored-by: Claude <noreply@anthropic.com>
Resolve os 2 TS2345 do deno type-check: ReturnType<typeof createClient> nao casa com o client real; troca por SupabaseClient. deno test 241/0. Co-authored-by: Claude <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughPequenos refinamentos: mock de Supabase no teste aceita args variádicos; tipo ChangesAjustes de tipo e comentários
🎯 3 (Moderate) | ⏱️ ~20 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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
Este PR busca deixar o CI “verde” corrigindo três gates que estavam falhando por problemas reais de typecheck e de validação de build.
Changes:
- Ajusta o mock de teste para aceitar argumentos variádicos e eliminar o TS2556 em
instanceHealthGate.test.ts. - Configura explicitamente
build.targete uma política intencional desourcemapnovite.config.tspara satisfazer o gatevps:check. - Corrige o typecheck do Deno na edge function
public-apisubstituindoReturnType<typeof createClient>porSupabaseCliente pinando o import dosupabase-jsviaesm.sh.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| vite.config.ts | Define build.target: "es2020" e sourcemaps apenas em modo development para passar vps:check e evitar sourcemaps em produção. |
| supabase/functions/public-api/index.ts | Ajusta tipagem do client do Supabase para resolver incompatibilidade no typecheck do Deno e fixa versão do import remoto. |
| src/lib/tests/instanceHealthGate.test.ts | Corrige assinatura do mock fromMock para bater com o call-site que espalha args. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
supabase/functions/public-api/index.ts (1)
189-189:⚠️ Potential issue | 🟠 Major | ⚖️ Poor tradeoffErro de banco pode vazar estrutura de schema.
O
msgError.messagepode incluir nomes de constraints, tabelas, ou detalhes da query que revelam a estrutura interna do banco. Considere logar apenas um identificador genérico para o cliente e registrar detalhes completos apenas no log interno.🔒 Sugestão de ajuste
if (msgError) { if (idempotencyKey && isUniqueViolation(msgError)) { const previousMessage = await findMessageByIdempotencyKey(supabase, idempotencyKey); if (previousMessage) { log.info('Idempotency replay after unique conflict', { idempotencyKey, messageId: previousMessage.id }); return jsonResponse(buildReplayPayload(previousMessage, requestId), 200, req); } } - log.error('Failed to save message', { error: msgError.message }); + log.error('Failed to save message', { errorCode: msgError.code, hint: msgError.hint }); return errorResponse('Failed to save message', 500, req); }🤖 Prompt for 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. In `@supabase/functions/public-api/index.ts` at line 189, A mensagem de erro atual log.error('Failed to save message', { error: msgError.message }) pode vazar schema/constraint detalhes; altere para registar um identificador genérico para o cliente no log público (ex.: { errorId }) e envie os detalhes completos (msgError and stack) apenas para um log interno/secure logger ou armazenador de erros. Substitua o uso direto de msgError.message na chamada log.error por um token/errorId gerado (ou uma mensagem genérica como "Database error") e faça um segundo envio seguro contendo msgError/msgError.stack para o logger interno; preserve o contexto (ex.: a operação "save message") para correlação usando o mesmo errorId.
🤖 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/public-api/index.ts`:
- Line 1: Update the Supabase client import to a current 2.x release (at least
`@2.106.0`) by changing the version in the import statement that references
createClient and SupabaseClient; also scan this file for the other ~43 imports
that pin `@2.x` and align them to the same updated version to avoid mixed
versions, then run your build/tests to ensure there are no breaking API changes
and adjust any call sites using createClient or SupabaseClient types if
necessary.
---
Outside diff comments:
In `@supabase/functions/public-api/index.ts`:
- Line 189: A mensagem de erro atual log.error('Failed to save message', {
error: msgError.message }) pode vazar schema/constraint detalhes; altere para
registar um identificador genérico para o cliente no log público (ex.: { errorId
}) e envie os detalhes completos (msgError and stack) apenas para um log
interno/secure logger ou armazenador de erros. Substitua o uso direto de
msgError.message na chamada log.error por um token/errorId gerado (ou uma
mensagem genérica como "Database error") e faça um segundo envio seguro contendo
msgError/msgError.stack para o logger interno; preserve o contexto (ex.: a
operação "save message") para correlação usando o mesmo errorId.
🪄 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: 48ab2b37-10e7-45c1-93cc-485c40041e85
📒 Files selected for processing (3)
src/lib/__tests__/instanceHealthGate.test.tssupabase/functions/public-api/index.tsvite.config.ts
| @@ -1,4 +1,4 @@ | |||
| import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; | |||
| import { createClient, type SupabaseClient } from "https://esm.sh/@supabase/supabase-js@2.49.1"; | |||
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verificar versão mais recente do supabase-js v2 e advisories
# Versão mais recente disponível
echo "=== Latest supabase-js v2.x version ==="
curl -s 'https://registry.npmjs.org/@supabase/supabase-js' | jq -r '.versions | keys[] | select(startswith("2."))' | sort -V | tail -1
# Buscar advisories de segurança
echo -e "\n=== Security advisories ==="
gh api graphql -f query='
{
securityVulnerabilities(first: 10, ecosystem: NPM, package: "`@supabase/supabase-js`") {
nodes {
advisory {
summary
severity
publishedAt
}
vulnerableVersionRange
firstPatchedVersion {
identifier
}
}
}
}'Repository: adm01-debug/zapp-web
Length of output: 199
🏁 Script executed:
#!/bin/bash
# Encontrar última versão estável v2.x (sem canary/beta/alpha)
curl -s 'https://registry.npmjs.org/@supabase/supabase-js' | jq -r '.versions | keys[] | select(startswith("2.") and (test("-") | not))' | sort -V | tail -5Repository: adm01-debug/zapp-web
Length of output: 104
Versão @2.49.1 está significativamente desatualizada — atualizar para @2.106.0 ou maior.
Sem vulnerabilidades conhecidas reportadas, mas está ~57 patches atrás da última release estável. Edge Functions em produção devem estar com dependências mais atualizadas para evitar bugs corrigidos em versões posteriores e manter compatibilidade. O PR já menciona 43 outras importações @2 que precisam atualização — considere uma passada geral no arquivo.
🤖 Prompt for 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.
In `@supabase/functions/public-api/index.ts` at line 1, Update the Supabase client
import to a current 2.x release (at least `@2.106.0`) by changing the version in
the import statement that references createClient and SupabaseClient; also scan
this file for the other ~43 imports that pin `@2.x` and align them to the same
updated version to avoid mixed versions, then run your build/tests to ensure
there are no breaking API changes and adjust any call sites using createClient
or SupabaseClient types if necessary.
There was a problem hiding this comment.
No issues found across 3 files
Tip: cubic could auto-approve low-risk PRs like this, if it thinks it's safe to merge. Learn more
Re-trigger cubic
…h 1/4) Preventive pin of the `@2` floating import to a fixed minor (@2.49.1) across edge functions, matching the fix already applied to public-api. Avoids future Deno typecheck drift from esm.sh resolving a newer minor. No logic change — single import-line edit per file. CI already green.
…h 2) Preventive pin of the floating `@2` import to @2.49.1 (no logic change).
…h 3) Preventive pin of the floating `@2` import to @2.49.1 (no logic change).
|
You're iterating quickly on this pull request. To help protect your rate limits, cubic has paused automatic reviews on new pushes for now—when you're ready for another review, comment |
…functions) Closes the preventive @2 -> @2.49.1 pin across all edge functions. Single import-line edit per file (box-drawing-heavy files done via sed for byte-exact fidelity); no logic change. CI already green.
Objetivo
Deixar o CI verde corrigindo os 3 gates que falhavam por conteúdo (os demais falhavam por cota de Actions, já resolvida).
Bugs corrigidos (todos reproduzidos e validados localmente)
Ambiente: Bun 1.3.14 / Node 22 / Deno 2.7. Resultado: 16/16 gates do CI verdes +
deno test241 passed / 0 failed.typecheck(TS2556) —src/lib/__tests__/instanceHealthGate.test.tsfromMockeravi.fn(() => …)(sem params) mas chamado comfromMock(...args). Recebe(..._args: unknown[]). Comportamento inalterado (8/8 testes).vps:check—vite.config.tscheck-vps-readiness.mjsexigebuild.targete política de sourcemap. Adicionadotarget: "es2020"esourcemap: _env.mode === "development"(dev=on / prod=off — não expõe fonte em produção). Confirmado: build de produção gera 0 sourcemaps.denotype-check (TS2345) —supabase/functions/public-api/index.tsA raiz era a anotação
ReturnType<typeof createClient>, que resolve para os genéricos default (SupabaseClient<unknown, never, …>) e não casa com o client real (SupabaseClient<any, "public", any>). Trocado porSupabaseClient(import de tipo) — resolve independe da versão. Import pinado em@2.49.1.Notas
supabase-js@2→@2.49.1: há outros 43 imports@2não-pinados nas edge functions (entram num commit adicional nesta branch). Não afetam o CI atual; são prevenção contra quebra futura quando o esm.sh avançar o major@2.ReturnType<typeof createClient>em 11 arquivos (não alcançadas por testes hoje).Co-authored-by: Claude noreply@anthropic.com
Summary by cubic
Fix CI by resolving TypeScript errors, the VPS readiness check, and auth lifecycle bugs. Dev error panels and monitoring hooks work in Vite, profile/permission checks are reliable, Supabase OAuth redirects work, production builds ship without sourcemaps, all edge/Deno imports pin
@supabase/supabase-js@2.49.1, and DB maintenance migrations improve query performance with corrected realtime publication schemas.Bug Fixes
fromMocknow accepts(..._args: unknown[]).build.target: "es2020"andsourcemaponly in development.SupabaseClientinstead ofReturnType<typeof createClient>in the public API.import.meta.env.DEVin bothErrorBoundaryandContactErrorBoundaryfor dev-only details (Vite-compatible).useMonitoringusesimport.meta.env.DEVfor dev logs and slow-render warnings.AuthProvideralways resetsfetchingRef(try/finally) and before session events;ProtectedRouteresets permission state on user change and fixes HOC typing withComponentType..envvalidation anddetectSessionInUrl: trueto support OAuth/magic links.evolution_webhook_events_wpp2, drop 9 unused/duplicate indexes, ensureconversations.contact_idandevolution_conversationsindexes (contact_id,status+assigned_to), and audit cron/realtime publication with corrected schemas.Dependencies
@supabase/supabase-jsimports to2.49.1viaesm.sh, including shared handlers and Deno tests.Written for commit 99f5e3a. Summary will update on new commits.
Summary by CodeRabbit
Chores
Tests