UNPKG

cnj-validate

Version:

Biblioteca TypeScript para validação e análise de números de processos em conformidade com o CNJ (Conselho Nacional de Justiça) do Brasil

137 lines 5.81 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.processFile = processFile; exports.isFileProcessingAvailable = isFileProcessingAvailable; const analyzer_1 = require("../core/analyzer"); const processor_1 = require("./processor"); /** * Processa arquivo CNJ e gera arquivo de saída * * ⚠️ ATENÇÃO: Esta função funciona apenas no Node.js (servidor) * Não pode ser usada em ambientes browser/frontend * * @param inputFilePath Caminho do arquivo de entrada * @param outputFilePath Caminho do arquivo de saída (opcional) * @param options Opções de processamento * @returns Resultado do processamento com estatísticas */ async function processFile(inputFilePath, outputFilePath, options = {}) { // Verificação de ambiente if (typeof globalThis !== 'undefined' && 'window' in globalThis) { throw new Error('processFile() só funciona no Node.js. Use processCSV() para ambientes browser.'); } const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const path = await Promise.resolve().then(() => __importStar(require('path'))); // Extrai opções com valores padrão const { separator = ',', includeHeader = true, encoding = 'utf8' } = options; // Usa performance.now() se disponível para maior precisão const startTime = typeof performance !== 'undefined' ? performance.now() : Date.now(); // Lê o arquivo de entrada usando encoding especificado const fileContent = await fs.readFile(inputFilePath, encoding); // Processa o conteúdo usando a função existente const processingResult = (0, processor_1.processCSV)(fileContent, { separator }); // Processa CNJs para gerar análises completas const lines = fileContent.split('\n').filter((line) => line.trim()); const analyses = []; lines.forEach((line) => { const cnj = line.split(separator)[0]?.trim(); if (cnj) { try { const analysis = (0, analyzer_1.analyzeCNJ)(cnj); analyses.push(analysis); } catch (error) { // Para CNJs com erro, cria análise básica analyses.push({ receivedCNJ: cnj, validCNJ: false, segmentName: 'ERRO', segmentShort: 'ERRO', sourceUnitType: 'ERRO', sourceUnitNumber: '', courtType: 'ERRO', courtNumber: '', detailed: { lawsuitCNJFormat: '', lawsuitNumber: '', verifyingDigit: '', protocolYear: '', segment: '', court: '', sourceUnit: '', argNumber: '', district: '', uf: '', tj: '', }, }); } } }); // Gera arquivo de saída const outputPath = outputFilePath || path.join(path.dirname(inputFilePath), `${path.basename(inputFilePath, path.extname(inputFilePath))}_processed.csv`); const csvOutput = (0, processor_1.generateCSV)(analyses, includeHeader); await fs.writeFile(outputPath, csvOutput, encoding); // Calcula tempo de processamento com a mesma medida usada no início const endTime = typeof performance !== 'undefined' ? performance.now() : Date.now(); const processingTime = Math.max(1, Math.round(endTime - startTime)); // Garante mínimo de 1ms // Prepara estatísticas const statistics = { totalCNJs: processingResult.totalProcessed, validCNJs: processingResult.validCount, invalidCNJs: processingResult.invalidCount, errorCount: processingResult.errors.length, processingTime, }; return { inputFile: inputFilePath, outputFile: outputPath, processingResult, analyses, statistics, }; } /** * Verifica se a funcionalidade de arquivo está disponível * @returns true se funcionalidades de arquivo estão disponíveis (Node.js) */ function isFileProcessingAvailable() { return (typeof globalThis !== 'undefined' && !('window' in globalThis) && typeof process !== 'undefined'); } //# sourceMappingURL=file-processor.js.map