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

@chicane-ai/core

v1.0.0

Published

Core da ferramenta Chicane para proteção de IA

Downloads

6

Readme

@chicane-ai/core

Core da ferramenta Chicane para proteção de IA. Fornece a base para criação de validadores e sistemas de proteção para aplicações de inteligência artificial.

🚀 Instalação

npm install @chicane-ai/core

🎯 Uso Básico

import { SafetyCar, OnFailAction } from '@chicane-ai/core';

// Criar uma instância do SafetyCar
const chicane = new SafetyCar();

// Adicionar validadores
chicane.use(validator, options, OnFailAction.EXCEPTION);

// Validar dados
const result = chicane.validate(data);

📦 Componentes Principais

SafetyCar

A classe principal para gerenciar validadores e executar validações.

import { SafetyCar } from '@chicane-ai/core';

const chicane = new SafetyCar();

// Adicionar um validador
chicane.use(validator, options, onFailAction);

// Adicionar múltiplos validadores
chicane.useMany(
  { validator: validator1, config: config1 },
  { validator: validator2, config: config2 }
);

// Validar dados
const result = chicane.validate(data);

// Limpar validadores
chicane.clear();

// Obter configuração atual
const config = chicane.getConfig();

OnFailAction

Enum que define as ações a serem tomadas quando uma validação falha:

  • EXCEPTION: Lança uma exceção
  • FIX: Tenta corrigir o valor automaticamente
  • FILTER: Remove o valor inválido (retorna null)
  • REFRAIN: Coleta os erros mas não interrompe o fluxo
import { OnFailAction } from '@chicane-ai/core';

// Exemplo de uso
chicane.use(validator, options, OnFailAction.EXCEPTION);

BoxValidator

Interface que todos os validadores devem implementar:

import { BoxValidator, ValidationResult } from '@chicane-ai/core';

class MeuValidador implements BoxValidator {
  name = 'MeuValidador';

  validate(value: any, options?: any): ValidationResult {
    // Implementar lógica de validação
    if (/* condição válida */) {
      return { valid: true };
    } else {
      return {
        valid: false,
        errors: ['Mensagem de erro']
      };
    }
  }
}

ValidationResult

Interface que define o resultado de uma validação:

interface ValidationResult {
  valid: boolean;           // Se a validação passou
  errors?: string[];        // Lista de erros (se houver)
  fixedValue?: any;         // Valor corrigido (se aplicável)
}

🔧 Exemplos

Validação Básica

import { SafetyCar, OnFailAction } from '@chicane-ai/core';

const chicane = new SafetyCar();

// Validar dados
try {
  const result = chicane.validate("dados para validar");
  console.log("Validação passou:", result.valid);
} catch (error) {
  console.error("Validação falhou:", error.message);
}

Múltiplos Validadores

import { SafetyCar, OnFailAction } from '@chicane-ai/core';

const chicane = new SafetyCar()
  .use(validator1, options1, OnFailAction.REFRAIN)
  .use(validator2, options2, OnFailAction.EXCEPTION);

const result = chicane.validate(data);

Validação com Bandeira Verde (Green Flag)

import { SafetyCar } from '@chicane-ai/core';

const chicane = new SafetyCar();

// Validar e executar callback apenas se passar (Bandeira Verde)
const result = await chicane.greenFlag(
  data,
  async (validatedData) => {
    // Este callback só é executado se a validação passar
    return await llmApi.generateResponse("prompt", validatedData);
  }
);

Validação com Callbacks de Sucesso e Erro

const result = await chicane.validateWithCallbacks(
  data,
  // Callback de sucesso
  async (validatedData) => {
    return await llmApi.generateResponse("prompt", validatedData);
  },
  // Callback de erro (opcional)
  async (errors) => {
    console.log("Validação falhou:", errors);
    return "Dados inválidos";
  }
);

🏗️ Arquitetura

O core do Chicane é projetado para ser:

  • Modular: Cada validador é independente
  • Extensível: Fácil adição de novos validadores
  • Flexível: Múltiplas ações de falha
  • Type-safe: Totalmente tipado com TypeScript

📦 Boxes Disponíveis

  • @chicane-ai/box-regex-match: Validação com expressões regulares
  • @chicane-ai/box-json-validation: Validação de JSON e schemas

🤝 Contribuindo

Para contribuir com o core:

  1. Fork o repositório
  2. Crie uma branch para sua feature
  3. Implemente suas mudanças
  4. Adicione testes
  5. Abra um Pull Request

📄 Licença

MIT License

🔗 Links