Markdown Converter
Agent skill for markdown-converter
These instructions are for AI assistants working in this project.
Sign in to like and favorite skills
These instructions are for AI assistants working in this project.
Always open
@/openspec/AGENTS.md when the request:
Use
@/openspec/AGENTS.md to learn:
Keep this managed block so 'openspec update' can refresh the instructions.
Meta: Modernizar completamente o SDK NFE.io de JavaScript/callbacks para TypeScript moderno com geração automática a partir de OpenAPI, mantendo compatibilidade funcional.
whenBaseResource.extend() pattern[email protected] (desatualizado)api.nfe.io/v1/src/generated/ - É auto-gerado e será sobrescritonpm run typecheck && npm run lint && npm testany no TypeScript - Use tipos explícitos ou unknownclient-nodejs/ # nfe-io - Core SDK ├── openapi/ │ ├── spec/ │ │ └── nfe-api.json # ⚠️ SOURCE OF TRUTH - OpenAPI spec │ └── generator-config.yaml # Configuração do gerador │ ├── src/ │ ├── core/ # ✏️ Core SDK implementation │ │ ├── client.ts # NfeClient principal │ │ ├── types.ts # TypeScript types completos │ │ ├── errors/ # Sistema de erros │ │ │ └── index.ts │ │ ├── http/ # HTTP client layer │ │ │ └── client.ts │ │ └── resources/ # API Resources │ │ ├── companies.ts │ │ ├── service-invoices.ts │ │ ├── legal-people.ts │ │ ├── natural-people.ts │ │ └── webhooks.ts │ │ │ └── index.ts # Public API exports │ ├── scripts/ │ ├── download-openapi.ts # Download spec da API │ └── validate-spec.ts # Valida OpenAPI spec │ ├── tests/ │ ├── unit/ # Testes unitários │ ├── integration/ # Testes de integração │ └── setup.ts # Test setup │ ├── examples/ # Exemplos de uso │ ├── basic-usage-esm.js │ └── basic-usage-cjs.cjs │ ├── docs/ # Documentação ├── .github/workflows/ # CI/CD pipelines │ ├── package.json ├── tsconfig.json ├── tsup.config.ts ├── vitest.config.ts ├── CONTRIBUTING.md # Guidelines para extensões └── README.md NOTA: Adaptadores MCP e n8n foram movidos para repositórios separados: - @nfe-io/mcp-server (https://github.com/nfe/mcp-server) - @nfe-io/n8n-nodes (https://github.com/nfe/n8n-nodes)
# Criar estrutura base mkdir -p nfe-io-sdk-v3/{openapi/spec,src/{generated,client,runtime,errors,utils},scripts,tests,examples} cd nfe-io-sdk-v3 # Inicializar projeto npm init -y # Instalar dependências essenciais npm install --save-dev \ typescript@^5.3.0 \ tsup@^8.0.0 \ tsx@^4.7.0 \ vitest@^1.0.0 \ @vitest/coverage-v8 \ eslint@^8.56.0 \ prettier@^3.2.0 \ openapi-typescript@^6.7.0 npm install zod@^3.22.0 # Criar configurações base cat > tsconfig.json << 'EOF' { "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "bundler", "declaration": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true } } EOF cat > package.json << 'EOF' { "name": "nfe-io", "version": "3.0.0-beta.1", "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "download-spec": "tsx scripts/download-openapi.ts", "validate-spec": "tsx scripts/validate-spec.ts", "generate": "tsx scripts/generate-sdk.ts", "build": "npm run generate && tsup", "test": "vitest", "lint": "eslint src --ext .ts", "typecheck": "tsc --noEmit" } } EOF
# 1. Atualizar OpenAPI spec npm run download-spec npm run validate-spec # 2. Gerar código npm run generate # 3. Implementar código handwritten # Edite arquivos em src/client/, src/runtime/, etc. # 4. Escrever testes # Crie testes em tests/unit/ ou tests/integration/ # 5. Validar qualidade npm run typecheck # DEVE passar npm run lint # DEVE passar npm test # DEVE passar npm run build # DEVE gerar dist/ # 6. Commit git add . git commit -m "feat: implementa X"
# Checklist obrigatório ✅ npm run typecheck # Zero erros ✅ npm run lint # Zero warnings ✅ npm test # 100% passing ✅ npm run build # Build sucesso ✅ git diff # Revisar mudanças ✅ CHANGELOG.md # Atualizado se necessário
Objetivo: Projeto TypeScript funcional + geração de código básica
Tarefas:
✅ Inicializar projeto TypeScript moderno
✅ Obter OpenAPI Spec
scripts/download-openapi.tsscripts/validate-spec.ts✅ Geração inicial de código
openapi-typescript para gerar typesscripts/generate-sdk.tsValidação:
npm run download-spec # Spec baixado ou criado manualmente npm run validate-spec # Spec válido npm run generate # Código gerado npm run typecheck # Zero erros
Objetivo: HTTP client funcional com retry e rate limiting
Tarefas:
✅ HTTP Client (
src/runtime/http-client.ts)
✅ Retry Logic (
src/runtime/retry.ts)
✅ Sistema de Erros (
src/errors/)
✅ Rate Limiter (
src/runtime/rate-limiter.ts)
Validação:
npm test tests/unit/runtime/ # Todos passando npm run typecheck # Zero erros
Objetivo: Recursos principais do SDK completos e funcionais
Tarefas em ordem:
✅ NfeClient principal (
src/core/client.ts)
✅ ServiceInvoices (
src/core/resources/service-invoices.ts)
✅ Companies (
src/core/resources/companies.ts)
⏳ LegalPeople (
src/core/resources/legal-people.ts)
⏳ NaturalPeople (
src/core/resources/natural-people.ts)
⏳ Webhooks (
src/core/resources/webhooks.ts)
Validação:
npm test tests/integration/ # Todos passando npm run build # Exports corretos
Exemplo de uso esperado:
const nfe = new NfeClient({ apiKey: 'xxx' }); const result = await nfe.serviceInvoices.create('company-id', data); if (result.status === 'pending') { const invoice = await result.waitForCompletion(); }
Tarefas:
⏳ Preparar SDK para extensibilidade
⏳ Testes unitários completos
⏳ Testes de integração com MSW
⏳ Documentação completa
Tarefas:
⏳ CI/CD Pipeline
⏳ NPM Publish Setup
⏳ Final polish
Validação:
npm test -- --coverage # Coverage > 80% npm run docs # Docs geradas
{ "name": "nfe-io", "version": "3.0.0-beta.1", "description": "Official NFe.io SDK for Node.js 18+", "main": "./dist/index.js", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { ".": { "require": "./dist/index.js", "import": "./dist/index.mjs", "types": "./dist/index.d.ts" } }, "engines": { "node": ">=18.0.0" }, "scripts": { "download-spec": "tsx scripts/download-openapi.ts", "validate-spec": "tsx scripts/validate-spec.ts", "generate": "tsx scripts/generate-sdk.ts", "build": "npm run generate && tsup", "test": "vitest", "test:coverage": "vitest --coverage", "lint": "eslint src --ext .ts", "format": "prettier --write 'src/**/*.ts'", "typecheck": "tsc --noEmit", "prepublishOnly": "npm run build && npm test" }, "keywords": ["nfe", "nfse", "nota-fiscal", "invoice", "brazil"], "author": "NFE.io", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/nfe/client-nodejs.git" } }
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "lib": ["ES2020"], "moduleResolution": "bundler", "declaration": true, "declarationMap": true, "sourceMap": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", "**/*.spec.ts", "**/*.test.ts"] }
import { defineConfig } from 'tsup'; export default defineConfig({ entry: ['src/index.ts'], format: ['cjs', 'esm'], dts: true, splitting: false, sourcemap: true, clean: true, treeshake: true, minify: true, external: [], // Zero dependencies });
Problema: NFE.io pode não ter spec OpenAPI público
Solução:
curl https://api.nfe.io/openapi.jsonEstrutura mínima do spec:
openapi: 3.0.0 info: title: NFE.io API version: 1.0.0 servers: - url: https://api.nfe.io/v1 paths: /companies/{company_id}/serviceinvoices: post: operationId: createServiceInvoice # ... parameters, requestBody, responses
Problema: Node 18 não tem FormData nativo compatível
Solução:
npm install form-data@^4.0.0
import FormData from 'form-data'; // Em Companies.uploadCertificate() const form = new FormData(); form.append('file', fileBuffer, 'certificate.pfx'); form.append('password', password);
Problema: Download de PDF/XML requer streaming
Solução:
async downloadPDF(companyId: string, invoiceId: string): Promise<Buffer> { const response = await this.http.request<Response>( `/companies/${companyId}/serviceinvoices/${invoiceId}/pdf`, { headers: { Accept: 'application/pdf' } } ); const arrayBuffer = await response.arrayBuffer(); return Buffer.from(arrayBuffer); }
npm run typecheck passanpm run build gera dist/const nfe = new NfeClient({ apiKey }) funcionaawait nfe.serviceInvoices.create() funciona<type>(<scope>): <description> [optional body] [optional footer]
Types:
feat: Nova featurefix: Bug fixdocs: Documentaçãotest: Testesrefactor: Refatoraçãochore: ManutençãoExemplos:
git commit -m "feat(client): adiciona NfeClient com configuração de environment" git commit -m "fix(retry): corrige exponential backoff com jitter" git commit -m "docs(readme): adiciona exemplos de uso básico" git commit -m "test(invoices): adiciona testes de integração para create"
✅ Setup inicial do projeto ✅ Geração de código do OpenAPI ✅ Implementação de resources seguindo padrões ✅ Escrita de testes unitários ✅ Configuração de CI/CD ✅ Geração de documentação
❌ OpenAPI spec não encontrado (precisa ser criado manualmente) ❌ Decisões de breaking changes na API pública ❌ Credenciais para testes E2E ou publicação NPM ❌ Validação final antes do release
Após CADA arquivo criado/modificado:
npm run typecheck && npm run lint && npm test
Se qualquer comando falhar, PARE e corrija antes de continuar.
O SDK NFE.io v3 foi projetado para ser extensível. As seguintes extensões oficiais estão em repositórios separados:
Model Context Protocol Server para integração com LLMs
nfe-io internamentenpm install @nfe-io/mcp-servernfe-io (peer dependency)Custom nodes n8n para automação de workflows
npm install @nfe-io/n8n-nodesnfe-io (dependency)Veja CONTRIBUTING.md para guidelines sobre como criar extensões usando o SDK.
Boa implementação! 🚀