JavaScript Python PHP
import { format } from "sql-formatter";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function inspectDatabasePlan(values) {
const input = dbJson(values.input);
if (!Array.isArray(input) || input.length !== 1)
throw new Error('Cole EXPLAIN (FORMAT JSON) do PostgreSQL como lista com exatamente um plano. Texto, YAML, outros bancos e múltiplos planos não são suportados.');
const document = dbObject(input[0]), root = dbObject(document.Plan), nodes = [];
const numeric = (node, key) => { const value = node[key]; if (value === undefined)
return undefined; if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
throw new Error('Métrica inválida: ' + key); return value; };
function visit(node, depth) {
if (depth > 50 || nodes.length >= 500)
throw new Error('Plano excede 50 níveis ou 500 operações.');
const operation = dbString(node['Node Type'], 'Node Type'), rows = numeric(node, 'Plan Rows'), actual = numeric(node, 'Actual Rows'), loops = numeric(node, 'Actual Loops'), cost = numeric(node, 'Total Cost'), time = numeric(node, 'Actual Total Time'), warnings = [];
if (operation === 'Seq Scan')
warnings.push('Leitura sequencial: pode ser adequada para tabelas pequenas ou baixa seletividade; não prova falta de índice.');
if (rows !== undefined && actual !== undefined && Math.max(rows, actual) >= 100 && (Math.min(rows, actual) === 0 || Math.max(rows, actual) / Math.min(rows, actual) >= 10))
warnings.push('Estimativa e linhas reais diferem por fator ≥ 10 (com pelo menos 100 linhas). Investigue estatísticas e seletividade.');
if (typeof node['Sort Method'] === 'string' && /external/i.test(node['Sort Method']))
warnings.push('Ordenação externa: pode ter utilizado disco; confira memória e volume de dados.');
if ((numeric(node, 'Temp Read Blocks') ?? 0) + (numeric(node, 'Temp Written Blocks') ?? 0) > 0)
warnings.push('Operação informa blocos temporários; avalie pressão de memória e I/O.');
if (operation === 'Nested Loop' && (loops ?? 0) > 1000)
warnings.push('Muitas repetições em Nested Loop: avalie os nós internos; o total de loops isolado não prova gargalo.');
nodes.push({ depth, operation, relation: node['Relation Name'], index: node['Index Name'], estimatedRows: rows, actualRowsPerLoop: actual, loops, totalCost: cost, actualTimeMsPerLoop: time, warnings });
if (node.Plans !== undefined) {
if (!Array.isArray(node.Plans))
throw new Error('Plans deve ser lista.');
for (const child of node.Plans)
visit(dbObject(child), depth + 1);
}
}
visit(root, 0);
return dbOutput(JSON.stringify({ planningTimeMs: numeric(document, 'Planning Time'), executionTimeMs: numeric(document, 'Execution Time'), operations: nodes, note: 'Custos são estimativas em unidades do planejador, não milissegundos. Tempos e linhas reais são médias por loop; tempos dos pais incluem filhos e não devem ser somados. Alertas são heurísticas, não diagnóstico. A ferramenta apenas lê o plano fornecido.' }, null, 2));
}
function dbJson(input) { return parseJsonCompatible(dbText(input), 'JSON'); }
function dbObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error('Informe um objeto JSON.');
return value;
}
function dbString(value, label) { if (typeof value !== 'string' || !value)
throw new Error(label + ': informe texto não vazio.'); return dbText(value, label); }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
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)) dbText(value);
return inspectDatabasePlan(values);
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm indicados no código abaixo.
source = r'''
import { format } from "sql-formatter";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function inspectDatabasePlan(values) {
const input = dbJson(values.input);
if (!Array.isArray(input) || input.length !== 1)
throw new Error('Cole EXPLAIN (FORMAT JSON) do PostgreSQL como lista com exatamente um plano. Texto, YAML, outros bancos e múltiplos planos não são suportados.');
const document = dbObject(input[0]), root = dbObject(document.Plan), nodes = [];
const numeric = (node, key) => { const value = node[key]; if (value === undefined)
return undefined; if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
throw new Error('Métrica inválida: ' + key); return value; };
function visit(node, depth) {
if (depth > 50 || nodes.length >= 500)
throw new Error('Plano excede 50 níveis ou 500 operações.');
const operation = dbString(node['Node Type'], 'Node Type'), rows = numeric(node, 'Plan Rows'), actual = numeric(node, 'Actual Rows'), loops = numeric(node, 'Actual Loops'), cost = numeric(node, 'Total Cost'), time = numeric(node, 'Actual Total Time'), warnings = [];
if (operation === 'Seq Scan')
warnings.push('Leitura sequencial: pode ser adequada para tabelas pequenas ou baixa seletividade; não prova falta de índice.');
if (rows !== undefined && actual !== undefined && Math.max(rows, actual) >= 100 && (Math.min(rows, actual) === 0 || Math.max(rows, actual) / Math.min(rows, actual) >= 10))
warnings.push('Estimativa e linhas reais diferem por fator ≥ 10 (com pelo menos 100 linhas). Investigue estatísticas e seletividade.');
if (typeof node['Sort Method'] === 'string' && /external/i.test(node['Sort Method']))
warnings.push('Ordenação externa: pode ter utilizado disco; confira memória e volume de dados.');
if ((numeric(node, 'Temp Read Blocks') ?? 0) + (numeric(node, 'Temp Written Blocks') ?? 0) > 0)
warnings.push('Operação informa blocos temporários; avalie pressão de memória e I/O.');
if (operation === 'Nested Loop' && (loops ?? 0) > 1000)
warnings.push('Muitas repetições em Nested Loop: avalie os nós internos; o total de loops isolado não prova gargalo.');
nodes.push({ depth, operation, relation: node['Relation Name'], index: node['Index Name'], estimatedRows: rows, actualRowsPerLoop: actual, loops, totalCost: cost, actualTimeMsPerLoop: time, warnings });
if (node.Plans !== undefined) {
if (!Array.isArray(node.Plans))
throw new Error('Plans deve ser lista.');
for (const child of node.Plans)
visit(dbObject(child), depth + 1);
}
}
visit(root, 0);
return dbOutput(JSON.stringify({ planningTimeMs: numeric(document, 'Planning Time'), executionTimeMs: numeric(document, 'Execution Time'), operations: nodes, note: 'Custos são estimativas em unidades do planejador, não milissegundos. Tempos e linhas reais são médias por loop; tempos dos pais incluem filhos e não devem ser somados. Alertas são heurísticas, não diagnóstico. A ferramenta apenas lê o plano fornecido.' }, null, 2));
}
function dbJson(input) { return parseJsonCompatible(dbText(input), 'JSON'); }
function dbObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error('Informe um objeto JSON.');
return value;
}
function dbString(value, label) { if (typeof value !== 'string' || !value)
throw new Error(label + ': informe texto não vazio.'); return dbText(value, label); }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
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)) dbText(value);
return inspectDatabasePlan(values);
}
let input = "";
for await (const chunk of process.stdin) input += chunk;
try { process.stdout.write(JSON.stringify({ok: true, result: executar(JSON.parse(input))})); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
'''
payload = json.dumps(values, ensure_ascii=True)
process = subprocess.run(["node", "--input-type=module", "-e", source], input=payload, capture_output=True, text=True, timeout=10, check=True)
response = json.loads(process.stdout)
if not response["ok"]:
raise ValueError(response["error"])
return response["result"]
<?php
function executar(array $values): string {
// Requer Node.js 22+ e os pacotes npm indicados no código abaixo.
$source = <<<'JAVASCRIPT'
import { format } from "sql-formatter";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function inspectDatabasePlan(values) {
const input = dbJson(values.input);
if (!Array.isArray(input) || input.length !== 1)
throw new Error('Cole EXPLAIN (FORMAT JSON) do PostgreSQL como lista com exatamente um plano. Texto, YAML, outros bancos e múltiplos planos não são suportados.');
const document = dbObject(input[0]), root = dbObject(document.Plan), nodes = [];
const numeric = (node, key) => { const value = node[key]; if (value === undefined)
return undefined; if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
throw new Error('Métrica inválida: ' + key); return value; };
function visit(node, depth) {
if (depth > 50 || nodes.length >= 500)
throw new Error('Plano excede 50 níveis ou 500 operações.');
const operation = dbString(node['Node Type'], 'Node Type'), rows = numeric(node, 'Plan Rows'), actual = numeric(node, 'Actual Rows'), loops = numeric(node, 'Actual Loops'), cost = numeric(node, 'Total Cost'), time = numeric(node, 'Actual Total Time'), warnings = [];
if (operation === 'Seq Scan')
warnings.push('Leitura sequencial: pode ser adequada para tabelas pequenas ou baixa seletividade; não prova falta de índice.');
if (rows !== undefined && actual !== undefined && Math.max(rows, actual) >= 100 && (Math.min(rows, actual) === 0 || Math.max(rows, actual) / Math.min(rows, actual) >= 10))
warnings.push('Estimativa e linhas reais diferem por fator ≥ 10 (com pelo menos 100 linhas). Investigue estatísticas e seletividade.');
if (typeof node['Sort Method'] === 'string' && /external/i.test(node['Sort Method']))
warnings.push('Ordenação externa: pode ter utilizado disco; confira memória e volume de dados.');
if ((numeric(node, 'Temp Read Blocks') ?? 0) + (numeric(node, 'Temp Written Blocks') ?? 0) > 0)
warnings.push('Operação informa blocos temporários; avalie pressão de memória e I/O.');
if (operation === 'Nested Loop' && (loops ?? 0) > 1000)
warnings.push('Muitas repetições em Nested Loop: avalie os nós internos; o total de loops isolado não prova gargalo.');
nodes.push({ depth, operation, relation: node['Relation Name'], index: node['Index Name'], estimatedRows: rows, actualRowsPerLoop: actual, loops, totalCost: cost, actualTimeMsPerLoop: time, warnings });
if (node.Plans !== undefined) {
if (!Array.isArray(node.Plans))
throw new Error('Plans deve ser lista.');
for (const child of node.Plans)
visit(dbObject(child), depth + 1);
}
}
visit(root, 0);
return dbOutput(JSON.stringify({ planningTimeMs: numeric(document, 'Planning Time'), executionTimeMs: numeric(document, 'Execution Time'), operations: nodes, note: 'Custos são estimativas em unidades do planejador, não milissegundos. Tempos e linhas reais são médias por loop; tempos dos pais incluem filhos e não devem ser somados. Alertas são heurísticas, não diagnóstico. A ferramenta apenas lê o plano fornecido.' }, null, 2));
}
function dbJson(input) { return parseJsonCompatible(dbText(input), 'JSON'); }
function dbObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error('Informe um objeto JSON.');
return value;
}
function dbString(value, label) { if (typeof value !== 'string' || !value)
throw new Error(label + ': informe texto não vazio.'); return dbText(value, label); }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
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)) dbText(value);
return inspectDatabasePlan(values);
}
let input = "";
for await (const chunk of process.stdin) input += chunk;
try { process.stdout.write(JSON.stringify({ok: true, result: executar(JSON.parse(input))})); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
JAVASCRIPT;
$payload = json_encode($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) { fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); proc_terminate($process); proc_close($process); throw new RuntimeException("Falha ao enviar a entrada."); }
$offset += $written;
}
fclose($pipes[0]);
stream_set_timeout($pipes[1], 10);
$output = stream_get_contents($pipes[1]);
$timedOut = stream_get_meta_data($pipes[1])["timed_out"];
fclose($pipes[1]);
if ($timedOut) { proc_terminate($process); }
stream_get_contents($pipes[2]); fclose($pipes[2]);
$status = proc_close($process);
if ($timedOut || $status !== 0) { throw new RuntimeException("Falha técnica ou limite de tempo no Node.js. Confira os pacotes npm necessários."); }
$response = json_decode($output, true, 512, JSON_THROW_ON_ERROR);
if (!$response["ok"]) { throw new InvalidArgumentException($response["error"]); }
return $response["result"];
}