npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mitra-sdk

v1.0.58

Published

SDK completo para a plataforma Mitra

Readme

Mitra SDK

SDK completo para a plataforma Mitra. Inclui todos os métodos do mitra-interactions-sdk e serviços adicionais.

Instalação

npm install mitra-sdk

Configuração

Configure o SDK com seu token da plataforma Mitra.

Importante: O token é um JWT de autenticação da plataforma Mitra. Nunca deixe o token estático no código. Utilize variáveis de ambiente para armazená-lo de forma segura.

import { configureSdkMitra } from 'mitra-sdk';

configureSdkMitra({
  baseURL: process.env.MITRA_BASE_URL || 'https://api.mitra.com',
  token: process.env.MITRA_TOKEN!
});

Exemplo de .env:

MITRA_BASE_URL=https://api.mitra.com
MITRA_TOKEN=seu-jwt-token-da-plataforma-mitra

Métodos incluídos do mitra-interactions-sdk

  • executeServerFunctionMitra({ projectId, serverFunctionId, input? })ExecuteServerFunctionResponse - Executa Server Function (síncrono, timeout 60s)
  • executeServerFunctionAsyncMitra({ projectId, serverFunctionId, input? })ExecuteServerFunctionAsyncResponse - Executa Server Function (assíncrono, retorna executionId)
  • stopServerFunctionExecutionMitra({ projectId, executionId })StopServerFunctionExecutionResponse - Para execução de Server Function
  • setFileStatusMitra({ projectId, fileName, targetPath }) - Move arquivo para PUBLIC/LOADABLE
  • listRecordsMitra({ projectId, tableName, page?, size?, filters?, jdbcConnectionConfigId? }) - Lista registros (Dynamic Schema CRUD)
  • getRecordMitra({ projectId, tableName, id, jdbcConnectionConfigId? }) - Busca registro por ID
  • createRecordMitra({ projectId, tableName, data, jdbcConnectionConfigId? }) - Cria registro
  • updateRecordMitra({ projectId, tableName, id, data, jdbcConnectionConfigId? }) - Atualiza registro (PUT)
  • patchRecordMitra({ projectId, tableName, id, data, jdbcConnectionConfigId? }) - Atualiza parcialmente (PATCH)
  • deleteRecordMitra({ projectId, tableName, id, jdbcConnectionConfigId? }) - Remove registro
  • createRecordsBatchMitra({ projectId, tableName, records, jdbcConnectionConfigId? }) - Cria múltiplos registros
  • uploadFilePublicMitra({ projectId, file, debug? })UploadFileResponse - Upload de arquivo para pasta PUBLIC (multipart/form-data)
  • uploadFileLoadableMitra({ projectId, file, debug? })UploadFileResponse - Upload de arquivo para pasta LOADABLE (multipart/form-data)
  • listIntegrationsMitra({ projectId? })IntegrationResponse[] - Lista integrações configuradas no projeto

Para exemplos detalhados destes métodos, consulte a documentação do mitra-interactions-sdk.

Métodos do Mitra SDK

Navegação

  • listWorkspacesMitra()ListWorkspacesResponse - Lista workspaces
  • listProjectsMitra({ workspaceId })ListProjectsResponse - Lista projetos de um workspace
  • createProjectMitra({ workspaceId, name, description? })CreateProjectResponse - Cria um projeto
  • getProjectContextMitra({ projectId })GetProjectContextResponse - Detalhes e inventário de um projeto
import { listWorkspacesMitra, listProjectsMitra } from 'mitra-sdk';

const workspaces = await listWorkspacesMitra();
// { status, result: [{ id, name }] }

const projects = await listProjectsMitra({ workspaceId: 1 });
// { status, workspaceId, result: [{ id, name }] }

JDBC

  • listJdbcConnectionsMitra({ projectId })ListJdbcConnectionsResponse - Lista conexões JDBC
  • createJdbcConnectionMitra({ projectId, name, type, host, port, database, user, password })CreateJdbcConnectionResponse - Cria conexão
  • updateJdbcConnectionMitra({ projectId, jdbcId, name, type, host, port, database, user, password })UpdateJdbcConnectionResponse - Atualiza conexão
import { createJdbcConnectionMitra } from 'mitra-sdk';

const result = await createJdbcConnectionMitra({
  projectId: 123,
  name: 'Meu Banco',
  type: 'PostgreSQL',
  host: 'localhost',
  port: 5432,
  database: 'mydb',
  user: 'admin',
  password: 'senha123'
});
// { status, result: { jdbcId, message }, paramsApplied: {...} }

SQL

  • runQueryMitra({ projectId, sql, jdbcId? })RunQueryResponse - Executa query SELECT (somente leitura)
  • runDdlMitra({ projectId, sql, jdbcId? })RunDdlResponse - Executa DDL (CREATE, ALTER, DROP)
  • runDmlMitra({ projectId, sql, jdbcId? })RunDmlResponse - Executa DML (INSERT, UPDATE, DELETE)
  • createOnlineTableMitra({ projectId, jdbcId, name, sqlQuery })CreateOnlineTableResponse - Cria online table
  • updateOnlineTableMitra({ projectId, tableName, sqlQuery })UpdateOnlineTableResponse - Atualiza online table
import { runQueryMitra, runDdlMitra, runDmlMitra } from 'mitra-sdk';

// SELECT (somente leitura)
const result = await runQueryMitra({ projectId: 123, sql: 'SELECT * FROM users' });
// { status, result: { rows: [...], rowCount } }

await runDdlMitra({ projectId: 123, sql: 'CREATE TABLE users (id INT, name VARCHAR(100))' });
// { status, result: { message } }

await runDmlMitra({ projectId: 123, sql: "INSERT INTO users VALUES (1, 'João')" });
// { status, result: { rowsAffected, message } }

Arquivos

  • listProjectFilesMitra({ projectId })ListProjectFilesResponse - Lista arquivos do projeto (CHAT, PUBLIC, LOADABLE)
  • getFilePreviewMitra({ projectId, fileName, maxLines? })GetFilePreviewResponse - Preview de arquivo (CSV, texto, imagem)
import { listProjectFilesMitra, getFilePreviewMitra } from 'mitra-sdk';

const files = await listProjectFilesMitra({ projectId: 123 });
// { status, result: [{ name, size, path, threadId? }] }

const preview = await getFilePreviewMitra({ projectId: 123, fileName: 'dados.csv', maxLines: 10 });
// { status, result: { fileName, type, preview?, totalLinesInFile?, message } }

Tabelas

  • listTablesMitra({ projectId })ListTablesResponse - Lista tabelas físicas com colunas e tipos
  • listOnlineTablesMitra({ projectId })ListOnlineTablesResponse - Lista tabelas online (QueryAlias) com queries
import { listTablesMitra, listOnlineTablesMitra } from 'mitra-sdk';

const tables = await listTablesMitra({ projectId: 123 });
// { status, result: [{ name, columns: [{ name, type, isPk, nullable }] }] }

const onlineTables = await listOnlineTablesMitra({ projectId: 123 });
// { status, result: [{ id, projectId, jdbcId, name, sqlQuery, columns }] }

Data Loaders

  • listDataLoadersMitra({ projectId })ListDataLoadersResponse - Lista rotinas de importação
  • createDataLoaderMitra({ projectId, jdbcId, query, name, runWhenCreate? })CreateDataLoaderResponse - Cria Data Loader (SQL)
  • updateDataLoaderMitra({ projectId, dataLoaderId, jdbcId?, query?, name?, runWhenCreate? })UpdateDataLoaderResponse - Atualiza Data Loader
  • executeDataLoaderMitra({ projectId, dataLoaderId })ExecuteDataLoaderResponse - Executa Data Loader
  • deleteDataLoaderMitra({ projectId, dataLoaderId })DeleteDataLoaderResponse - Remove Data Loader
import { createDataLoaderMitra, executeDataLoaderMitra } from 'mitra-sdk';

const loader = await createDataLoaderMitra({
  projectId: 123,
  jdbcId: 1,
  query: 'SELECT * FROM vendas_externas',
  name: 'Vendas Externas',
  runWhenCreate: true
});
// { status, result: { dataLoaderId, tableName, message, executionLog? } }

await executeDataLoaderMitra({ projectId: 123, dataLoaderId: 1 });
// { status, result: { dataLoaderId, executionLog: { timestamp, rowCount, query, status, ... }, message } }

Usuários

  • listProjectUsersMitra({ projectId })ListProjectUsersResponse - Lista usuários do projeto
  • manageUserAccessMitra({ projectId, email, action, type? })ManageUserAccessResponse - Convida, remove ou altera tipo de acesso
import { listProjectUsersMitra, manageUserAccessMitra } from 'mitra-sdk';

const users = await listProjectUsersMitra({ projectId: 123 });
// { status, result: [{ userId, name, email, profile, userType }] }

// Convidar usuário
await manageUserAccessMitra({ projectId: 123, email: '[email protected]', action: 'INVITE', type: 'dev' });

// Remover usuário
await manageUserAccessMitra({ projectId: 123, email: '[email protected]', action: 'REMOVE' });

// Alterar tipo de acesso
await manageUserAccessMitra({ projectId: 123, email: '[email protected]', action: 'CHANGE_TYPE', type: 'business' });
// { status, result: { email, message, oldType?, newType? } }

Configurações do Projeto

  • updateProjectSettingsMitra({ projectId, name?, color?, icon?, allowPublicUpload? })UpdateProjectSettingsResponse - Atualiza configurações
  • updateAdditionalInstructionsMitra({ projectId, instructions })UpdateAdditionalInstructionsResponse - Atualiza instruções adicionais de IA
  • updateAdditionalBusinessInstructionsMitra({ projectId, instructions })UpdateAdditionalInstructionsResponse - Atualiza instruções adicionais de IA para Business
import { updateProjectSettingsMitra, updateAdditionalInstructionsMitra, updateAdditionalBusinessInstructionsMitra } from 'mitra-sdk';

await updateProjectSettingsMitra({
  projectId: 123,
  name: 'Meu Projeto',
  color: '#4F46E5',
  icon: 'BarChart',
  allowPublicUpload: true
});
// { status, result: { projectId, message } }

// Instruções adicionais de IA (dev)
await updateAdditionalInstructionsMitra({
  projectId: 123,
  instructions: 'Sempre responda em português. Use tabelas quando possível.'
});
// { status, result: { projectId, message } }

// Instruções adicionais de IA (business)
await updateAdditionalBusinessInstructionsMitra({
  projectId: 123,
  instructions: 'Foque em relatórios de vendas e métricas de performance.'
});
// { status, result: { projectId, message } }

Server Functions

  • listServerFunctionsMitra({ projectId })ListServerFunctionsResponse - Lista Server Functions (inclui cronExpression se configurado)
  • readServerFunctionMitra({ projectId, serverFunctionId })ReadServerFunctionResponse - Detalhes de uma Server Function (inclui cronExpression e cronInputJson)
  • createServerFunctionMitra({ projectId, name, code, description?, type?, jdbcId?, cronExpression?, cronInputJson? })CreateServerFunctionResponse - Cria Server Function (com cron opcional)
  • updateServerFunctionMitra({ projectId, serverFunctionId, name?, code?, description?, type?, jdbcId?, cronExpression?, cronInputJson? })UpdateServerFunctionResponse - Atualiza Server Function (com cron opcional)
  • deleteServerFunctionMitra({ projectId, serverFunctionId })DeleteServerFunctionResponse - Remove Server Function
  • getServerFunctionExecutionMitra({ projectId, executionId })GetServerFunctionExecutionResponse - Consulta resultado de execução
  • togglePublicExecutionMitra({ projectId, serverFunctionId, publicExecution })TogglePublicExecutionResponse - Ativa/desativa execução pública (sem auth) de uma Server Function

Nota: Para executar uma Server Function, use executeServerFunctionMitra do mitra-interactions-sdk.

import { listServerFunctionsMitra, readServerFunctionMitra, createServerFunctionMitra, updateServerFunctionMitra, togglePublicExecutionMitra } from 'mitra-sdk';

// Listar Server Functions
const functions = await listServerFunctionsMitra({ projectId: 123 });
// { status, result: [{ id, name, description, type, jdbcId, cronExpression? }] }

// Ler detalhes (incluindo código e cron)
const fn = await readServerFunctionMitra({ projectId: 123, serverFunctionId: 1 });
// { status, result: { id, name, description, code, type, jdbcId, cronExpression?, cronInputJson?, createdBy, createdAt, updatedAt } }

// Criar Server Function com cron (executa a cada 30 minutos)
const result = await createServerFunctionMitra({
  projectId: 123,
  name: 'sincronizarDados',
  code: 'return syncData(input);',
  description: 'Sincroniza dados periodicamente',
  cronExpression: '0 */30 * * * *',
  cronInputJson: { source: 'erp', mode: 'incremental' }
});
// { status, result: { serverFunctionId } }

// Ativar execução pública (sem autenticação)
await togglePublicExecutionMitra({
  projectId: 123,
  serverFunctionId: 1,
  publicExecution: true
});
// { status: "success", result: { serverFunctionId: 1, publicExecution: true } }

// Criar Server Function SQL (usa jdbcId)
const sqlFn = await createServerFunctionMitra({
  projectId: 123,
  name: 'buscarClientes',
  code: 'SELECT * FROM clientes WHERE ativo = 1',
  type: 'SQL',
  jdbcId: 1
});
// { status, result: { serverFunctionId } }

// Remover cron de uma Server Function
await updateServerFunctionMitra({
  projectId: 123,
  serverFunctionId: result.result.serverFunctionId,
  cronExpression: null
});

Navegação (getProjects)

  • getProjectsMitra()GetProjectsResponse - Lista todos os workspaces e projetos do usuário
import { getProjectsMitra } from 'mitra-sdk';

const projects = await getProjectsMitra();
// { status, result: [{ id, name, projects: [{ id, name, accessType }] }] }

Profiles

  • listProfilesMitra({ projectId })ListProfilesResponse - Lista perfis do projeto
  • getProfileDetailsMitra({ projectId, profileId })GetProfileDetailsResponse - Detalhes de um perfil (usuários, tabelas, ações, telas, server functions)
  • createProfileMitra({ projectId, name })CreateProfileResponse - Cria perfil
  • updateProfileMitra({ projectId, profileId, name })UpdateProfileResponse - Atualiza nome do perfil
  • deleteProfileMitra({ projectId, profileId })DeleteProfileResponse - Remove perfil
  • setProfileUsersMitra({ projectId, profileId, userIds?, emails? })SetProfileUsersResponse - Define usuários do perfil (ao menos um de userIds ou emails)
  • setProfileSelectTablesMitra({ projectId, profileId, jdbcConnectionConfigId?, tables })SetProfilePermissionResponse - Define tabelas de leitura (SELECT)
  • setProfileScreensMitra({ projectId, profileId, screenIds })SetProfilePermissionResponse - Define telas permitidas
  • setProfileServerFunctionsMitra({ projectId, profileId, serverFunctionIds })SetProfilePermissionResponse - Define server functions permitidas
import {
  listProfilesMitra,
  getProfileDetailsMitra,
  createProfileMitra,
  setProfileUsersMitra,
  setProfileSelectTablesMitra
} from 'mitra-sdk';

// Listar perfis
const profiles = await listProfilesMitra({ projectId: 123 });
// { status, result: [{ id, name }] }

// Criar perfil
const created = await createProfileMitra({ projectId: 123, name: 'Vendas' });
// { status, result: { id, name, message } }

// Definir usuários (por ID e/ou email)
await setProfileUsersMitra({
  projectId: 123,
  profileId: created.result.id,
  userIds: [1, 2],
  emails: ['[email protected]']
});
// { status, result: { profileId, userCount, message, emailsNotFound? } }

// Definir tabelas de leitura
await setProfileSelectTablesMitra({
  projectId: 123,
  profileId: created.result.id,
  jdbcConnectionConfigId: 1,   // Opcional — ID da conexão JDBC (default: banco principal)
  tables: [
    { tableName: 'clientes' },
    { tableName: 'vendas_externas' }
  ]
});
// { status, result: { profileId, message } }

// Detalhes completos
const details = await getProfileDetailsMitra({ projectId: 123, profileId: created.result.id });
// { status, result: { id, name, users: [...], selectTables: [...], dmlTables: [...], actions: [...], screens: [...], serverFunctions: [...] } }

Email

  • sendEmailMitra({ projectId, to, subject, body })SendEmailResponse - Envia email
import { sendEmailMitra } from 'mitra-sdk';

await sendEmailMitra({
  projectId: 123,
  to: ['[email protected]'],
  subject: 'Relatório Diário',
  body: '<h1>Relatório</h1><p>Segue o relatório do dia.</p>'
});
// { status, projectId, executionTime, result: { message, recipientCount } }

Integrações (Gerenciamento)

  • listIntegrationTemplatesMitra()ConnectorTemplateResponse[] - Lista templates de conectores disponíveis
  • getIntegrationTemplateMitra({ templateId })ConnectorTemplateResponse - Detalhes de um template
  • createIntegrationMitra({ projectId?, name, slug, blueprintId?, blueprintType, authType, credentials, authorizationConfig?, authenticationConfig? })IntegrationResponse - Cria integração (com template ou custom)
  • testIntegrationMitra({ blueprintId, credentials, testEndpoint? })TestConnectionResponse - Testa credenciais antes de salvar
  • testIntegrationByIdMitra({ integrationId })TestConnectionResponse - Testa integração já salva (atualiza status)
import {
  listIntegrationTemplatesMitra,
  getIntegrationTemplateMitra,
  createIntegrationMitra,
  testIntegrationMitra,
  testIntegrationByIdMitra
} from 'mitra-sdk';

// Listar templates disponíveis
const templates = await listIntegrationTemplatesMitra();
// ConnectorTemplateResponse[] — [{ id, name, logo, authStrategy, fieldsSchema, docUrl, testEndpoint, custom, active, createdAt, updatedAt }]

// Detalhes de um template
const template = await getIntegrationTemplateMitra({ templateId: 'hubspot' });

// Testar credenciais antes de criar
const test = await testIntegrationMitra({
  blueprintId: 'hubspot',
  credentials: { apiKey: 'xxx' },
  testEndpoint: '/crm/v3/objects/contacts'
});
// { success: true, message: 'OK', statusCode: 200 }

// Criar integração com template
const integration = await createIntegrationMitra({
  projectId: 123,
  name: 'HubSpot Produção',
  slug: 'hubspot-prod',
  blueprintId: 'hubspot',
  blueprintType: 'REST',
  authType: 'API_KEY',
  credentials: { apiKey: 'xxx' }
});

// Testar integração já salva (atualiza status connected/error)
const result = await testIntegrationByIdMitra({
  integrationId: integration.id
});
// { success: true, message: 'Conexao estabelecida com sucesso.', statusCode: 200 }

// Criar integração custom (sem template)
const custom = await createIntegrationMitra({
  projectId: 123,
  name: 'OpenAI',
  slug: 'openai',
  blueprintId: null,
  blueprintType: 'HTTP_REQUEST',
  authType: 'STATIC_KEY',
  credentials: { base_url: 'https://api.openai.com/v1', api_key: 'sk-...' },
  authorizationConfig: {
    type: 'header',
    config: [{ name: 'Authorization', value: 'Bearer {{api_key}}' }]
  }
});

Cloudflare Tunnel

  • createTunnelMitra({ alias })CloudflareTunnel - Cria túnel
  • listTunnelsMitra({ updateStatus? })CloudflareTunnel[] - Lista túneis do workspace
  • getTunnelMitra({ id, updateStatus? })CloudflareTunnel - Consulta túnel por ID
  • syncTunnelStatusMitra({ id })CloudflareTunnel - Sincroniza status completo (túnel + rotas)
  • syncTunnelProcessStatusMitra({ id })CloudflareTunnel - Sincroniza status do processo do túnel
  • updateTunnelAliasMitra({ id, alias })CloudflareTunnel - Atualiza apelido do túnel
  • deleteTunnelMitra({ id })void - Exclui túnel e todos os recursos associados
  • getTunnelRouteMitra({ routeId })CloudflareTunnelRoute - Consulta rota
  • addTunnelRouteMitra({ tunnelId, alias, internalDbUrl, internalDbPort })CloudflareTunnelRoute - Adiciona rota ao túnel
  • updateTunnelRouteMitra({ id, alias?, url?, port? })CloudflareTunnelRoute - Atualiza rota
  • syncTunnelRouteStatusMitra({ routeId })CloudflareTunnelRoute - Sincroniza status da rota
  • removeTunnelRouteMitra({ routeId })void - Remove rota
  • activateTunnelMitra({ id })void - Ativa túnel e inicia processos cloudflared
  • deactivateTunnelMitra({ id })void - Desativa túnel e encerra processos
  • stopTunnelMitra({ id })void - Para túnel (sem alterar flag enabled)
import { createTunnelMitra, addTunnelRouteMitra, listTunnelsMitra, syncTunnelStatusMitra } from 'mitra-sdk';

// Criar túnel
const tunnel = await createTunnelMitra({ alias: 'meu-workspace-producao' });
// { id, tunnelName, alias, tunnelToken, status: "pending", routes: [], ... }

// Adicionar rota (banco de dados do cliente)
const route = await addTunnelRouteMitra({
  tunnelId: tunnel.id,
  alias: 'banco-producao',
  internalDbUrl: '192.168.1.10',
  internalDbPort: 3306
});
// { id, hostname, routeStatus: "PENDING", processStatus: "STARTING", ... }

// Listar túneis com status atualizado
const tunnels = await listTunnelsMitra({ updateStatus: true });

// Sincronizar status completo
const updated = await syncTunnelStatusMitra({ id: tunnel.id });
// { status: "healthy", routes: [{ routeStatus: "RUNNING", processStatus: "RUNNING", ... }] }

Deploy / Pull (S3)

  • deployToS3Mitra({ projectId, workspaceId, file })DeployToS3Response - Upload de projeto (tar.gz) para S3
  • pullFromS3Mitra({ projectId, workspaceId })Blob - Download do código fonte (src/) como tar.gz

Licença

MIT