JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function generateWebsocketPayload(values) {
const source = text(values.body, 'Conteúdo da mensagem');
if (values.mode === 'Texto') {
if (/[\ud800-\udfff]/u.test(source))
throw new Error('A mensagem contém Unicode inválido.');
return source;
}
if (values.mode !== 'JSON')
throw new Error('Escolha JSON ou Texto como modo da mensagem.');
const type = label(values.eventType, 'Tipo do evento', 100);
const id = label(values.requestId, 'ID de correlação', 200, true);
const payload = { type, data: json(source, 'Dados do evento') };
if (id)
payload.id = id;
return result(payload);
}
function text(value, label) {
if (typeof value !== 'string')
throw new Error(label + ': informe texto.');
if (value.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
return value;
}
function json(input, label, objectOnly = false) {
try {
const value = parseJsonCompatible(text(input, label), 'JSON');
if (objectOnly && (!value || typeof value !== 'object' || Array.isArray(value)))
throw new Error('Informe um objeto JSON.');
return value;
}
catch (cause) {
const message = cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string' ? cause.message : 'JSON inválido.';
throw new Error(label + ': ' + message);
}
}
function result(value) {
const output = JSON.stringify(value, null, 2);
if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.');
return output;
}
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
function label(input, title, max, optional = false) {
const source = text(input, title);
if (/[\x00-\x1f\x7f]/.test(source))
throw new Error(title + ': controles não são permitidos.');
const value = source.trim();
if ((!value && !optional) || value.length > max || /[\x00-\x1f\x7f\ud800-\udfff]/u.test(value))
throw new Error(`${title}: use texto válido, sem controles, com ${optional ? 'até' : '1 a'} ${max} caracteres.`);
return value;
}
return generateWebsocketPayload(values);
}
import json
import math
import re
def executar(values):
def read(source, label, object_only=False):
text(source, label)
if not source.strip():
raise ValueError(label + ': informe JSON')
def pairs(items):
result = {}
for (key, value) in items:
if key in result:
raise ValueError('Chave duplicada: ' + key)
result[key] = value
return result
def number(token):
if '.' not in token and 'e' not in token.lower() and (len(token.lstrip('-')) > 16):
raise ValueError('Inteiro fora do intervalo seguro; use string')
value = float(token) if '.' in token or 'e' in token.lower() else int(token)
if not math.isfinite(value):
raise ValueError('Número não finito')
if value == 0 and (token.startswith('-') or re.search('[1-9]', token.lower().split('e')[0])):
raise ValueError('Zero negativo ou underflow')
if value % 1 == 0 and abs(value) > 9007199254740991:
raise ValueError('Inteiro fora do intervalo seguro; use string')
return value
def reject(value):
raise ValueError('Constante JSON inválida: ' + value)
value = json.loads(source, object_pairs_hook=pairs, parse_int=number, parse_float=number, parse_constant=reject)
count = 0
def walk(value, depth=0):
nonlocal count
count += 1
if count > 100000 or depth > 100:
raise ValueError('Limite de 100 níveis ou 100 mil nós JSON')
if isinstance(value, dict):
for child in value.values():
walk(child, depth + 1)
elif isinstance(value, list):
for child in value:
walk(child, depth + 1)
walk(value)
if object_only and (not isinstance(value, dict)):
raise ValueError(label + ': informe objeto JSON')
return value
def output(value):
source = json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)
source = source.encode('utf-8', errors='backslashreplace').decode('utf-8')
if len(source.encode('utf-16-le')) // 2 > 1000000:
raise ValueError('Limite de 1 milhão na saída')
return source
def label(value, title, limit, optional=False):
value = text(value, title)
if re.search('[\\x00-\\x1f\\x7f]', value):
raise ValueError('Controles não permitidos')
value = value.strip()
if not value and (not optional) or len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > limit or re.search('[\\x00-\\x1f\\x7f\\ud800-\\udfff]', value):
raise ValueError(title + ': texto inválido ou fora do limite')
return value
def text(value, title):
if not isinstance(value, str) or len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000:
raise ValueError(title + ': limite de 100 mil unidades UTF-16')
return value
def websocket_payload(values):
source = text(values['body'], 'Conteúdo')
if values['mode'] == 'Texto':
if re.search('[\\ud800-\\udfff]', source):
raise ValueError('Unicode inválido')
return source
if values['mode'] != 'JSON':
raise ValueError('Escolha JSON ou Texto')
event = label(values['eventType'], 'Tipo', 100)
correlation = label(values['requestId'], 'ID', 200, True)
data = {'type': event, 'data': read(source, 'Dados do evento')}
if correlation:
data['id'] = correlation
return output(data)
return websocket_payload(values)
<?php
function executar($values) {
$text = function ($value,$title) {
if (!is_string($value) || !preg_match('//u',$value) || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($title.': texto UTF-8 válido, até 100 mil unidades UTF-16');
return $value;
};
$label = function ($value,$title,$limit,$optional=false) use ($text) {
$value = $text($value,$title);
if (preg_match('/[\x00-\x1f\x7f]/',$value)) throw new InvalidArgumentException('Controles não permitidos');
$value = trim($value);
if ($value==='' && !$optional || strlen(iconv('UTF-8','UTF-16LE',$value))/2>$limit || preg_match('/[\x00-\x1f\x7f]/',$value)) throw new InvalidArgumentException($title.': texto inválido ou fora do limite');
return $value;
};
$read = function ($source, $label, $objectOnly = false) use ($text) {
$source = $text($source, $label);
if (trim($source) === '') throw new InvalidArgumentException($label.': informe JSON');
json_decode($source, false, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$stack = [];
for ($i = 0; $i < strlen($source); $i++) {
$ch = $source[$i];
if ($ch === '{' || $ch === '[') { $stack[] = ['object'=>$ch === '{', 'keys'=>[]]; continue; }
if ($ch === '}' || $ch === ']') { array_pop($stack); continue; }
if ($ch === '"') {
$start = $i; $escaped = false;
while (++$i < strlen($source)) { $c = $source[$i]; if ($escaped) $escaped = false; elseif ($c === '\\') $escaped = true; elseif ($c === '"') break; }
$look = $i + 1; while ($look < strlen($source) && str_contains(" \t\r\n", $source[$look])) $look++;
$index = count($stack) - 1;
if ($index >= 0 && $stack[$index]['object'] && ($source[$look] ?? '') === ':') {
$key = json_decode(substr($source, $start, $i-$start+1), false, 512, JSON_THROW_ON_ERROR);
if (array_key_exists($key, $stack[$index]['keys'])) throw new InvalidArgumentException('Chave duplicada: '.$key);
$stack[$index]['keys'][$key] = true;
}
} elseif ($ch === '-' || ctype_digit($ch)) {
preg_match('/\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/', $source, $match, 0, $i);
$token = $match[0]; $value = (float)$token; $mantissa = explode('e', strtolower($token))[0];
if (!is_finite($value) || ($value == 0 && (str_starts_with($token, '-') || preg_match('/[1-9]/', $mantissa))) || (floor($value) === $value && abs($value) > 9007199254740991)) throw new InvalidArgumentException('Número não preservável; use string');
$i += strlen($token)-1;
}
}
$value = json_decode($source, false, 512, JSON_THROW_ON_ERROR);
$count = 0;
$walk = function ($value, $depth = 0) use (&$walk, &$count) {
if (++$count > 100000 || $depth > 100) throw new InvalidArgumentException('Limite de 100 níveis ou 100 mil nós JSON');
if (is_object($value) || is_array($value)) foreach ($value as $child) $walk($child, $depth+1);
};
$walk($value);
if ($objectOnly && !is_object($value)) throw new InvalidArgumentException($label.': informe objeto JSON');
return $value;
};
$output = function ($value) {
$source = json_encode($value,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
$source = preg_replace_callback('/^( +)/m',fn($m)=>str_repeat(' ',strlen($m[1])/2),$source);
if (strlen(iconv('UTF-8','UTF-16LE',$source))/2>1000000) throw new InvalidArgumentException('Limite de 1 milhão na saída');
return $source;
};
$websocket_payload = function ($values) use ($text,$label,$read,$output) {
$source = $text($values['body'],'Conteúdo');
if ($values['mode']==='Texto') return $source;
if ($values['mode']!=='JSON') throw new InvalidArgumentException('Escolha JSON ou Texto');
$type = $label($values['eventType'],'Tipo',100); $id = $label($values['requestId'],'ID',200,true);
$data = ['type'=>$type,'data'=>$read($source,'Dados do evento')];
if ($id!=='') $data['id']=$id;
return $output($data);
};
return $websocket_payload($values);
}