JavaScript Python PHP
async function executar(values) {
async function compareInfraFiles(v) {
const endings = infraChoice(v.endings, ['Exatos', 'Normalizar para LF']);
const input = infraText(v.input), target = infraText(v.target);
if ([input, target].some(value => value.split(/\r\n|\r|\n/).length > 5000))
throw new Error('Limite de 5 mil linhas por lado.');
const normalize = (value) => endings === 'Normalizar para LF' ? value.replace(/\r\n?/g, '\n') : value;
const { structuredPatch, formatPatch } = await import('diff');
const patch = structuredPatch('origem.txt', 'destino.txt', normalize(input), normalize(target), '', '', { context: 3, timeout: 1500, maxEditLength: 2000 });
if (!patch)
throw new Error('Comparação interrompida: excedeu 1,5 segundo ou 2 mil edições. Reduza os arquivos.');
if (!patch.hunks.length)
return { text: 'Sem diferenças.' };
const rows = [];
for (const hunk of patch.hunks) {
rows.push({ type: 'heading', text: `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@` });
for (const line of hunk.lines)
rows.push({ type: line.startsWith('+') ? 'added' : line.startsWith('-') ? 'removed' : 'context', text: line });
}
const text = formatPatch(patch);
return { text, rows, files: [{ name: 'comparacao.diff', content: text }], notes: ['Adições têm +; remoções têm −. Uma substituição aparece como remoção e adição. Espaços e finais de linha seguem a opção escolhida.'] };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} caracteres.`);
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) || /[\uD800-\uDFFF]/u.test(value))
throw new Error('Há caracteres de controle ou Unicode inválidos na entrada.');
return value;
}
function infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
for (const value of Object.values(values)) infraText(value);
const output = await compareInfraFiles(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm abaixo; a implementação completa está visível.
source = r'''
async function executar(values) {
async function compareInfraFiles(v) {
const endings = infraChoice(v.endings, ['Exatos', 'Normalizar para LF']);
const input = infraText(v.input), target = infraText(v.target);
if ([input, target].some(value => value.split(/\r\n|\r|\n/).length > 5000))
throw new Error('Limite de 5 mil linhas por lado.');
const normalize = (value) => endings === 'Normalizar para LF' ? value.replace(/\r\n?/g, '\n') : value;
const { structuredPatch, formatPatch } = await import('diff');
const patch = structuredPatch('origem.txt', 'destino.txt', normalize(input), normalize(target), '', '', { context: 3, timeout: 1500, maxEditLength: 2000 });
if (!patch)
throw new Error('Comparação interrompida: excedeu 1,5 segundo ou 2 mil edições. Reduza os arquivos.');
if (!patch.hunks.length)
return { text: 'Sem diferenças.' };
const rows = [];
for (const hunk of patch.hunks) {
rows.push({ type: 'heading', text: `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@` });
for (const line of hunk.lines)
rows.push({ type: line.startsWith('+') ? 'added' : line.startsWith('-') ? 'removed' : 'context', text: line });
}
const text = formatPatch(patch);
return { text, rows, files: [{ name: 'comparacao.diff', content: text }], notes: ['Adições têm +; remoções têm −. Uma substituição aparece como remoção e adição. Espaços e finais de linha seguem a opção escolhida.'] };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} caracteres.`);
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) || /[\uD800-\uDFFF]/u.test(value))
throw new Error('Há caracteres de controle ou Unicode inválidos na entrada.');
return value;
}
function infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
for (const value of Object.values(values)) infraText(value);
const output = await compareInfraFiles(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:await executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
'''
process = subprocess.run(["node", "--input-type=module", "-e", source], input=json.dumps(values, ensure_ascii=True), capture_output=True, text=True, timeout=15, check=True)
response = json.loads(process.stdout)
if not response["ok"]:
raise ValueError(response["error"])
return response["result"]
<?php
function executar(array $values): array {
// Requer Node.js 22+ e os pacotes npm abaixo; a implementação completa está visível.
$source = <<<'JAVASCRIPT'
async function executar(values) {
async function compareInfraFiles(v) {
const endings = infraChoice(v.endings, ['Exatos', 'Normalizar para LF']);
const input = infraText(v.input), target = infraText(v.target);
if ([input, target].some(value => value.split(/\r\n|\r|\n/).length > 5000))
throw new Error('Limite de 5 mil linhas por lado.');
const normalize = (value) => endings === 'Normalizar para LF' ? value.replace(/\r\n?/g, '\n') : value;
const { structuredPatch, formatPatch } = await import('diff');
const patch = structuredPatch('origem.txt', 'destino.txt', normalize(input), normalize(target), '', '', { context: 3, timeout: 1500, maxEditLength: 2000 });
if (!patch)
throw new Error('Comparação interrompida: excedeu 1,5 segundo ou 2 mil edições. Reduza os arquivos.');
if (!patch.hunks.length)
return { text: 'Sem diferenças.' };
const rows = [];
for (const hunk of patch.hunks) {
rows.push({ type: 'heading', text: `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@` });
for (const line of hunk.lines)
rows.push({ type: line.startsWith('+') ? 'added' : line.startsWith('-') ? 'removed' : 'context', text: line });
}
const text = formatPatch(patch);
return { text, rows, files: [{ name: 'comparacao.diff', content: text }], notes: ['Adições têm +; remoções têm −. Uma substituição aparece como remoção e adição. Espaços e finais de linha seguem a opção escolhida.'] };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} caracteres.`);
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) || /[\uD800-\uDFFF]/u.test(value))
throw new Error('Há caracteres de controle ou Unicode inválidos na entrada.');
return value;
}
function infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
for (const value of Object.values(values)) infraText(value);
const output = await compareInfraFiles(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:await executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
JAVASCRIPT;
$payload = json_encode($values, JSON_THROW_ON_ERROR);
$process = proc_open(["node", "--input-type=module", "-e", $source], [["pipe", "r"], ["pipe", "w"], ["pipe", "w"]], $pipes);
if (!is_resource($process)) throw new RuntimeException("Não foi possível iniciar Node.js.");
$offset = 0; while ($offset < strlen($payload)) { $n = fwrite($pipes[0], substr($payload, $offset)); if ($n === false || $n === 0) { proc_terminate($process); foreach ($pipes as $pipe) fclose($pipe); proc_close($process); throw new RuntimeException("Falha ao enviar a entrada."); } $offset += $n; }
fclose($pipes[0]); stream_set_timeout($pipes[1], 15); $output = stream_get_contents($pipes[1]); $timeout = stream_get_meta_data($pipes[1])["timed_out"]; fclose($pipes[1]); if ($timeout) proc_terminate($process); stream_get_contents($pipes[2]); fclose($pipes[2]); $status = proc_close($process);
if ($timeout || $status !== 0) throw new RuntimeException("Falha técnica ou timeout no Node.js; confira as dependências npm.");
$response = json_decode($output, true, 512, JSON_THROW_ON_ERROR); if (!$response["ok"]) throw new InvalidArgumentException($response["error"]);
return $response["result"];
}