Skip to content
This repository was archived by the owner on Aug 14, 2026. It is now read-only.

fix(ci): CI verde — corrige typecheck (TS2556), vps:check e deno (TS2345) - #150

Open
adm01-debug wants to merge 19 commits into
mainfrom
fix/ci-green-10-10
Open

fix(ci): CI verde — corrige typecheck (TS2556), vps:check e deno (TS2345)#150
adm01-debug wants to merge 19 commits into
mainfrom
fix/ci-green-10-10

Conversation

@adm01-debug

@adm01-debug adm01-debug commented May 20, 2026

Copy link
Copy Markdown
Owner

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 test 241 passed / 0 failed.

  1. typecheck (TS2556)src/lib/__tests__/instanceHealthGate.test.ts
    fromMock era vi.fn(() => …) (sem params) mas chamado com fromMock(...args). Recebe (..._args: unknown[]). Comportamento inalterado (8/8 testes).

  2. vps:checkvite.config.ts
    check-vps-readiness.mjs exige build.target e política de sourcemap. Adicionado target: "es2020" e sourcemap: _env.mode === "development" (dev=on / prod=off — não expõe fonte em produção). Confirmado: build de produção gera 0 sourcemaps.

  3. deno type-check (TS2345)supabase/functions/public-api/index.ts
    A 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 por SupabaseClient (import de tipo) — resolve independe da versão. Import pinado em @2.49.1.

Notas

  • Pin preventivo supabase-js@2@2.49.1: há outros 43 imports @2 nã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.
  • CodeQL: decisão de visibilidade do repo pendente — ver discussão no chat (recomendado ajustar o workflow em vez de tornar o repo público).
  • Dívida latente: 14 outras ocorrências de 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

    • TS2556: test mock fromMock now accepts (..._args: unknown[]).
    • VPS check: Vite build.target: "es2020" and sourcemap only in development.
    • Deno TS2345: use SupabaseClient instead of ReturnType<typeof createClient> in the public API.
    • Error boundaries: use import.meta.env.DEV in both ErrorBoundary and ContactErrorBoundary for dev-only details (Vite-compatible).
    • Monitoring hooks: useMonitoring uses import.meta.env.DEV for dev logs and slow-render warnings.
    • Auth lifecycle: AuthProvider always resets fetchingRef (try/finally) and before session events; ProtectedRoute resets permission state on user change and fixes HOC typing with ComponentType.
    • Supabase client: strict .env validation and detectSessionInUrl: true to support OAuth/magic links.
    • Database health: VACUUM/ANALYZE evolution_webhook_events_wpp2, drop 9 unused/duplicate indexes, ensure conversations.contact_id and evolution_conversations indexes (contact_id, status+assigned_to), and audit cron/realtime publication with corrected schemas.
  • Dependencies

    • Pin all @supabase/supabase-js imports to 2.49.1 via esm.sh, including shared handlers and Deno tests.

Written for commit 99f5e3a. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Chores

    • Padronização de importações do cliente Supabase para uma versão fixa em diversas funções e ajuste de tipagem do cliente.
    • Clarificações na configuração de build relacionadas ao agrupamento de módulos.
  • Tests

    • Ajuste em mocks de testes para aceitar argumentos arbitrários; manutenção da limpeza/verificação de mocks e dos cenários de cache/TTL e idempotência.

Review Change Stack

adm01-debug and others added 2 commits May 20, 2026 09:22
- 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>
Copilot AI review requested due to automatic review settings May 20, 2026 12:27
@vercel

vercel Bot commented May 20, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
zapp-web Ready Ready Preview, Comment Jun 12, 2026 1:10pm

@coderabbitai

coderabbitai Bot commented May 20, 2026

Copy link
Copy Markdown

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Pequenos refinamentos: mock de Supabase no teste aceita args variádicos; tipo SupabaseClient importado e usado na API pública; comentários em vite.config.ts atualizados; vários handlers de edge fixam a versão do cliente Supabase para @supabase/supabase-js@2.49.1.

Changes

Ajustes de tipo e comentários

Layer / File(s) Summary
Ajuste de mock do Supabase no teste
src/lib/__tests__/instanceHealthGate.test.ts
O mock de supabase.from agora aceita argumentos variádicos ((..._args: unknown[])) em vez de uma assinatura sem parâmetros.
Importação e uso de SupabaseClient
supabase/functions/public-api/index.ts
Importação do tipo SupabaseClient adicionada; findMessageByIdempotencyKey usa SupabaseClient como tipo de parâmetro; pequeno ajuste de comentário no bloco de inserção de mensagem.
Comentários de chunking no Vite
vite.config.ts
Comentários descritivos do bloco build.rollupOptions.output.manualChunks atualizados; lógica de chunking inalterada.
Padronizar versão do createClient em Edge Functions
supabase/functions/* (health-check, cleanup-rate-limit-logs, cleanup-storage-orphans, client-observability, get-sip-password, send-email, virustotal-test, whatsapp-cloud-secrets-status, ai-classify-tickets, email-track-link, gmail-tests.test.ts, send-rate-limit-alert, sicoob-bridge-reply, whatsapp-cloud-webhook-verify, e muitos outros handlers listados no diff`)
Importes de createClient atualizados para @supabase/supabase-js@2.49.1 em múltiplas funções; nenhum outro comportamento dessas funções foi alterado.

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed O título descreve com precisão os três problemas corrigidos (TS2556, vps:check e TS2345) e menciona o contexto de CI, alinhado com o resumo do PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ci-green-10-10

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.target e uma política intencional de sourcemap no vite.config.ts para satisfazer o gate vps:check.
  • Corrige o typecheck do Deno na edge function public-api substituindo ReturnType<typeof createClient> por SupabaseClient e pinando o import do supabase-js via esm.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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 tradeoff

Erro de banco pode vazar estrutura de schema.

O msgError.message pode 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

📥 Commits

Reviewing files that changed from the base of the PR and between 755acba and 49dd438.

📒 Files selected for processing (3)
  • src/lib/__tests__/instanceHealthGate.test.ts
  • supabase/functions/public-api/index.ts
  • vite.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";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 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 -5

Repository: 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.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).
@cubic-dev-ai

cubic-dev-ai Bot commented May 20, 2026

Copy link
Copy Markdown

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 @cubic-dev-ai review.

…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.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants