JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
function convertInfraEnv(v) {
const direction = infraChoice(v.direction, ['ENV → JSON', 'JSON → ENV']);
if (direction === 'ENV → JSON')
return { text: JSON.stringify(parseInfraEnv(v.input).values, null, 2) };
const values = infraEnvironment(v.input), text = Object.entries(values).map(([key, value]) => key + '=' + encodeInfraEnvValue(value)).join('\n') + (Object.keys(values).length ? '\n' : '');
return { text, files: [{ name: 'variaveis.env', content: text }] };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} 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 infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function infraEnvironment(input) {
const data = parseJsonCompatible(infraText(input), 'JSON');
if (!data || typeof data !== 'object' || Array.isArray(data))
throw new Error('Informe um objeto JSON de strings, sem listas ou valores aninhados.');
if (Object.keys(data).length > 200)
throw new Error('Limite de 200 variáveis.');
const result = Object.create(null);
for (const [key, value] of Object.entries(data)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
throw new Error('Nome de variável inválido: ' + key);
if (typeof value !== 'string')
throw new Error('A variável ' + key + ' precisa ser string, inclusive números, booleanos e valores vazios.');
result[key] = infraText(value);
}
return result;
}
function parseInfraEnv(input) {
const source = infraText(input).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n'), values = Object.create(null), parts = [];
let position = 0;
const fail = (message, offset = position) => { const prefix = source.slice(0, offset), line = prefix.split('\n').length, column = offset - prefix.lastIndexOf('\n'); throw new Error(`ENV: ${message} (linha ${line}, coluna ${column}).`); };
while (position < source.length) {
const start = position;
while (/[\t ]/.test(source[position] || '\0'))
position++;
if (source[position] === '#' || source[position] === '\n' || position === source.length) {
while (position < source.length && source[position] !== '\n')
position++;
if (source[position] === '\n')
position++;
parts.push({ raw: source.slice(start, position) });
continue;
}
if (source.slice(position).startsWith('export ') || source.slice(position).startsWith('export\t')) {
position += 6;
while (/[\t ]/.test(source[position] || '\0'))
position++;
}
const match = source.slice(position).match(/^[A-Za-z_][A-Za-z0-9_]*/);
if (!match)
fail('nome de variável inválido');
const key = match[0];
position += key.length;
while (/[\t ]/.test(source[position] || '\0'))
position++;
if (source[position] !== '=')
fail('esperado = após o nome');
position++;
while (/[\t ]/.test(source[position] || '\0'))
position++;
const valueStart = position;
let value = '', valueEnd = position;
const quote = source[position];
if (quote === '"' || quote === "'" || quote === '`') {
position++;
const content = position;
while (position < source.length && source[position] !== quote)
position++;
if (position === source.length)
fail('aspas não fechadas', valueStart);
value = source.slice(content, position);
position++;
valueEnd = position;
if (quote === '"')
value = value.replace(/\\n/g, '\n').replace(/\\r/g, '\r');
while (/[\t ]/.test(source[position] || '\0'))
position++;
if (position < source.length && source[position] !== '#' && source[position] !== '\n')
fail('conteúdo extra após as aspas; escapes do delimitador não são suportados');
}
else {
while (position < source.length && source[position] !== '\n' && source[position] !== '#')
position++;
valueEnd = position;
while (valueEnd > valueStart && /[\t ]/.test(source[valueEnd - 1]))
valueEnd--;
value = source.slice(valueStart, valueEnd);
}
while (position < source.length && source[position] !== '\n')
position++;
if (source[position] === '\n')
position++;
if (Object.hasOwn(values, key))
fail('variável duplicada: ' + key, start);
if (Object.keys(values).length >= 200)
fail('limite de 200 variáveis', start);
values[key] = value;
parts.push({ raw: source.slice(start, position), key, value, prefix: source.slice(start, valueStart), suffix: source.slice(valueEnd, position) });
}
return { values, parts };
}
function encodeInfraEnvValue(value) {
infraText(value);
if (value === '')
return '';
const candidates = [];
if (!/[#\r\n]/.test(value) && value.trim() === value && !/^["'`]/.test(value))
candidates.push(value);
if (!value.includes("'") && !value.includes('\r'))
candidates.push("'" + value + "'");
if (!value.includes('`') && !value.includes('\r'))
candidates.push('`' + value + '`');
if (!value.includes('"') && !/\\[nr]/.test(value))
candidates.push('"' + value.replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '"');
for (const candidate of candidates)
if (parseInfraEnv('VALUE=' + candidate).values.VALUE === value)
return candidate;
throw new Error('O valor combina aspas/escapes sem representação fiel no subconjunto ENV. Mantenha-o em JSON ou ajuste conscientemente a configuração; nenhum caractere foi descartado.');
}
const keys = ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
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}`));
for (const value of Object.values(values)) infraText(value);
const output = await convertInfraEnv(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
import json
import re
def executar(values):
def text(value, limit=100000):
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > limit or re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff\ud800-\udfff]', value):
raise ValueError('Texto excede o limite ou contém caracteres inválidos.')
return value
def choice(value, options):
if value not in options:
raise ValueError('Opção não suportada.')
return value
def read_env(source):
source = text(source).removeprefix('\ufeff').replace('\r\n', '\n').replace('\r', '\n')
position, result, parts = 0, {}, []
def fail(message):
line = source[:position].count('\n') + 1
column = position - source.rfind('\n', 0, position)
raise ValueError(f'ENV: {message} (linha {line}, coluna {column}).')
while position < len(source):
start = position
while position < len(source) and source[position] in ' \t': position += 1
if position == len(source) or source[position] in '#\n':
while position < len(source) and source[position] != '\n': position += 1
if position < len(source): position += 1
parts.append({'raw': source[start:position]})
continue
if source[position:].startswith(('export ', 'export\t')):
position += 6
while position < len(source) and source[position] in ' \t': position += 1
match = re.match(r'[A-Za-z_][A-Za-z0-9_]*', source[position:])
if not match: fail('nome de variável inválido')
key = match[0]
position += len(key)
while position < len(source) and source[position] in ' \t': position += 1
if position >= len(source) or source[position] != '=': fail('esperado =')
position += 1
while position < len(source) and source[position] in ' \t': position += 1
value_start = position
if position < len(source) and source[position] in "'\"`":
quote = source[position]
position += 1
content = position
while position < len(source) and source[position] != quote: position += 1
if position == len(source): fail('aspas não fechadas')
value = source[content:position]
position += 1
value_end = position
if quote == '"': value = value.replace('\\n', '\n').replace('\\r', '\r')
while position < len(source) and source[position] in ' \t': position += 1
if position < len(source) and source[position] not in '#\n': fail('conteúdo extra após aspas')
else:
while position < len(source) and source[position] not in '#\n': position += 1
value_end = position
while value_end > value_start and source[value_end - 1] in ' \t': value_end -= 1
value = source[value_start:value_end]
while position < len(source) and source[position] != '\n': position += 1
if position < len(source): position += 1
if key in result: fail('variável duplicada: ' + key)
if len(result) >= 200: fail('limite de 200 variáveis')
result[key] = value
parts.append({'key': key, 'prefix': source[start:value_start], 'suffix': source[value_end:position]})
return result, parts
def encode_env(value):
text(value)
if value == '': return ''
candidates = []
if not re.search(r'[#\r\n]', value) and value.strip() == value and value[0] not in "'\"`": candidates.append(value)
if "'" not in value and '\r' not in value: candidates.append("'" + value + "'")
if '`' not in value and '\r' not in value: candidates.append('`' + value + '`')
if '"' not in value and not re.search(r'\\[nr]', value): candidates.append('"' + value.replace('\n', '\\n').replace('\r', '\\r') + '"')
for candidate in candidates:
if read_env('VALUE=' + candidate)[0]['VALUE'] == value: return candidate
raise ValueError('Valor sem representação fiel no subconjunto ENV.')
def object_strings(source):
def pairs(items):
output = {}
for key, value in items:
if key in output: raise ValueError('Chave JSON duplicada: ' + key)
output[key] = value
return output
data = json.loads(text(source), object_pairs_hook=pairs)
if not isinstance(data, dict) or len(data) > 200: raise ValueError('Use objeto JSON de até 200 strings.')
for key, value in data.items():
if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', key) or not isinstance(value, str): raise ValueError('Nome inválido ou valor não textual.')
text(value)
return data
for value in values.values(): text(value)
direction = choice(values['direction'], ['ENV → JSON', 'JSON → ENV'])
if direction == 'ENV → JSON': return {'text': json.dumps(read_env(values['input'])[0], ensure_ascii=False, indent=2)}
data = object_strings(values['input'])
output = '\n'.join(key + '=' + encode_env(value) for key, value in data.items()) + ('\n' if data else '')
return {'text': output, 'files': [{'name': 'variaveis.env', 'content': output}]}
<?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; };
$choice = static function ($value, $options) { if (!in_array($value, $options, true)) throw new InvalidArgumentException('Opção não suportada.'); return $value; };
$readEnv = static function ($source) use ($text) {
$source = preg_replace('/^\xEF\xBB\xBF/', '', $text($source)); $source = str_replace(["\r\n", "\r"], "\n", $source); $p = 0; $size = strlen($source); $values = []; $parts = [];
$fail = static function ($message) use (&$p, $source) { throw new InvalidArgumentException('ENV: ' . $message . ' (linha ' . (substr_count(substr($source, 0, $p), "\n") + 1) . ').'); };
while ($p < $size) {
$start = $p; while ($p < $size && str_contains(" \t", $source[$p])) $p++;
if ($p === $size || $source[$p] === '#' || $source[$p] === "\n") { while ($p < $size && $source[$p] !== "\n") $p++; if ($p < $size) $p++; $parts[] = ['raw' => substr($source, $start, $p - $start)]; continue; }
if (str_starts_with(substr($source, $p), 'export ') || str_starts_with(substr($source, $p), "export\t")) { $p += 6; while ($p < $size && str_contains(" \t", $source[$p])) $p++; }
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*/', substr($source, $p), $match)) $fail('nome inválido'); $key = $match[0]; $p += strlen($key);
while ($p < $size && str_contains(" \t", $source[$p])) $p++; if ($p === $size || $source[$p] !== '=') $fail('esperado ='); $p++; while ($p < $size && str_contains(" \t", $source[$p])) $p++; $valueStart = $p;
if ($p < $size && str_contains("'\"`", $source[$p])) { $quote = $source[$p++]; $content = $p; while ($p < $size && $source[$p] !== $quote) $p++; if ($p === $size) $fail('aspas não fechadas'); $value = substr($source, $content, $p - $content); $p++; $valueEnd = $p; if ($quote === '"') $value = str_replace(['\\n', '\\r'], ["\n", "\r"], $value); while ($p < $size && str_contains(" \t", $source[$p])) $p++; if ($p < $size && $source[$p] !== '#' && $source[$p] !== "\n") $fail('conteúdo extra após aspas'); }
else { while ($p < $size && $source[$p] !== '#' && $source[$p] !== "\n") $p++; $valueEnd = $p; while ($valueEnd > $valueStart && str_contains(" \t", $source[$valueEnd - 1])) $valueEnd--; $value = substr($source, $valueStart, $valueEnd - $valueStart); }
while ($p < $size && $source[$p] !== "\n") $p++; if ($p < $size) $p++; if (array_key_exists($key, $values)) $fail('variável duplicada: ' . $key); if (count($values) >= 200) $fail('limite de 200 variáveis'); $values[$key] = $value; $parts[] = ['key' => $key, 'prefix' => substr($source, $start, $valueStart - $start), 'suffix' => substr($source, $valueEnd, $p - $valueEnd)];
}
return [$values, $parts];
};
$encodeEnv = static function ($value) use ($text, $readEnv) {
$text($value); if ($value === '') return ''; $candidates = [];
if (!preg_match('/[#\r\n]/', $value) && trim($value) === $value && !str_contains("'\"`", $value[0])) $candidates[] = $value;
if (!str_contains($value, "'") && !str_contains($value, "\r")) $candidates[] = "'" . $value . "'";
if (!str_contains($value, '`') && !str_contains($value, "\r")) $candidates[] = '`' . $value . '`';
if (!str_contains($value, '"') && !preg_match('/\\\\[nr]/', $value)) $candidates[] = '"' . str_replace(["\n", "\r"], ['\\n', '\\r'], $value) . '"';
foreach ($candidates as $candidate) if ($readEnv('VALUE=' . $candidate)[0]['VALUE'] === $value) return $candidate;
throw new InvalidArgumentException('Valor sem representação fiel no subconjunto ENV.');
};
$objectStrings = static function ($source) use ($text) {
$source = $text($source); $p = 0; $n = strlen($source); $result = [];
$space = static function () use (&$p, $source, $n) { while ($p < $n && str_contains(" \t\r\n", $source[$p])) $p++; };
$string = static function () use (&$p, $source, $n) { if ($p >= $n || $source[$p] !== '"') throw new InvalidArgumentException('JSON exige nomes e valores string.'); $start = $p++; while ($p < $n) { if ($source[$p] === '\\') { $p += 2; continue; } if ($source[$p++] === '"') return json_decode(substr($source, $start, $p - $start), true, 512, JSON_THROW_ON_ERROR); } throw new InvalidArgumentException('String JSON incompleta.'); };
$space(); if (($source[$p++] ?? '') !== '{') throw new InvalidArgumentException('Use objeto JSON de strings.'); $space(); if (($source[$p] ?? '') === '}') $p++; else while (true) { $space(); $key = $string(); $space(); if (($source[$p++] ?? '') !== ':') throw new InvalidArgumentException('Esperado :'); $space(); $value = $string(); if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/D', $key) || array_key_exists($key, $result) || count($result) >= 200) throw new InvalidArgumentException('Nome inválido, duplicado ou limite excedido.'); $text($value); $result[$key] = $value; $space(); $next = $source[$p++] ?? ''; if ($next === '}') break; if ($next !== ',') throw new InvalidArgumentException('JSON inválido.'); }
$space(); if ($p !== $n) throw new InvalidArgumentException('Conteúdo extra após o JSON.'); return $result;
};
foreach ($values as $value) $text($value);
$direction = $choice($values['direction'], ['ENV → JSON', 'JSON → ENV']);
if ($direction === 'ENV → JSON') { $data = $readEnv($values['input'])[0]; $lines = []; foreach ($data as $key => $value) $lines[] = ' ' . json_encode($key, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR) . ': ' . json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR); return ['text' => count($lines) ? "{\n" . implode(",\n", $lines) . "\n}" : '{}']; }
$data = $objectStrings($values['input']); $lines = []; foreach ($data as $key => $value) $lines[] = $key . '=' . $encodeEnv($value); $output = implode("\n", $lines) . (count($lines) ? "\n" : '');
return ['text' => $output, 'files' => [['name' => 'variaveis.env', 'content' => $output]]];
}