JavaScript Python PHP
async function executar(values, image) {
async function generateFrontendFavicon(v, image) {
const name = feText(v.name, 80).trim();
if (!name)
throw new Error('Informe o nome do site.');
if (!image || image.length < 45 || image.length > 2097152)
throw new Error('Envie um PNG de até 2 MB.');
const { decode, encode, hasPngSignature } = await import('fast-png');
const { zipSync, strToU8, Unzlib } = await import('fflate');
if (!hasPngSignature(image))
throw new Error('O arquivo precisa ser uma imagem PNG.');
const view = new DataView(image.buffer, image.byteOffset, image.byteLength);
const width = view.getUint32(16), height = view.getUint32(20), channels = image[25] === 6 ? 4 : 3;
if (!width || !height || width > 2048 || height > 2048 || image[24] !== 8 || ![2, 6].includes(image[25]) || image[28] !== 0)
throw new Error('Use PNG RGB/RGBA de 8 bits, não entrelaçado, com até 2048 × 2048 pixels.');
// Exclude compressed metadata and APNG. Check the inflated image size before decoding.
const chunks = [image.slice(0, 8)], compressed = [];
let offset = 8, chunkCount = 0, ended = false, seenHeader = false, seenData = false;
while (offset + 12 <= image.length) {
if (++chunkCount > 10000)
throw new Error('PNG com quantidade excessiva de blocos.');
const length = view.getUint32(offset), end = offset + length + 12;
if (end > image.length)
throw new Error('PNG truncado.');
const type = String.fromCharCode(...image.subarray(offset + 4, offset + 8));
if (type === 'IHDR') {
if (seenHeader || offset !== 8 || length !== 13)
throw new Error('Cabeçalho PNG inválido.');
seenHeader = true;
}
if (['acTL', 'fcTL', 'fdAT', 'tRNS'].includes(type))
throw new Error('PNG animado ou transparência por tRNS não são suportados. Use RGBA.');
if (type === 'IDAT') {
seenData = true;
compressed.push(image.slice(offset + 8, offset + 8 + length));
}
if (['IHDR', 'IDAT', 'IEND'].includes(type))
chunks.push(image.slice(offset, end));
if (type === 'IEND') {
if (length !== 0)
throw new Error('Final PNG inválido.');
ended = true;
offset = end;
break;
}
offset = end;
}
if (!ended || !seenHeader || !seenData || offset !== image.length)
throw new Error('Estrutura PNG incompleta ou dados adicionais não suportados.');
let inflated = 0;
const expected = (width * channels + 1) * height;
const inflator = new Unzlib(chunk => { inflated += chunk.length; if (inflated > expected)
throw new Error('Dados PNG excedem as dimensões declaradas.'); });
compressed.forEach((part, i) => { for (let p = 0; p < part.length; p += 16384)
inflator.push(part.subarray(p, p + 16384), i === compressed.length - 1 && p + 16384 >= part.length); });
if (inflated !== expected)
throw new Error('Dados PNG não correspondem às dimensões declaradas.');
const packed = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
let packedOffset = 0;
for (const chunk of chunks) {
packed.set(chunk, packedOffset);
packedOffset += chunk.length;
}
const source = decode(packed, { checkCrc: true });
const files = Object.create(null);
for (const size of [16, 32, 180, 192, 512]) {
const data = new Uint8Array(size * size * 4), scale = Math.min(size / width, size / height);
const drawW = Math.max(1, Math.round(width * scale)), drawH = Math.max(1, Math.round(height * scale)), left = Math.floor((size - drawW) / 2), top = Math.floor((size - drawH) / 2);
for (let y = 0; y < drawH; y++)
for (let x = 0; x < drawW; x++) {
const sx = Math.max(0, Math.min(width - 1, (x + .5) * width / drawW - .5)), sy = Math.max(0, Math.min(height - 1, (y + .5) * height / drawH - .5));
const x0 = Math.floor(sx), y0 = Math.floor(sy), tx = sx - x0, ty = sy - y0;
const samples = [[x0, y0, (1 - tx) * (1 - ty)], [Math.min(x0 + 1, width - 1), y0, tx * (1 - ty)], [x0, Math.min(y0 + 1, height - 1), (1 - tx) * ty], [Math.min(x0 + 1, width - 1), Math.min(y0 + 1, height - 1), tx * ty]];
let alpha = 0;
const rgb = [0, 0, 0];
for (const [px, py, weight] of samples) {
const p = (py * width + px) * channels, a = channels === 4 ? source.data[p + 3] / 255 : 1;
alpha += a * weight;
for (let c = 0; c < 3; c++)
rgb[c] += source.data[p + c] * a * weight;
}
const dest = ((y + top) * size + x + left) * 4;
for (let c = 0; c < 3; c++)
data[dest + c] = alpha ? Math.round(rgb[c] / alpha) : 0;
data[dest + 3] = Math.round(alpha * 255);
}
files[`icon-${size}.png`] = encode({ width: size, height: size, data, channels: 4 });
}
const png = files['icon-32.png'], ico = new Uint8Array(22 + png.length), icoView = new DataView(ico.buffer);
icoView.setUint16(2, 1, true);
icoView.setUint16(4, 1, true);
ico[6] = 32;
ico[7] = 32;
icoView.setUint16(10, 1, true);
icoView.setUint16(12, 32, true);
icoView.setUint32(14, png.length, true);
icoView.setUint32(18, 22, true);
ico.set(png, 22);
files['favicon.ico'] = ico;
const html = '<link rel="icon" href="/favicon.ico" sizes="32x32">\n<link rel="icon" type="image/png" sizes="16x16" href="/icon-16.png">\n<link rel="icon" type="image/png" sizes="32x32" href="/icon-32.png">\n<link rel="apple-touch-icon" sizes="180x180" href="/icon-180.png">\n<link rel="manifest" href="/site.webmanifest">';
files['tags.html'] = strToU8(html);
files['site.webmanifest'] = strToU8(JSON.stringify({ name, short_name: name, icons: [192, 512].map(size => ({ src: `/icon-${size}.png`, sizes: `${size}x${size}`, type: 'image/png' })) }, null, 2));
return { text: html, artifacts: [{ name: 'favicons.zip', mime: 'application/zip', bytes: zipSync(files, { level: 6, mtime: new Date('2020-01-01T00:00:00Z') }) }, { name: 'icon-180.png', mime: 'image/png', bytes: files['icon-180.png'] }] };
}
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 generateFrontendFavicon(values, new Uint8Array(image));
}
import json
import subprocess
def executar(values, image):
# Requer Node.js 22+ e os pacotes npm indicados abaixo; toda a lógica está visível.
source = r'''
async function executar(values, image) {
async function generateFrontendFavicon(v, image) {
const name = feText(v.name, 80).trim();
if (!name)
throw new Error('Informe o nome do site.');
if (!image || image.length < 45 || image.length > 2097152)
throw new Error('Envie um PNG de até 2 MB.');
const { decode, encode, hasPngSignature } = await import('fast-png');
const { zipSync, strToU8, Unzlib } = await import('fflate');
if (!hasPngSignature(image))
throw new Error('O arquivo precisa ser uma imagem PNG.');
const view = new DataView(image.buffer, image.byteOffset, image.byteLength);
const width = view.getUint32(16), height = view.getUint32(20), channels = image[25] === 6 ? 4 : 3;
if (!width || !height || width > 2048 || height > 2048 || image[24] !== 8 || ![2, 6].includes(image[25]) || image[28] !== 0)
throw new Error('Use PNG RGB/RGBA de 8 bits, não entrelaçado, com até 2048 × 2048 pixels.');
// Exclude compressed metadata and APNG. Check the inflated image size before decoding.
const chunks = [image.slice(0, 8)], compressed = [];
let offset = 8, chunkCount = 0, ended = false, seenHeader = false, seenData = false;
while (offset + 12 <= image.length) {
if (++chunkCount > 10000)
throw new Error('PNG com quantidade excessiva de blocos.');
const length = view.getUint32(offset), end = offset + length + 12;
if (end > image.length)
throw new Error('PNG truncado.');
const type = String.fromCharCode(...image.subarray(offset + 4, offset + 8));
if (type === 'IHDR') {
if (seenHeader || offset !== 8 || length !== 13)
throw new Error('Cabeçalho PNG inválido.');
seenHeader = true;
}
if (['acTL', 'fcTL', 'fdAT', 'tRNS'].includes(type))
throw new Error('PNG animado ou transparência por tRNS não são suportados. Use RGBA.');
if (type === 'IDAT') {
seenData = true;
compressed.push(image.slice(offset + 8, offset + 8 + length));
}
if (['IHDR', 'IDAT', 'IEND'].includes(type))
chunks.push(image.slice(offset, end));
if (type === 'IEND') {
if (length !== 0)
throw new Error('Final PNG inválido.');
ended = true;
offset = end;
break;
}
offset = end;
}
if (!ended || !seenHeader || !seenData || offset !== image.length)
throw new Error('Estrutura PNG incompleta ou dados adicionais não suportados.');
let inflated = 0;
const expected = (width * channels + 1) * height;
const inflator = new Unzlib(chunk => { inflated += chunk.length; if (inflated > expected)
throw new Error('Dados PNG excedem as dimensões declaradas.'); });
compressed.forEach((part, i) => { for (let p = 0; p < part.length; p += 16384)
inflator.push(part.subarray(p, p + 16384), i === compressed.length - 1 && p + 16384 >= part.length); });
if (inflated !== expected)
throw new Error('Dados PNG não correspondem às dimensões declaradas.');
const packed = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
let packedOffset = 0;
for (const chunk of chunks) {
packed.set(chunk, packedOffset);
packedOffset += chunk.length;
}
const source = decode(packed, { checkCrc: true });
const files = Object.create(null);
for (const size of [16, 32, 180, 192, 512]) {
const data = new Uint8Array(size * size * 4), scale = Math.min(size / width, size / height);
const drawW = Math.max(1, Math.round(width * scale)), drawH = Math.max(1, Math.round(height * scale)), left = Math.floor((size - drawW) / 2), top = Math.floor((size - drawH) / 2);
for (let y = 0; y < drawH; y++)
for (let x = 0; x < drawW; x++) {
const sx = Math.max(0, Math.min(width - 1, (x + .5) * width / drawW - .5)), sy = Math.max(0, Math.min(height - 1, (y + .5) * height / drawH - .5));
const x0 = Math.floor(sx), y0 = Math.floor(sy), tx = sx - x0, ty = sy - y0;
const samples = [[x0, y0, (1 - tx) * (1 - ty)], [Math.min(x0 + 1, width - 1), y0, tx * (1 - ty)], [x0, Math.min(y0 + 1, height - 1), (1 - tx) * ty], [Math.min(x0 + 1, width - 1), Math.min(y0 + 1, height - 1), tx * ty]];
let alpha = 0;
const rgb = [0, 0, 0];
for (const [px, py, weight] of samples) {
const p = (py * width + px) * channels, a = channels === 4 ? source.data[p + 3] / 255 : 1;
alpha += a * weight;
for (let c = 0; c < 3; c++)
rgb[c] += source.data[p + c] * a * weight;
}
const dest = ((y + top) * size + x + left) * 4;
for (let c = 0; c < 3; c++)
data[dest + c] = alpha ? Math.round(rgb[c] / alpha) : 0;
data[dest + 3] = Math.round(alpha * 255);
}
files[`icon-${size}.png`] = encode({ width: size, height: size, data, channels: 4 });
}
const png = files['icon-32.png'], ico = new Uint8Array(22 + png.length), icoView = new DataView(ico.buffer);
icoView.setUint16(2, 1, true);
icoView.setUint16(4, 1, true);
ico[6] = 32;
ico[7] = 32;
icoView.setUint16(10, 1, true);
icoView.setUint16(12, 32, true);
icoView.setUint32(14, png.length, true);
icoView.setUint32(18, 22, true);
ico.set(png, 22);
files['favicon.ico'] = ico;
const html = '<link rel="icon" href="/favicon.ico" sizes="32x32">\n<link rel="icon" type="image/png" sizes="16x16" href="/icon-16.png">\n<link rel="icon" type="image/png" sizes="32x32" href="/icon-32.png">\n<link rel="apple-touch-icon" sizes="180x180" href="/icon-180.png">\n<link rel="manifest" href="/site.webmanifest">';
files['tags.html'] = strToU8(html);
files['site.webmanifest'] = strToU8(JSON.stringify({ name, short_name: name, icons: [192, 512].map(size => ({ src: `/icon-${size}.png`, sizes: `${size}x${size}`, type: 'image/png' })) }, null, 2));
return { text: html, artifacts: [{ name: 'favicons.zip', mime: 'application/zip', bytes: zipSync(files, { level: 6, mtime: new Date('2020-01-01T00:00:00Z') }) }, { name: 'icon-180.png', mime: 'image/png', bytes: files['icon-180.png'] }] };
}
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 generateFrontendFavicon(values, new Uint8Array(image));
}
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, "image": list(image)}, 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 $image): array {
// Requer Node.js 22+ e os pacotes npm indicados abaixo; toda a lógica está visível.
$source = <<<'JAVASCRIPT'
async function executar(values, image) {
async function generateFrontendFavicon(v, image) {
const name = feText(v.name, 80).trim();
if (!name)
throw new Error('Informe o nome do site.');
if (!image || image.length < 45 || image.length > 2097152)
throw new Error('Envie um PNG de até 2 MB.');
const { decode, encode, hasPngSignature } = await import('fast-png');
const { zipSync, strToU8, Unzlib } = await import('fflate');
if (!hasPngSignature(image))
throw new Error('O arquivo precisa ser uma imagem PNG.');
const view = new DataView(image.buffer, image.byteOffset, image.byteLength);
const width = view.getUint32(16), height = view.getUint32(20), channels = image[25] === 6 ? 4 : 3;
if (!width || !height || width > 2048 || height > 2048 || image[24] !== 8 || ![2, 6].includes(image[25]) || image[28] !== 0)
throw new Error('Use PNG RGB/RGBA de 8 bits, não entrelaçado, com até 2048 × 2048 pixels.');
// Exclude compressed metadata and APNG. Check the inflated image size before decoding.
const chunks = [image.slice(0, 8)], compressed = [];
let offset = 8, chunkCount = 0, ended = false, seenHeader = false, seenData = false;
while (offset + 12 <= image.length) {
if (++chunkCount > 10000)
throw new Error('PNG com quantidade excessiva de blocos.');
const length = view.getUint32(offset), end = offset + length + 12;
if (end > image.length)
throw new Error('PNG truncado.');
const type = String.fromCharCode(...image.subarray(offset + 4, offset + 8));
if (type === 'IHDR') {
if (seenHeader || offset !== 8 || length !== 13)
throw new Error('Cabeçalho PNG inválido.');
seenHeader = true;
}
if (['acTL', 'fcTL', 'fdAT', 'tRNS'].includes(type))
throw new Error('PNG animado ou transparência por tRNS não são suportados. Use RGBA.');
if (type === 'IDAT') {
seenData = true;
compressed.push(image.slice(offset + 8, offset + 8 + length));
}
if (['IHDR', 'IDAT', 'IEND'].includes(type))
chunks.push(image.slice(offset, end));
if (type === 'IEND') {
if (length !== 0)
throw new Error('Final PNG inválido.');
ended = true;
offset = end;
break;
}
offset = end;
}
if (!ended || !seenHeader || !seenData || offset !== image.length)
throw new Error('Estrutura PNG incompleta ou dados adicionais não suportados.');
let inflated = 0;
const expected = (width * channels + 1) * height;
const inflator = new Unzlib(chunk => { inflated += chunk.length; if (inflated > expected)
throw new Error('Dados PNG excedem as dimensões declaradas.'); });
compressed.forEach((part, i) => { for (let p = 0; p < part.length; p += 16384)
inflator.push(part.subarray(p, p + 16384), i === compressed.length - 1 && p + 16384 >= part.length); });
if (inflated !== expected)
throw new Error('Dados PNG não correspondem às dimensões declaradas.');
const packed = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
let packedOffset = 0;
for (const chunk of chunks) {
packed.set(chunk, packedOffset);
packedOffset += chunk.length;
}
const source = decode(packed, { checkCrc: true });
const files = Object.create(null);
for (const size of [16, 32, 180, 192, 512]) {
const data = new Uint8Array(size * size * 4), scale = Math.min(size / width, size / height);
const drawW = Math.max(1, Math.round(width * scale)), drawH = Math.max(1, Math.round(height * scale)), left = Math.floor((size - drawW) / 2), top = Math.floor((size - drawH) / 2);
for (let y = 0; y < drawH; y++)
for (let x = 0; x < drawW; x++) {
const sx = Math.max(0, Math.min(width - 1, (x + .5) * width / drawW - .5)), sy = Math.max(0, Math.min(height - 1, (y + .5) * height / drawH - .5));
const x0 = Math.floor(sx), y0 = Math.floor(sy), tx = sx - x0, ty = sy - y0;
const samples = [[x0, y0, (1 - tx) * (1 - ty)], [Math.min(x0 + 1, width - 1), y0, tx * (1 - ty)], [x0, Math.min(y0 + 1, height - 1), (1 - tx) * ty], [Math.min(x0 + 1, width - 1), Math.min(y0 + 1, height - 1), tx * ty]];
let alpha = 0;
const rgb = [0, 0, 0];
for (const [px, py, weight] of samples) {
const p = (py * width + px) * channels, a = channels === 4 ? source.data[p + 3] / 255 : 1;
alpha += a * weight;
for (let c = 0; c < 3; c++)
rgb[c] += source.data[p + c] * a * weight;
}
const dest = ((y + top) * size + x + left) * 4;
for (let c = 0; c < 3; c++)
data[dest + c] = alpha ? Math.round(rgb[c] / alpha) : 0;
data[dest + 3] = Math.round(alpha * 255);
}
files[`icon-${size}.png`] = encode({ width: size, height: size, data, channels: 4 });
}
const png = files['icon-32.png'], ico = new Uint8Array(22 + png.length), icoView = new DataView(ico.buffer);
icoView.setUint16(2, 1, true);
icoView.setUint16(4, 1, true);
ico[6] = 32;
ico[7] = 32;
icoView.setUint16(10, 1, true);
icoView.setUint16(12, 32, true);
icoView.setUint32(14, png.length, true);
icoView.setUint32(18, 22, true);
ico.set(png, 22);
files['favicon.ico'] = ico;
const html = '<link rel="icon" href="/favicon.ico" sizes="32x32">\n<link rel="icon" type="image/png" sizes="16x16" href="/icon-16.png">\n<link rel="icon" type="image/png" sizes="32x32" href="/icon-32.png">\n<link rel="apple-touch-icon" sizes="180x180" href="/icon-180.png">\n<link rel="manifest" href="/site.webmanifest">';
files['tags.html'] = strToU8(html);
files['site.webmanifest'] = strToU8(JSON.stringify({ name, short_name: name, icons: [192, 512].map(size => ({ src: `/icon-${size}.png`, sizes: `${size}x${size}`, type: 'image/png' })) }, null, 2));
return { text: html, artifacts: [{ name: 'favicons.zip', mime: 'application/zip', bytes: zipSync(files, { level: 6, mtime: new Date('2020-01-01T00:00:00Z') }) }, { name: 'icon-180.png', mime: 'image/png', bytes: files['icon-180.png'] }] };
}
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 generateFrontendFavicon(values, new Uint8Array(image));
}
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, "image" => $image], 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"];
}