### Local Installation Script - Full Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Installs all NFeWizard-io packages into a specified test project directory, simulating a complete local setup. ```bash ./scripts/local-install.sh ~/seu-projeto-teste ``` -------------------------------- ### NFeWizard-io Program Startup Notice Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/LICENSE.txt This is an example of a short notice displayed when the NFeWizard-io program starts in interactive mode. It informs users about the lack of warranty and redistribution conditions. ```text NFeWizard-io Copyright (C) 2024 Marco Aurélio Silva Lima This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### NFeWizard-io Usage Example Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/nfewizard-io/README.md Example demonstrating how to instantiate and initialize NFeWizard, including configuration for DFe distribution, NFe environment, email, and library settings. It also shows an example of distributing DFe by NFe key. ```typescript import NFeWizard from 'nfewizard-io'; // Instanciar const nfeWizard = new NFeWizard(); // Inicializar await nfeWizard.NFE_LoadEnvironment({ config: { dfe: { baixarXMLDistribuicao: true, pathXMLDistribuicao: "tmp/DistribuicaoDFe", armazenarXMLAutorizacao: true, pathXMLAutorizacao: "tmp/Autorizacao", armazenarXMLRetorno: true, pathXMLRetorno: "tmp/RequestLogs", armazenarXMLConsulta: true, pathXMLConsulta: "tmp/RequestLogs", armazenarXMLConsultaComTagSoap: false, armazenarRetornoEmJSON: false, pathRetornoEmJSON: "tmp/DistribuicaoDFe", pathCertificado: "certificado.pfx", senhaCertificado: "1234", UF: "SP", CPFCNPJ: "99999999999999", }, nfe: { ambiente: 2, versaoDF: "4.00", idCSC: 1, tokenCSC: '99999999-9999-9999-9999-999999999999' }, email: { host: 'mail.provider.com.br', port: 465, secure: true, auth: { user: 'nfe.example@email.com.br', pass: '123456' }, emailParams: { from: 'Company ', to: 'customer.name@email.com.br', } }, lib: { connection: { timeout: 30000, }, log: { exibirLogNoConsole: true, armazenarLogs: true, pathLogs: 'tmp/Logs' }, useOpenSSL: false, useForSchemaValidation: 'validateSchemaJsBased', } } }); // Exemplo de Distribuição DFe por Chave const chaveNFe: DFePorChaveNFe = { cUFAutor: 35, CNPJ: '99999999999999', consChNFe: { chNFe: '00000000000000000000000000000000000000000000' }, } await nfeWizard.NFE_DistribuicaoDFePorChave(chaveNFe); ``` -------------------------------- ### Local Installation Script - Single Package Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Installs a single specified NFeWizard-io package and its dependencies into a test project, mimicking a standard npm install. ```bash # Test only NFe ./scripts/local-install-single.sh nfewizard-io ~/seu-projeto-teste # Test only NFCe ./scripts/local-install-single.sh @nfewizard/nfce ~/seu-projeto-teste # Test only CTe ./scripts/local-install-single.sh @nfewizard/cte ~/seu-projeto-teste # Test only DANFE ./scripts/local-install-single.sh @nfewizard/danfe ~/seu-projeto-teste ``` -------------------------------- ### Minimal Test Example Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md A basic JavaScript example demonstrating how to load environment settings and query the SEFAZ service status using NFeWizard. ```javascript import NFeWizard from 'nfewizard-io'; const nfe = new NFeWizard(); await nfe.NFE_LoadEnvironment({ dfe: { pathCertificado: 'certificado.pfx', senhaCertificado: '1234', ambiente: 2 // Homologação } }); const resultado = await nfe.NFE_ConsultaStatusServico({ cUF: 35, // São Paulo tpAmb: 2 // Homologação }); console.log('Status SEFAZ:', resultado.retornoSOAP.xMotivo); ``` -------------------------------- ### Install @nfewizard/danfe Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/danfe/README.md Install the library using npm or pnpm. ```bash npm install @nfewizard/danfe # ou pnpm add @nfewizard/danfe ``` -------------------------------- ### Install All Modules Locally Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/README.md Use this script to perform a full installation of all monorepo modules for local testing. It simulates installing packages into a specified test project directory. ```bash ./scripts/local-install.sh ~/seu-projeto-teste ``` -------------------------------- ### Install @nfewizard/danfe and its dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md When installing `@nfewizard/danfe`, the script ensures that `@nfewizard/types` is also installed. ```bash ./scripts/local-install-single.sh @nfewizard/danfe ~/projeto ``` -------------------------------- ### Install Single Module Locally Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/README.md This script allows for the installation of a single module from the monorepo, simulating a specific package installation. Useful for testing individual components. ```bash # Testar apenas NFe ./scripts/local-install-single.sh nfewizard-io ~/seu-projeto-teste ``` ```bash # Testar apenas NFCe ./scripts/local-install-single.sh @nfewizard/nfce ~/seu-projeto-teste ``` ```bash # Testar apenas CTe ./scripts/local-install-single.sh @nfewizard/cte ~/seu-projeto-teste ``` -------------------------------- ### Install @nfewizard/cte Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/cte/EXEMPLO-USO.md Install the @nfewizard/cte package using pnpm. ```bash pnpm add @nfewizard/cte ``` -------------------------------- ### Complete CTe Consultation Example Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/cte/EXEMPLO-USO.md A comprehensive example demonstrating the full workflow: initializing CTeWizard, loading the environment, and querying CTe documents by the last NSU. Includes error handling. ```typescript import CTeWizard from '@nfewizard/cte'; async function consultarCTe() { const CTeWizard = new CTeWizard(); try { // 1. Carregar ambiente await CTeWizard.NFE_LoadEnvironment({ config: { nfe: { ambiente: 2, pathXMLDistribuicao: 'tmp/XMLs/CTe', baixarXMLDistribuicao: true, armazenarRetornoEmJSON: true }, certificado: { pathCertificado: 'certificado.pfx', senhaCertificado: '1234' } } }); // 2. Consultar CTe por último NSU const resultado = await CTeWizard.CTE_DistribuicaoDFePorUltNSU({ cUFAutor: 35, CNPJ: '12345678901234', distNSU: { ultNSU: '000000000000000' } }); console.log('Status:', resultado.data.retDistDFeInt.cStat); console.log('Motivo:', resultado.xMotivo); console.log('Arquivos:', resultado.filesList); return resultado; } catch (error) { console.error('Erro ao consultar CTe:', error); throw error; } } consultarCTe(); ``` -------------------------------- ### Install @nfewizard/cte dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/cte/README.md Install the required packages using npm or pnpm. ```bash npm install @nfewizard/cte @nfewizard/types # ou pnpm add @nfewizard/cte @nfewizard/types ``` -------------------------------- ### Install pnpm and Project Dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Installs pnpm globally if not already present, then installs all monorepo dependencies using pnpm. ```bash # Install pnpm globally (if you don't have it yet) npm install -g pnpm # Install all monorepo dependencies pnpm install ``` -------------------------------- ### Local Installation Scripts Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Scripts for testing local package installations. ```bash # Instalar todos os pacotes localmente para teste ./scripts/local-install.sh ~/seu-projeto-teste # Instalar apenas um pacote ./scripts/local-install-single.sh @nfewizard/nfce ~/seu-projeto-teste ``` -------------------------------- ### Initialize NFeWizard with Configuration Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Example of initializing the NFeWizard class with configuration for environment, company details, and certificate. ```javascript import { NFeWizard } from 'nfewizard-io'; const config = { nfe: { ambiente: 2, // 1=Production, 2=Homologation UF: 'SP', razaoSocial: 'Empresa Teste LTDA', CNPJ: '12345678000190', // ... other configurations }, certificate: { pfxPath: './certificado.pfx', pfxPassword: 'senha123', }, }; async function testar() { try { const nfe = new NFeWizard(config); console.log('NFeWizard initialized successfully!'); } catch (error) { console.error('Error initializing:', error); } } testar(); ``` -------------------------------- ### Run Full Local Installation Script Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Execute the `local-install.sh` script to test all modules of the nfewizard-io library. This script installs all packages including types, shared, danfe, nfce, cte, and nfewizard-io. ```bash ./scripts/local-install.sh ~/Documents/projetos/NFeWizard/Testes/NFeWizard ``` -------------------------------- ### Install @nfewizard/types Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/types/README.md Commands to install the package using npm or pnpm. ```bash npm install @nfewizard/types # ou pnpm add @nfewizard/types ``` -------------------------------- ### Run Single Package Local Installation Script Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Use `local-install-single.sh` to simulate `npm install ` for a specific nfewizard package. Specify the package name and the destination directory. ```bash ./scripts/local-install-single.sh ``` ```bash ./scripts/local-install-single.sh nfewizard-io ~/meu-projeto ``` ```bash ./scripts/local-install-single.sh @nfewizard/nfce ~/meu-projeto ``` ```bash ./scripts/local-install-single.sh @nfewizard/cte ~/meu-projeto ``` ```bash ./scripts/local-install-single.sh @nfewizard/danfe ~/meu-projeto ``` -------------------------------- ### Log Example Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/nfse/README.md Example of a structured log entry for NFSe authorization errors. ```jsonl {"context":"NFSE_Autorizacao","error":{"message":"Rejeição: Consumo Indevido",...} ``` -------------------------------- ### Install @nfewizard/cte and its dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md The installation of `@nfewizard/cte` includes `@nfewizard/types` and `@nfewizard/shared` as automatic dependencies. ```bash ./scripts/local-install-single.sh @nfewizard/cte ~/projeto ``` -------------------------------- ### Import Library Modules Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Examples of importing the main library or specific sub-packages. ```javascript // Código existente continua funcionando import { NFeWizard } from 'nfewizard-io'; ``` ```javascript // Usar apenas NFCe import { NFCEAutorizacao } from '@nfewizard/nfce'; ``` -------------------------------- ### Install @nfewizard/nfce and its dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Installing the `@nfewizard/nfce` package also brings in `@nfewizard/types` and `@nfewizard/shared` automatically. ```bash ./scripts/local-install-single.sh @nfewizard/nfce ~/projeto ``` -------------------------------- ### Sample Console Logs Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Example output format for development console logs. ```text 2025-06-27 00:48:22 info: [Logger] Logger inicializado com sucesso {"config":{"console":true}} 2025-06-27 00:48:22 http: [BaseNFE][NFEConsultaProtocolo] Iniciando comunicação {"url":"https://..."} 2025-06-27 00:48:22 error: [XmlParser] Erro ao converter XML {"error":"Formato desconhecido"} ``` -------------------------------- ### JSONL Log File Examples Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Examples of structured JSONL log entries for application, error, and HTTP logs. ```jsonl {"level":"info","message":"Inicializando ambiente","timestamp":"2025-06-27T00:48:22.720Z","context":"Environment"} {"level":"warn","message":"Certificado expira em 30 dias","timestamp":"2025-06-27T00:48:23.120Z","context":"Certificate"} ``` ```jsonl {"level":"error","message":"Erro na conversão XML","timestamp":"2025-06-27T00:48:22.928Z","context":"XmlParser","error":{"message":"Formato inválido","stack":"..."}} ``` ```jsonl {"level":"http","message":"Requisição iniciada","timestamp":"2025-06-27T00:48:22.771Z","context":"BaseNFE","url":"https://nfe.sefaz.sp.gov.br/ws","duration":"150ms"} ``` -------------------------------- ### Install nFEwizard-io and its dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md When installing `nfewizard-io`, the script automatically includes its core dependencies: `@nfewizard/types`, `@nfewizard/shared`, and `@nfewizard/danfe`. ```bash ./scripts/local-install-single.sh nfewizard-io ~/projeto ``` -------------------------------- ### Project tsconfig.json Example Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/README.md Example tsconfig.json for a project that imports NFEWizard.IO. This configuration enables source maps and other essential options for development. ```json { "compilerOptions": { "target": "es2020", "module": "nodenext", "outDir": "dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "sourceMap": true, "inlineSources": true, "inlineSourceMap": false, "declaration": true, "declarationMap": true, "moduleResolution": "nodenext" } } ``` -------------------------------- ### Install NFeWizard-io Package Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/nfewizard-io/README.md Install the main NFeWizard package using npm. This package handles core NFe operations. ```bash npm install nfewizard-io ``` -------------------------------- ### Install @nfewizard/nfse Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/nfse/README.md Use npm or pnpm to add the @nfewizard/nfse library to your project. ```bash npm install @nfewizard/nfse # ou pnpm add @nfewizard/nfse ``` -------------------------------- ### Log Format Example Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/danfe/README.md Example of a relevant log entry format for debugging issues related to DANFE generation. ```json {"context":"DANFE_NFe","error":{"message":"Erro ao gerar PDF",...} ``` -------------------------------- ### Verify NFeWizard Package Installation Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Use these commands to check if the NFeWizard packages are correctly installed in your project's node_modules directory. ```bash ls -la ~/projeto-teste/node_modules/@nfewizard/ ``` ```bash ls -la ~/projeto-teste/node_modules/nfewizard-io/ ``` -------------------------------- ### Usage of NFeWizard-io (Legacy) Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Example usage of the monolithic package before modularization. ```typescript import NFeWizard from 'nfewizard-io'; const nfeWizard = new NFeWizard(); // NFe await nfeWizard.NFE_Autorizacao(nfeData); // NFCe await nfeWizard.NFCE_Autorizacao(nfceData); // DANFE import { NFEGerarDanfe } from 'nfewizard-io'; await NFEGerarDanfe({ xml: nfeXml }); ``` -------------------------------- ### Install C++ Compilers for Native Modules Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md If you encounter 'bindings file not found' errors for libxmljs2, you may need to install C++ build tools. These commands are for Linux and macOS. ```bash # Linux sudo apt install build-essential # macOS xcode-select --install ``` -------------------------------- ### Install External Dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md This command installs essential external dependencies required for the nfewizard library, including packages like axios, libxmljs2, and pdfkit. It also handles the compilation of native modules and sets up the .npmrc file for build scripts. ```bash pnpm add axios libxmljs2 xml2js pdfkit qrcode ... ``` -------------------------------- ### Install NFCe Module Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/README.md To use services related to NFCe, install the dedicated module. This allows for a more optimized bundle size by including only necessary services. ```typescript npm i @nfewizard-io/nfce ``` -------------------------------- ### Usage Case: NFe Only Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Installation and usage for NFe-only projects. ```bash npm install nfewizard-io ``` ```typescript import NFeWizard from 'nfewizard-io'; // Operações NFe funcionam sem alterações // ⚠️ DANFE removido - use @nfewizard/danfe separadamente // ⚠️ NFCe removido - use @nfewizard/nfce separadamente // ⚠️ CTe removido - use @nfewizard/cte separadamente // ℹ️ NFS-e - @nfewizard/nfse (novo módulo, não existia antes) ``` -------------------------------- ### Usage Case: NFCe Only Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Installation and usage for NFCe-only projects. ```bash npm install @nfewizard/nfce ``` ```typescript import NFCeWizard from '@nfewizard/nfce'; const nfceWizard = new NFCeWizard(); await nfceWizard.NFE_LoadEnvironment({ config }); await nfceWizard.NFCE_Autorizacao(nfceData); ``` -------------------------------- ### Create and Test a New Project Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Steps to create a new test project, add the local NFeWizard-io package, and create an `index.js` file to test initialization. ```bash mkdir nfewizard-test cd nfewizard-test pnpm init pnpm add ../nfewizard-io/packages/nfewizard-io ``` -------------------------------- ### Instalar um pacote específico Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/scripts/README.md Utilize o script de instalação única para testar um pacote individual e suas dependências. ```bash ./scripts/local-install-single.sh ``` ```bash ./scripts/local-install-single.sh nfewizard-io ~/meu-projeto ``` ```bash ./scripts/local-install-single.sh @nfewizard/nfce ~/meu-projeto ``` ```bash ./scripts/local-install-single.sh @nfewizard/cte ~/meu-projeto ``` ```bash ./scripts/local-install-single.sh @nfewizard/nfse ~/meu-projeto ``` ```bash ./scripts/local-install-single.sh @nfewizard/danfe ~/meu-projeto ``` -------------------------------- ### Testar nfewizard-io localmente Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/README.md Execute estes comandos para testar a instalação local do nfewizard-io em seu projeto. ```bash # Teste completo ../scripts/local-install.sh ~/seu-projeto-teste ``` ```bash # Teste único (simula npm install) ../scripts/local-install-single.sh nfewizard-io ~/seu-projeto-teste ``` -------------------------------- ### Instalar dependências e build Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Comandos para instalar as dependências do projeto e validar a compilação. ```bash # Instalar dependências npm install # Verificar se está tudo funcionando npm run build:rp ``` -------------------------------- ### Initialize NFSe Wizard with Configuration Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/nfse/README.md Instantiate the NFSe class with detailed configuration for DFe, NFSe, and library settings. Ensure correct paths for certificates and logs are provided. ```typescript import NFSe from '@nfewizard/nfse'; import { NFSe as NFSeType } from '@nfewizard/types'; // Instanciar com configuração const nfseWizard = new NFSe({ dfe: { armazenarXMLAutorizacao: true, pathXMLAutorizacao: "tmp/NFSe/Autorizacao", armazenarXMLRetorno: true, pathXMLRetorno: "tmp/NFSe/Retorno", armazenarXMLConsulta: true, pathXMLConsulta: "tmp/NFSe/Consulta", pathCertificado: "certificado.pfx", senhaCertificado: "1234", UF: "SP", CPFCNPJ: "99999999999999", }, nfse: { ambiente: 2, // 1=Produção, 2=Homologação versao: "1.00" }, lib: { connection: { timeout: 30000, }, log: { exibirLogNoConsole: true, armazenarLogs: true, pathLogs: 'tmp/Logs/NFSe' }, useForSchemaValidation: 'validateSchemaJsBased', } }); ``` -------------------------------- ### Initialize CTeWizard and Load Environment Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/cte/EXEMPLO-USO.md Import and initialize the CTeWizard class, then configure the environment with NFe and certificate details. Ensure the correct environment (1 for Production, 2 for Homologation) and paths are set. ```typescript import CTeWizard from '@nfewizard/cte'; const CTeWizard = new CTeWizard(); // Configurar ambiente await CTeWizard.NFE_LoadEnvironment({ config: { nfe: { ambiente: 2, // 1=Produção, 2=Homologação pathXMLDistribuicao: 'tmp/XMLs/CTe', baixarXMLDistribuicao: true, armazenarRetornoEmJSON: true }, certificado: { pathCertificado: 'certificado.pfx', senhaCertificado: '1234' } } }); ``` -------------------------------- ### Development Workflow: Reinstall and Test Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Steps to follow after code changes: edit code, reinstall the package in the test project using local scripts, and then test by running the project. ```bash # 1. Edit the code vim packages/shared/src/adapters/SchemaLoader.ts # 2. Reinstall in the test project (choose one) ./scripts/local-install.sh ~/projeto-teste # Full ./scripts/local-install-single.sh nfewizard-io ~/projeto-teste # Single # 3. Test cd ~/projeto-teste node index.js ``` -------------------------------- ### NFCe Cancellation Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Example of cancelling an NFCe using the @nfewizard/nfce package. ```typescript import NFCeWizard from '@nfewizard/nfce'; const nfceWizard = new NFCeWizard(); await nfceWizard.NFCE_Cancelamento({ idLote: Date.now(), evento: [{ cOrgao: 35, tpAmb: 2, CNPJ: '99999999999999', chNFe: '35000000000000000000000000000000000000000001', dhEvento: new Date().toISOString(), tpEvento: '110111', nSeqEvento: 1, verEvento: '1.00', detEvento: { descEvento: 'Cancelamento', nProt: '135000000000000', xJust: 'Motivo do cancelamento com no mínimo 15 caracteres' } }] }); ``` -------------------------------- ### Usage Case: DANFE Separated Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Installation and usage for generating DANFE documents independently. ```bash npm install @nfewizard/danfe ``` ```typescript import { NFE_GerarDanfe, NFCE_GerarDanfe } from '@nfewizard/danfe'; // DANFE NFe await NFE_GerarDanfe({ data, // Objeto com NFe, protNFe e xml chave, outputPath: './danfe.pdf' }); // DANFE NFCe await NFCE_GerarDanfe({ data, // Objeto com NFe, protNFe e xml chave, outputPath: './nfce-danfe.pdf', pageWidth: 226.772 }); ``` -------------------------------- ### Exemplos de commits convencionais Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Exemplos de mensagens de commit seguindo o padrão Conventional Commits. ```bash # Exemplos de commits git commit -m "feat: adicionar suporte para NFSe" git commit -m "fix: corrigir parsing do XML de retorno" git commit -m "docs: atualizar README com novos exemplos" git commit -m "test: adicionar testes para consulta de protocolo" git commit -m "refactor: melhorar estrutura do BaseNFe" ``` -------------------------------- ### Usage Case: NFe + NFCe Migration Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Installation and usage for projects requiring both NFe and NFCe. ```bash npm install nfewizard-io @nfewizard/nfce ``` ```typescript import NFeWizard from 'nfewizard-io'; import NFCeWizard from '@nfewizard/nfce'; // NFe const nfeWizard = new NFeWizard(); await nfeWizard.NFE_LoadEnvironment({ config }); // NFCe const nfceWizard = new NFCeWizard(); await nfceWizard.NFE_LoadEnvironment({ config }); // Mesma config! ``` -------------------------------- ### Initialize CTeWizard Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/packages/cte/README.md Import the CTeWizard class and initialize the environment with a configuration object. ```typescript import { CTeWizard } from '@nfewizard/cte'; const cteWizard = new CTeWizard(); await cteWizard.CTE_LoadEnvironment({ config }); ``` -------------------------------- ### Development Workflow: Edit, Reinstall, Test Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md A typical development cycle involves editing code in the packages directory, reinstalling the library locally using one of the provided scripts, and then running tests in the target project. ```bash # 1. Edite código vim packages/shared/src/adapters/SchemaLoader.ts # 2. Reinstale localmente (escolha um método) ./scripts/local-install.sh ~/projeto-teste # Completo ./scripts/local-install-single.sh nfewizard-io ~/projeto-teste # Único # 3. Execute teste cd ~/projeto-teste node index.js ``` -------------------------------- ### Verificar instalação e recursos Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/scripts/README.md Comandos para validar a presença de pacotes, certificados, schemas e módulos nativos compilados. ```bash ls -la ~/projeto-teste/node_modules/@nfewizard/ ls -la ~/projeto-teste/node_modules/nfewizard-io/ ``` ```bash ls ~/projeto-teste/node_modules/@nfewizard/shared/resources/certs/ | wc -l # Deve retornar: 335 ``` ```bash ls ~/projeto-teste/node_modules/@nfewizard/shared/resources/schemas/ | wc -l # Deve retornar: 143 ``` ```bash ls ~/projeto-teste/node_modules/.pnpm/libxmljs2@*/node_modules/libxmljs2/build/Release/ # Deve mostrar: xmljs.node ``` -------------------------------- ### Verify CA Certificates Count Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Check the number of CA certificates installed. This helps ensure that all necessary security certificates are present. ```bash ls ~/projeto-teste/node_modules/@nfewizard/shared/resources/certs/ | wc -l # Deve retornar: 335 ``` -------------------------------- ### Workflow de desenvolvimento Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/scripts/README.md Sequência de comandos para aplicar alterações no código da biblioteca e reinstalar para testes. ```bash # 1. Edite o código vim packages/shared/src/adapters/SchemaLoader.ts # 2. Reinstale (escolha um): ./scripts/local-install.sh ~/projeto-teste # Completo ./scripts/local-install-single.sh nfewizard-io ~/projeto-teste # Único # 3. Teste cd ~/projeto-teste node index.js ``` -------------------------------- ### Build All Packages in Monorepo Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Executes a full build for all packages in the monorepo, recommended after cloning the repository. Alternatively, uses turbo for cached and parallel builds. ```bash # Full build (recommended after cloning the repository) pnpm run build # Or using turbo (with cache and parallelization) pnpm turbo build ``` -------------------------------- ### Package Size Comparison Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Comparison of bundle sizes between the monolithic package and modularized approach. ```bash nfewizard-io: 19.1 MB (descompactado) ``` ```bash # Apenas NFe nfewizard-io + @nfewizard/types + @nfewizard/shared: Compactado: 963.3 KB | Descompactado: 4.37 MB # Apenas NFCe @nfewizard/nfce + @nfewizard/types + @nfewizard/shared: Compactado: 1.06 MB | Descompactado: 4.84 MB # NFe + DANFE nfewizard-io + @nfewizard/danfe + @nfewizard/types + @nfewizard/shared: Compactado: 2.03 MB | Descompactado: 6.66 MB # NFe + NFCe + DANFE nfewizard-io + @nfewizard/nfce + @nfewizard/danfe + @nfewizard/types + @nfewizard/shared: Compactado: 2.23 MB | Descompactado: 7.63 MB # Todos os pacotes (incluindo NFS-e - novo módulo) TOTAL: Compactado: 2.37 MB | Descompactado: 8.36 MB ``` -------------------------------- ### Execute Local Test Script Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Navigate to the test project directory and run the test script using Node.js. ```bash cd ~/projeto-teste node test.js ``` -------------------------------- ### Configurar certificado digital Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Comandos para preparar o diretório de certificados e copiar o arquivo .pfx. ```bash # Crie um diretório para seu certificados mkdir -p certificados # Copie seu certificado .pfx para o diretório cp /caminho/para/seu/certificado.pfx ./certificado.pfx # Informe o caminho para o certificado no método de inicialização da lib (NFE_LoadEnvironment config -> dfe -> pathCertificado) ``` -------------------------------- ### Limpar cache e reinstalar dependências Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Sequência de comandos para resolver erros de declaração de tipos limpando o cache e reinstalando os módulos. ```bash npm cache clean --force rm -rf node_modules package-lock.json npm install ``` -------------------------------- ### Manage Dependencies Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Commands to add dependencies to the root workspace or specific packages. ```bash # Adicionar ao workspace root pnpm add -w # Adicionar a pacote específico pnpm --filter @nfewizard/shared add # Adicionar dependência de desenvolvimento pnpm --filter @nfewizard/types add -D ``` -------------------------------- ### Execute Test Script Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/scripts/README.md Command to run the previously created JavaScript test file using Node.js. ```bash node test.js ``` -------------------------------- ### Publish Packages Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Commands to publish packages to the npm registry. ```bash # Publicar todos os pacotes (requer permissões npm) pnpm publish -r --access public # Publicar pacote específico cd packages/nfewizard-io pnpm publish --access public ``` -------------------------------- ### Analyze Package Size and Structure Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Commands to inspect the disk usage and file structure of compiled packages. ```bash # Ver tamanho dos pacotes compilados du -sh packages/*/dist/ # Ver estrutura de arquivos tree packages/nfewizard-io/dist -L 2 ``` -------------------------------- ### Configure Logging System Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Define log behavior and storage paths within the library configuration. ```typescript lib: { log: { exibirLogNoConsole: true, // Mostrar logs no console armazenarLogs: true, // Salvar logs em arquivos pathLogs: 'tmp/Logs' // Diretório dos logs } } ``` -------------------------------- ### Instalar módulo NFCe Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Comando para instalar o pacote @nfewizard/nfce quando o módulo não é encontrado. ```bash npm install @nfewizard/nfce ``` -------------------------------- ### Configure NFeWizard Test Environment Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Initialize the NFeWizard instance with certificate and environment credentials in src/debug.ts. ```typescript // Edite o arquivo src/debug.ts const nfeWizard = new NFeWizard(); await nfeWizard.NFE_LoadEnvironment({ config: { dfe: { // ... outras configurações pathCertificado: "certificado.pfx", senhaCertificado: "SUA_SENHA", UF: "SP", // Sua UF CPFCNPJ: "SEU_CNPJ", // Seu CNPJ }, // ... outras configurações } }); ``` -------------------------------- ### Project Directory Structure Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Overview of the project file organization. ```text src/ ├── adapters/ # Adaptadores principais da API ├── core/ # Funcionalidades centrais │ ├── exceptions/ # Sistema de logs e erros │ └── utils/ # Utilitários gerais ├── modules/ # Módulos da NFe │ └── dfe/ │ ├── base/ # Classes base │ ├── nfe/ # Implementações NFe │ └── nfce/ # Implementações NFCe ├── types/ # Definições TypeScript ├── debug.ts # Arquivo para debug/desenvolvimento ``` -------------------------------- ### Enable Watch Mode Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Command to trigger automatic recompilation upon file changes. ```bash # Observar mudanças e recompilar automaticamente pnpm --filter @nfewizard/shared build -- --watch ``` -------------------------------- ### Configuration Structure Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/BREAKING_CHANGES.md Standard configuration object compatible with all modules. ```typescript const config = { dfe: { pathCertificado: "certificado.pfx", senhaCertificado: "1234", UF: "SP", CPFCNPJ: "99999999999999", // ... mesmas propriedades }, nfe: { ambiente: 2, versaoDF: "4.00", // ... mesmas propriedades }, nfce: { ambiente: 2, versaoDF: "4.00", idCSC: 1, tokenCSC: 'token', // ... mesmas propriedades }, lib: { useForSchemaValidation: 'validateSchemaJsBased', // ... mesmas propriedades } }; ``` -------------------------------- ### Troubleshoot Common Errors Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Commands to resolve module resolution issues, cache conflicts, or build failures. ```bash # Rebuild do pacote types pnpm --filter @nfewizard/types build ``` ```bash # Limpar cache do turbo e rebuildar rm -rf .turbo pnpm run clean pnpm run build ``` ```bash # Limpar store do pnpm e reinstalar pnpm store prune rm -rf node_modules pnpm install ``` -------------------------------- ### NFeWizard-io Copyright Notice for Source Files Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/LICENSE.txt This is the standard copyright notice to be included at the beginning of each source file in the NFeWizard-io project. It specifies the licensing terms under the GNU General Public License. ```text NFeWizard-io Copyright (C) 2024 Marco Aurélio Silva Lima This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` -------------------------------- ### Build Packages Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Executes the build process for the nfewizard packages. This command compiles TypeScript code into JavaScript, generates TypeScript definition files (.d.ts), and creates both ESM and CJS bundles. ```bash pnpm build ``` -------------------------------- ### Consulta CT-e por NSU Específico Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/DOCS_CTE.md Busca documentos CT-e a partir de um NSU específico. Certifique-se de ter inicializado o ambiente com NFE_LoadEnvironment(). ```typescript import CTeWizard from '@nfewizard/cte'; import { DFePorNSUCTe } from 'nfewizard-io'; const nfeWizard = new CTeWizard(); // Inicializar ambiente (veja README.md para configuração completa) await nfeWizard.NFE_LoadEnvironment({ config: { /* ... */ } }); // Consultar CT-e por NSU específico const NSUCTe: DFePorNSUCTe = { cUFAutor: 41, // Código da UF do autor CNPJ: '99999999999999', // CNPJ do interessado consNSU: { NSU: '000000000000001' // NSU específico a consultar } }; await nfeWizard.CTE_DistribuicaoDFePorNSU(NSUCTe); ``` -------------------------------- ### VS Code Debug Configuration Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/README.md Configure your VS Code launch.json to enable step-through debugging of NFeWizard IO methods. Ensure source maps are enabled and outFiles are correctly set. ```json { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Debug NFe Wizard", "skipFiles": [ "/**" ], "program": "${workspaceFolder}/src/testes.ts", "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx", "runtimeArgs": [], "console": "integratedTerminal", "env": { "NODE_ENV": "development" }, "sourceMaps": true, "restart": true, "protocol": "inspector", "outFiles": [ "${workspaceFolder}/**/*.js" ] }, { "type": "node", "request": "launch", "name": "Debug com ts-node", "skipFiles": [ "/**" ], "program": "${workspaceFolder}/src/testes.ts", "runtimeArgs": [ "--loader", "ts-node/esm" ], "console": "integratedTerminal", "env": { "NODE_ENV": "development", "NODE_OPTIONS": "--loader ts-node/esm" }, "sourceMaps": true } ] } ``` -------------------------------- ### Commit Changes Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/INSTALACAO_LOCAL.md Stage all modified files and commit them with a descriptive message. This is a standard step before versioning or publishing. ```bash git add . git commit -m "feat: implementação X" ``` -------------------------------- ### Build Individual Packages Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/examples/BUILD.md Builds a specific package within the monorepo using the pnpm filter command. ```bash # Build of a specific package pnpm --filter @nfewizard/types build pnpm --filter @nfewizard/shared build pnpm --filter @nfewizard/danfe build pnpm --filter @nfewizard/nfce build pnpm --filter @nfewizard/cte build pnpm --filter nfewizard-io build ``` -------------------------------- ### Analyze Logs via CLI Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/CONTRIBUTING.md Use standard shell commands to filter and inspect JSONL log files. ```bash # Ver últimas 50 linhas do log de aplicação tail -50 tmp/Logs/app.jsonl # Filtrar apenas erros de um contexto específico grep '"context":"XmlParser"' tmp/Logs/error.jsonl # Ver requisições HTTP que demoraram mais de 1 segundo grep -E '"duration":"[2-9][0-9]{3}ms"' tmp/Logs/http.jsonl ``` -------------------------------- ### Importação de Tipos CT-e Source: https://github.com/nfewizard-org/nfewizard-io/blob/master/DOCS_CTE.md Importa os tipos de dados necessários para trabalhar com a distribuição de CT-e na biblioteca NFeWizard-io. ```typescript // Importação dos tipos import { DFePorNSUCTe, DFePorUltimoNSUCTe, ConsultaCTe } from 'nfewizard-io'; ```