JavaScript Python PHP
import { SaxesParser } from 'saxes';
async function executar(values) {
async function generateFrontendBarcode(v) {
const text = feText(v.input), format = feChoice(v.format, ['Code 128', 'EAN-13', 'Code 39']);
if (format === 'Code 128' && !/^[\x20-\x7e]{1,80}$/.test(text))
throw new Error('Code 128 aceita de 1 a 80 caracteres ASCII imprimíveis.');
if (format === 'Code 39' && !/^[A-Z0-9 .$/+%\-]{1,40}$/.test(text))
throw new Error('Code 39 aceita 1–40 caracteres: A–Z, 0–9, espaço e -.$/+%.');
if (format === 'EAN-13') {
if (!/^\d{13}$/.test(text))
throw new Error('EAN-13 exige exatamente 13 dígitos, incluindo o verificador.');
const sum = [...text.slice(0, 12)].reduce((sum, c, i) => sum + Number(c) * (i % 2 ? 3 : 1), 0);
if ((10 - sum % 10) % 10 !== Number(text[12]))
throw new Error('Dígito verificador EAN-13 inválido.');
}
const { code128, ean13, code39, drawingSVG } = await import('@bwip-js/generic');
const encoder = format === 'EAN-13' ? ean13 : format === 'Code 39' ? code39 : code128;
const svg = feBarcodeSize(encoder({ bcid: format === 'EAN-13' ? 'ean13' : format === 'Code 39' ? 'code39' : 'code128', text, scale: 2, height: 15, includetext: true, textxalign: 'center', paddingwidth: 12, paddingheight: 4, backgroundcolor: 'FFFFFF', parse: false, parsefnc: false }, drawingSVG()));
return feImage(svg, format + ': ' + text);
}
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;
}
function feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function feImage(svg, label) {
return { text: svg, images: [{ label, svg }] };
}
function feBarcodeSize(svg) {
let width = 0, height = 0;
const parser = new SaxesParser();
parser.on('opentag', tag => {
if (tag.name !== 'svg')
return;
const box = String(tag.attributes.viewBox).split(/\s+/).map(Number);
width = box[2];
height = box[3];
});
parser.write(svg).close();
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192)
throw new Error('Código excede as dimensões de imagem suportadas.');
return svg.replace('<svg ', `<svg width="${width}" height="${height}" `);
}
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 generateFrontendBarcode(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 generateFrontendBarcode(v) {
const text = feText(v.input), format = feChoice(v.format, ['Code 128', 'EAN-13', 'Code 39']);
if (format === 'Code 128' && !/^[\x20-\x7e]{1,80}$/.test(text))
throw new Error('Code 128 aceita de 1 a 80 caracteres ASCII imprimíveis.');
if (format === 'Code 39' && !/^[A-Z0-9 .$/+%\-]{1,40}$/.test(text))
throw new Error('Code 39 aceita 1–40 caracteres: A–Z, 0–9, espaço e -.$/+%.');
if (format === 'EAN-13') {
if (!/^\d{13}$/.test(text))
throw new Error('EAN-13 exige exatamente 13 dígitos, incluindo o verificador.');
const sum = [...text.slice(0, 12)].reduce((sum, c, i) => sum + Number(c) * (i % 2 ? 3 : 1), 0);
if ((10 - sum % 10) % 10 !== Number(text[12]))
throw new Error('Dígito verificador EAN-13 inválido.');
}
const { code128, ean13, code39, drawingSVG } = await import('@bwip-js/generic');
const encoder = format === 'EAN-13' ? ean13 : format === 'Code 39' ? code39 : code128;
const svg = feBarcodeSize(encoder({ bcid: format === 'EAN-13' ? 'ean13' : format === 'Code 39' ? 'code39' : 'code128', text, scale: 2, height: 15, includetext: true, textxalign: 'center', paddingwidth: 12, paddingheight: 4, backgroundcolor: 'FFFFFF', parse: false, parsefnc: false }, drawingSVG()));
return feImage(svg, format + ': ' + text);
}
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;
}
function feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function feImage(svg, label) {
return { text: svg, images: [{ label, svg }] };
}
function feBarcodeSize(svg) {
let width = 0, height = 0;
const parser = new SaxesParser();
parser.on('opentag', tag => {
if (tag.name !== 'svg')
return;
const box = String(tag.attributes.viewBox).split(/\s+/).map(Number);
width = box[2];
height = box[3];
});
parser.write(svg).close();
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192)
throw new Error('Código excede as dimensões de imagem suportadas.');
return svg.replace('<svg ', `<svg width="${width}" height="${height}" `);
}
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 generateFrontendBarcode(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 generateFrontendBarcode(v) {
const text = feText(v.input), format = feChoice(v.format, ['Code 128', 'EAN-13', 'Code 39']);
if (format === 'Code 128' && !/^[\x20-\x7e]{1,80}$/.test(text))
throw new Error('Code 128 aceita de 1 a 80 caracteres ASCII imprimíveis.');
if (format === 'Code 39' && !/^[A-Z0-9 .$/+%\-]{1,40}$/.test(text))
throw new Error('Code 39 aceita 1–40 caracteres: A–Z, 0–9, espaço e -.$/+%.');
if (format === 'EAN-13') {
if (!/^\d{13}$/.test(text))
throw new Error('EAN-13 exige exatamente 13 dígitos, incluindo o verificador.');
const sum = [...text.slice(0, 12)].reduce((sum, c, i) => sum + Number(c) * (i % 2 ? 3 : 1), 0);
if ((10 - sum % 10) % 10 !== Number(text[12]))
throw new Error('Dígito verificador EAN-13 inválido.');
}
const { code128, ean13, code39, drawingSVG } = await import('@bwip-js/generic');
const encoder = format === 'EAN-13' ? ean13 : format === 'Code 39' ? code39 : code128;
const svg = feBarcodeSize(encoder({ bcid: format === 'EAN-13' ? 'ean13' : format === 'Code 39' ? 'code39' : 'code128', text, scale: 2, height: 15, includetext: true, textxalign: 'center', paddingwidth: 12, paddingheight: 4, backgroundcolor: 'FFFFFF', parse: false, parsefnc: false }, drawingSVG()));
return feImage(svg, format + ': ' + text);
}
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;
}
function feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function feImage(svg, label) {
return { text: svg, images: [{ label, svg }] };
}
function feBarcodeSize(svg) {
let width = 0, height = 0;
const parser = new SaxesParser();
parser.on('opentag', tag => {
if (tag.name !== 'svg')
return;
const box = String(tag.attributes.viewBox).split(/\s+/).map(Number);
width = box[2];
height = box[3];
});
parser.write(svg).close();
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192)
throw new Error('Código excede as dimensões de imagem suportadas.');
return svg.replace('<svg ', `<svg width="${width}" height="${height}" `);
}
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 generateFrontendBarcode(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"];
}