JavaScript Python PHP
import { SaxesParser } from 'saxes';
async function executar(values) {
async function optimizeFrontendSvg(v) {
const input = validateFrontendSvg(v.input);
const precision = feInteger(v.precision, 'Precisão', 0, 6);
feChoice(v.comments, ['Remover', 'Preservar']);
const { optimize } = await import('svgo/browser');
const svg = optimize(input, { floatPrecision: precision, multipass: true, plugins: [{ name: 'preset-default', params: { overrides: { cleanupIds: false, removeComments: v.comments === 'Remover' ? {} : false } } }] }).data;
validateFrontendSvg(svg);
const before = new TextEncoder().encode(input).length, after = new TextEncoder().encode(svg).length;
return { text: svg, images: [{ label: 'Original', svg: input }, { label: 'Otimizado', svg }], meta: { title: `${before} → ${after} bytes`, description: `Redução: ${((1 - after / before) * 100).toFixed(2)}%. Confira a comparação visual.`, url: '' } };
}
function feInteger(value, label, min, max) {
if (!/^-?\d+$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
function feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function validateFrontendSvg(input) {
feText(input);
const tags = new Set(['svg', 'g', 'defs', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan', 'title', 'desc', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'pattern', 'use']);
const attributes = new Set(('xmlns id x y x1 y1 x2 y2 cx cy r rx ry width height viewBox preserveAspectRatio d points transform fill fill-opacity fill-rule stroke stroke-width stroke-opacity stroke-linecap stroke-linejoin stroke-miterlimit stroke-dasharray stroke-dashoffset opacity clip-path clip-rule mask href gradientUnits gradientTransform offset stop-color stop-opacity fx fy fr spreadMethod patternUnits patternContentUnits patternTransform font-size font-family font-weight text-anchor dominant-baseline dx dy rotate textLength lengthAdjust').split(' '));
let depth = 0, nodes = 0, root = '';
const parser = new SaxesParser({ xmlns: false });
parser.on('doctype', () => { throw new Error('DTDs e entidades personalizadas não são aceitos.'); });
parser.on('processinginstruction', () => { throw new Error('Instruções de processamento não são aceitas em SVG.'); });
parser.on('error', error => { throw new Error('SVG inválido: ' + error.message); });
parser.on('opentag', tag => {
if (++nodes > 5000 || ++depth > 64)
throw new Error('SVG excede 5000 elementos ou 64 níveis.');
if (depth === 1)
root = tag.name;
if (!tags.has(tag.name))
throw new Error(`Elemento SVG não suportado: ${tag.name}. Use apenas SVG estático, sem scripts, estilos ou recursos externos.`);
for (const [name, raw] of Object.entries(tag.attributes)) {
const value = String(raw);
if (!attributes.has(name))
throw new Error(`Atributo SVG não suportado: ${name}. Eventos, estilos e namespaces adicionais não são aceitos.`);
if (name === 'xmlns' && value !== 'http://www.w3.org/2000/svg')
throw new Error('Namespace SVG inválido.');
if (name === 'href' && !/^#[A-Za-z_][\w.-]*$/.test(value))
throw new Error('SVG aceita apenas referências internas por #id.');
// Presentation attributes may contain fragment paint servers, never remote URLs.
if (/url\s*\(/i.test(value) && !/^url\(\s*#[A-Za-z_][\w.-]*\s*\)$/.test(value))
throw new Error('Recursos externos ou URLs não suportadas no SVG.');
if (/[\\\u0000-\u001f]/.test(value))
throw new Error('Escape ou controle não suportado em atributo SVG.');
}
});
parser.on('closetag', () => { depth--; });
parser.write(input).close();
if (root !== 'svg')
throw new Error('O elemento raiz deve ser svg.');
return input;
}
function feText(value, max = 100000) {
if (typeof value !== 'string' || value.length > max)
throw new Error(`Use texto com até ${max} 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;
}
for (const value of Object.values(values)) if (typeof value !== "string" || value.length > 100000) throw new Error("Use até 100 mil caracteres por campo.");
return await optimizeFrontendSvg(values);
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm indicados abaixo; toda a lógica está visível.
source = r'''
import { SaxesParser } from 'saxes';
async function executar(values) {
async function optimizeFrontendSvg(v) {
const input = validateFrontendSvg(v.input);
const precision = feInteger(v.precision, 'Precisão', 0, 6);
feChoice(v.comments, ['Remover', 'Preservar']);
const { optimize } = await import('svgo/browser');
const svg = optimize(input, { floatPrecision: precision, multipass: true, plugins: [{ name: 'preset-default', params: { overrides: { cleanupIds: false, removeComments: v.comments === 'Remover' ? {} : false } } }] }).data;
validateFrontendSvg(svg);
const before = new TextEncoder().encode(input).length, after = new TextEncoder().encode(svg).length;
return { text: svg, images: [{ label: 'Original', svg: input }, { label: 'Otimizado', svg }], meta: { title: `${before} → ${after} bytes`, description: `Redução: ${((1 - after / before) * 100).toFixed(2)}%. Confira a comparação visual.`, url: '' } };
}
function feInteger(value, label, min, max) {
if (!/^-?\d+$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
function feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function validateFrontendSvg(input) {
feText(input);
const tags = new Set(['svg', 'g', 'defs', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan', 'title', 'desc', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'pattern', 'use']);
const attributes = new Set(('xmlns id x y x1 y1 x2 y2 cx cy r rx ry width height viewBox preserveAspectRatio d points transform fill fill-opacity fill-rule stroke stroke-width stroke-opacity stroke-linecap stroke-linejoin stroke-miterlimit stroke-dasharray stroke-dashoffset opacity clip-path clip-rule mask href gradientUnits gradientTransform offset stop-color stop-opacity fx fy fr spreadMethod patternUnits patternContentUnits patternTransform font-size font-family font-weight text-anchor dominant-baseline dx dy rotate textLength lengthAdjust').split(' '));
let depth = 0, nodes = 0, root = '';
const parser = new SaxesParser({ xmlns: false });
parser.on('doctype', () => { throw new Error('DTDs e entidades personalizadas não são aceitos.'); });
parser.on('processinginstruction', () => { throw new Error('Instruções de processamento não são aceitas em SVG.'); });
parser.on('error', error => { throw new Error('SVG inválido: ' + error.message); });
parser.on('opentag', tag => {
if (++nodes > 5000 || ++depth > 64)
throw new Error('SVG excede 5000 elementos ou 64 níveis.');
if (depth === 1)
root = tag.name;
if (!tags.has(tag.name))
throw new Error(`Elemento SVG não suportado: ${tag.name}. Use apenas SVG estático, sem scripts, estilos ou recursos externos.`);
for (const [name, raw] of Object.entries(tag.attributes)) {
const value = String(raw);
if (!attributes.has(name))
throw new Error(`Atributo SVG não suportado: ${name}. Eventos, estilos e namespaces adicionais não são aceitos.`);
if (name === 'xmlns' && value !== 'http://www.w3.org/2000/svg')
throw new Error('Namespace SVG inválido.');
if (name === 'href' && !/^#[A-Za-z_][\w.-]*$/.test(value))
throw new Error('SVG aceita apenas referências internas por #id.');
// Presentation attributes may contain fragment paint servers, never remote URLs.
if (/url\s*\(/i.test(value) && !/^url\(\s*#[A-Za-z_][\w.-]*\s*\)$/.test(value))
throw new Error('Recursos externos ou URLs não suportadas no SVG.');
if (/[\\\u0000-\u001f]/.test(value))
throw new Error('Escape ou controle não suportado em atributo SVG.');
}
});
parser.on('closetag', () => { depth--; });
parser.write(input).close();
if (root !== 'svg')
throw new Error('O elemento raiz deve ser svg.');
return input;
}
function feText(value, max = 100000) {
if (typeof value !== 'string' || value.length > max)
throw new Error(`Use texto com até ${max} 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;
}
for (const value of Object.values(values)) if (typeof value !== "string" || value.length > 100000) throw new Error("Use até 100 mil caracteres por campo.");
return await optimizeFrontendSvg(values);
}
let payload = "";
for await (const chunk of process.stdin) payload += chunk;
try { const input = JSON.parse(payload); const result = await executar(input.values, input.image); process.stdout.write(JSON.stringify({ok: true, result}, (_, value) => value instanceof Uint8Array ? Array.from(value) : value)); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
'''
payload = json.dumps({"values": values}, ensure_ascii=True)
process = subprocess.run(["node", "--input-type=module", "-e", source], input=payload, 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 indicados abaixo; toda a lógica está visível.
$source = <<<'JAVASCRIPT'
import { SaxesParser } from 'saxes';
async function executar(values) {
async function optimizeFrontendSvg(v) {
const input = validateFrontendSvg(v.input);
const precision = feInteger(v.precision, 'Precisão', 0, 6);
feChoice(v.comments, ['Remover', 'Preservar']);
const { optimize } = await import('svgo/browser');
const svg = optimize(input, { floatPrecision: precision, multipass: true, plugins: [{ name: 'preset-default', params: { overrides: { cleanupIds: false, removeComments: v.comments === 'Remover' ? {} : false } } }] }).data;
validateFrontendSvg(svg);
const before = new TextEncoder().encode(input).length, after = new TextEncoder().encode(svg).length;
return { text: svg, images: [{ label: 'Original', svg: input }, { label: 'Otimizado', svg }], meta: { title: `${before} → ${after} bytes`, description: `Redução: ${((1 - after / before) * 100).toFixed(2)}%. Confira a comparação visual.`, url: '' } };
}
function feInteger(value, label, min, max) {
if (!/^-?\d+$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
function feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function validateFrontendSvg(input) {
feText(input);
const tags = new Set(['svg', 'g', 'defs', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan', 'title', 'desc', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'pattern', 'use']);
const attributes = new Set(('xmlns id x y x1 y1 x2 y2 cx cy r rx ry width height viewBox preserveAspectRatio d points transform fill fill-opacity fill-rule stroke stroke-width stroke-opacity stroke-linecap stroke-linejoin stroke-miterlimit stroke-dasharray stroke-dashoffset opacity clip-path clip-rule mask href gradientUnits gradientTransform offset stop-color stop-opacity fx fy fr spreadMethod patternUnits patternContentUnits patternTransform font-size font-family font-weight text-anchor dominant-baseline dx dy rotate textLength lengthAdjust').split(' '));
let depth = 0, nodes = 0, root = '';
const parser = new SaxesParser({ xmlns: false });
parser.on('doctype', () => { throw new Error('DTDs e entidades personalizadas não são aceitos.'); });
parser.on('processinginstruction', () => { throw new Error('Instruções de processamento não são aceitas em SVG.'); });
parser.on('error', error => { throw new Error('SVG inválido: ' + error.message); });
parser.on('opentag', tag => {
if (++nodes > 5000 || ++depth > 64)
throw new Error('SVG excede 5000 elementos ou 64 níveis.');
if (depth === 1)
root = tag.name;
if (!tags.has(tag.name))
throw new Error(`Elemento SVG não suportado: ${tag.name}. Use apenas SVG estático, sem scripts, estilos ou recursos externos.`);
for (const [name, raw] of Object.entries(tag.attributes)) {
const value = String(raw);
if (!attributes.has(name))
throw new Error(`Atributo SVG não suportado: ${name}. Eventos, estilos e namespaces adicionais não são aceitos.`);
if (name === 'xmlns' && value !== 'http://www.w3.org/2000/svg')
throw new Error('Namespace SVG inválido.');
if (name === 'href' && !/^#[A-Za-z_][\w.-]*$/.test(value))
throw new Error('SVG aceita apenas referências internas por #id.');
// Presentation attributes may contain fragment paint servers, never remote URLs.
if (/url\s*\(/i.test(value) && !/^url\(\s*#[A-Za-z_][\w.-]*\s*\)$/.test(value))
throw new Error('Recursos externos ou URLs não suportadas no SVG.');
if (/[\\\u0000-\u001f]/.test(value))
throw new Error('Escape ou controle não suportado em atributo SVG.');
}
});
parser.on('closetag', () => { depth--; });
parser.write(input).close();
if (root !== 'svg')
throw new Error('O elemento raiz deve ser svg.');
return input;
}
function feText(value, max = 100000) {
if (typeof value !== 'string' || value.length > max)
throw new Error(`Use texto com até ${max} 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;
}
for (const value of Object.values(values)) if (typeof value !== "string" || value.length > 100000) throw new Error("Use até 100 mil caracteres por campo.");
return await optimizeFrontendSvg(values);
}
let payload = "";
for await (const chunk of process.stdin) payload += chunk;
try { const input = JSON.parse(payload); const result = await executar(input.values, input.image); process.stdout.write(JSON.stringify({ok: true, result}, (_, value) => value instanceof Uint8Array ? Array.from(value) : value)); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
JAVASCRIPT;
$payload = json_encode(["values" => $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)) {
$written = fwrite($pipes[0], substr($payload, $offset));
if ($written === false || $written === 0) { proc_terminate($process); foreach ($pipes as $pipe) fclose($pipe); proc_close($process); throw new RuntimeException("Falha ao enviar a entrada."); }
$offset += $written;
}
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); $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); $status = proc_close($process);
if ($timeout || $status !== 0) { throw new RuntimeException("Falha técnica 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"];
}