JavaScript Python PHP
async function executar(values) {
function generateFrontendBreakpoints(v) {
feText(v.input);
let points;
try {
points = JSON.parse(v.input);
}
catch {
throw new Error('Breakpoints: informe uma lista JSON válida.');
}
if (!Array.isArray(points) || !points.length || points.length > 10)
throw new Error('Informe de 1 a 10 breakpoints.');
let previous = 0;
const gap = feInteger(v.gap, 'Espaçamento', 0, 64), rules = ['.preview-grid { display: grid; grid-template-columns: 1fr; gap: ' + gap + 'px; }'];
for (const point of points) {
if (!point || typeof point !== 'object' || Object.keys(point).some(k => !['width', 'columns'].includes(k)) || !Number.isInteger(point.width) || !Number.isInteger(point.columns))
throw new Error('Cada breakpoint deve conter apenas width e columns inteiros.');
const width = feInteger(String(point.width), 'Largura', 240, 2560), columns = feInteger(String(point.columns), 'Colunas', 1, 6);
if (width <= previous)
throw new Error('Os breakpoints devem estar em ordem crescente, sem repetição.');
previous = width;
rules.push(`@media (min-width: ${width}px) { .preview-grid { grid-template-columns: repeat(${columns}, minmax(0, 1fr)); } }`);
}
const text = rules.join('\n');
const frame = '<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'; script-src \'none\'; img-src \'none\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:0;padding:16px;font:16px sans-serif;background:#f1f5f9;color:#0f172a;box-sizing:border-box}.card{background:#fff;border:1px solid #94a3b8;padding:20px;border-radius:8px;min-width:0;overflow-wrap:anywhere}*{box-sizing:border-box}' + text + '</style></head><body><main class="preview-grid">' + Array.from({ length: 6 }, (_, i) => `<article class="card"><h2>Cartão ${i + 1}</h2><p>Conteúdo de demonstração para testar as colunas.</p></article>`).join('') + '</main></body></html>';
return { text, frame };
}
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 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);
}
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 generateFrontendBreakpoints(values);
}
import html
import json
import math
import re
from urllib.parse import urlsplit, urlunsplit
def executar(values):
def text(value, limit=100000):
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > limit:
raise ValueError('Texto excede o limite permitido.')
if re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff\ud800-\udfff]', value):
raise ValueError('Controle ou Unicode inválido.')
return value
def integer(value, minimum, maximum):
if not isinstance(value, str) or not re.fullmatch(r'-?[0-9]+', value) or not minimum <= int(value) <= maximum:
raise ValueError('Inteiro fora dos limites permitidos.')
return int(value)
def color(value):
if not re.fullmatch(r'#[0-9a-fA-F]{6}', value):
raise ValueError('Cor HEX inválida.')
return value.lower()
def choice(value, options):
if value not in options:
raise ValueError('Opção não suportada.')
return value
def esc(value):
return html.escape(text(value), quote=True).replace(''', ''')
def url(value):
text(value, 2048)
parsed = urlsplit(value)
if not re.match(r'https?://', value, re.I) or parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or re.search(r'[\s\\]', value):
raise ValueError('Use uma URL HTTP/HTTPS absoluta sem credenciais.')
if parsed.port is not None and not 0 <= parsed.port <= 65535:
raise ValueError('Porta inválida.')
return value
def svg(width, height, body):
return f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">{body}</svg>'
def image(markup, label):
return {'text': markup, 'images': [{'label': label, 'svg': markup}]}
def num(value):
rounded = math.floor(value * 1000 + 0.5) / 1000
return str(int(rounded)) if rounded.is_integer() else str(rounded)
for value in values.values():
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > 100000:
raise ValueError('Use até 100 mil caracteres por campo.')
points = json.loads(text(values['input']))
if not isinstance(points, list) or not 1 <= len(points) <= 10:
raise ValueError('Informe de 1 a 10 breakpoints.')
gap, previous = integer(values['gap'], 0, 64), 0
rules = [f'.preview-grid {{ display: grid; grid-template-columns: 1fr; gap: {gap}px; }}']
for point in points:
if not isinstance(point, dict) or set(point) != {'width', 'columns'} or type(point['width']) is not int or type(point['columns']) is not int:
raise ValueError('Cada breakpoint deve conter apenas width e columns inteiros.')
width, columns = integer(str(point['width']), 240, 2560), integer(str(point['columns']), 1, 6)
if width <= previous:
raise ValueError('Os breakpoints devem estar em ordem crescente, sem repetição.')
previous = width
rules.append(f'@media (min-width: {width}px) {{ .preview-grid {{ grid-template-columns: repeat({columns}, minmax(0, 1fr)); }} }}')
output = '\n'.join(rules)
frame = '<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'; script-src \'none\'; img-src \'none\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:0;padding:16px;font:16px sans-serif;background:#f1f5f9;color:#0f172a;box-sizing:border-box}.card{background:#fff;border:1px solid #94a3b8;padding:20px;border-radius:8px;min-width:0;overflow-wrap:anywhere}*{box-sizing:border-box}' + output + '</style></head><body><main class="preview-grid">' + ''.join(f'<article class="card"><h2>Cartão {i + 1}</h2><p>Conteúdo de demonstração para testar as colunas.</p></article>' for i in range(6)) + '</main></body></html>'
return {'text': output, 'frame': frame}
<?php
function executar(array $values): array {
$text = static function ($value, $limit = 100000) {
if (!is_string($value) || !preg_match('//u', $value) || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > $limit || preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x{fffe}\x{ffff}]/u', $value)) { throw new InvalidArgumentException('Texto excede o limite ou contém caracteres inválidos.'); }
return $value;
};
$integer = static function ($value, $min, $max) {
if (!is_string($value) || !preg_match('/^-?[0-9]+$/D', $value) || strlen(ltrim($value, '-0')) > 10 || (float)$value < $min || (float)$value > $max) { throw new InvalidArgumentException('Inteiro fora dos limites permitidos.'); }
return (int)$value;
};
$color = static function ($value) {
if (!preg_match('/^#[0-9a-fA-F]{6}$/D', $value)) { throw new InvalidArgumentException('Cor HEX inválida.'); }
return strtolower($value);
};
$choice = static function ($value, $options) {
if (!in_array($value, $options, true)) { throw new InvalidArgumentException('Opção não suportada.'); }
return $value;
};
$esc = static function ($value) use ($text) { return str_replace(''', ''', htmlspecialchars($text($value), ENT_QUOTES | ENT_HTML401, 'UTF-8')); };
$url = static function ($value) use ($text) {
$text($value, 2048); $p = parse_url($value);
if (!$p || !isset($p['host']) || !in_array(strtolower($p['scheme'] ?? ''), ['http', 'https'], true) || isset($p['user']) || isset($p['pass']) || preg_match('/[\s\\\\]/u', $value)) { throw new InvalidArgumentException('Use URL HTTP/HTTPS absoluta sem credenciais.'); }
return $value;
};
$svg = static function ($w, $h, $body) { return '<svg xmlns="http://www.w3.org/2000/svg" width="' . $w . '" height="' . $h . '" viewBox="0 0 ' . $w . ' ' . $h . '">' . $body . '</svg>'; };
$image = static function ($markup, $label) { return ['text' => $markup, 'images' => [['label' => $label, 'svg' => $markup]]]; };
$num = static function ($value) { return (string)(floor($value * 1000 + 0.5) / 1000); };
foreach ($values as $value) { if (!is_string($value) || !preg_match('//u', $value) || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > 100000) { throw new InvalidArgumentException('Use até 100 mil caracteres por campo.'); } }
$points = json_decode($text($values['input']), true, 512, JSON_THROW_ON_ERROR); if (!is_array($points) || !array_is_list($points) || count($points) < 1 || count($points) > 10) { throw new InvalidArgumentException('Informe de 1 a 10 breakpoints.'); }
$gap = $integer($values['gap'], 0, 64); $previous = 0; $rules = ['.preview-grid { display: grid; grid-template-columns: 1fr; gap: ' . $gap . 'px; }'];
foreach ($points as $point) { if (!is_array($point) || count($point) !== 2 || !isset($point['width'], $point['columns']) || !is_int($point['width']) || !is_int($point['columns'])) { throw new InvalidArgumentException('Cada breakpoint deve conter apenas width e columns inteiros.'); } $w = $integer((string)$point['width'], 240, 2560); $c = $integer((string)$point['columns'], 1, 6); if ($w <= $previous) { throw new InvalidArgumentException('Os breakpoints devem estar em ordem crescente, sem repetição.'); } $previous = $w; $rules[] = '@media (min-width: ' . $w . 'px) { .preview-grid { grid-template-columns: repeat(' . $c . ', minmax(0, 1fr)); } }'; }
$output = implode("\n", $rules);
$frame = '<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'; script-src \'none\'; img-src \'none\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:0;padding:16px;font:16px sans-serif;background:#f1f5f9;color:#0f172a;box-sizing:border-box}.card{background:#fff;border:1px solid #94a3b8;padding:20px;border-radius:8px;min-width:0;overflow-wrap:anywhere}*{box-sizing:border-box}' . $output . '</style></head><body><main class="preview-grid">'; for ($i = 1; $i <= 6; $i++) { $frame .= '<article class="card"><h2>Cartão ' . $i . '</h2><p>Conteúdo de demonstração para testar as colunas.</p></article>'; } $frame .= '</main></body></html>';
return ['text' => $output, 'frame' => $frame];
}