JavaScript Python PHP
import * as __pacote0 from "graphql";
import * as __pacote1 from "yaml";
function executar(values) {
const variant = values.variant ?? "payload";
function convertSelected() {
if (variant === "payload") {
const parameters = { ...{"document":"","variables":"{}","operationName":""}, ...values };
const GraphQLObjectType = __pacote0["GraphQLObjectType"];
const GraphQLSchema = __pacote0["GraphQLSchema"];
const GraphQLString = __pacote0["GraphQLString"];
const Kind = __pacote0["Kind"];
const OperationTypeNode = __pacote0["OperationTypeNode"];
const parse = __pacote0["parse"];
const validate = __pacote0["validate"];
const visit = __pacote0["visit"];
const ExecutableDefinitionsRule = __pacote0["ExecutableDefinitionsRule"];
const UniqueOperationNamesRule = __pacote0["UniqueOperationNamesRule"];
const LoneAnonymousOperationRule = __pacote0["LoneAnonymousOperationRule"];
const KnownFragmentNamesRule = __pacote0["KnownFragmentNamesRule"];
const NoFragmentCyclesRule = __pacote0["NoFragmentCyclesRule"];
const NoUnusedFragmentsRule = __pacote0["NoUnusedFragmentsRule"];
const UniqueFragmentNamesRule = __pacote0["UniqueFragmentNamesRule"];
const UniqueVariableNamesRule = __pacote0["UniqueVariableNamesRule"];
const NoUndefinedVariablesRule = __pacote0["NoUndefinedVariablesRule"];
const NoUnusedVariablesRule = __pacote0["NoUnusedVariablesRule"];
const UniqueArgumentNamesRule = __pacote0["UniqueArgumentNamesRule"];
const UniqueInputFieldNamesRule = __pacote0["UniqueInputFieldNamesRule"];
const isAlias = __pacote1["isAlias"];
const isMap = __pacote1["isMap"];
const isScalar = __pacote1["isScalar"];
const isSeq = __pacote1["isSeq"];
const LineCounter = __pacote1["LineCounter"];
const parseDocument = __pacote1["parseDocument"];
function convert(values) {
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
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);
}
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) {
throw new Error(label + ': ' + (cause instanceof Error ? cause.message : 'JSON inválido.'));
}
}
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 name(input, label, optional = false) {
const value = text(input, label).trim();
if (optional && !value)
return '';
if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(value))
throw new Error(label + ': use um nome GraphQL, sem $, espaços, acentos ou pontuação.');
return value;
}
function executable(input) {
let document;
try {
document = parse(text(input, 'Documento GraphQL'), { maxTokens: 10000 });
}
catch (cause) {
const error = cause;
const at = error.locations?.[0];
throw new Error('GraphQL inválido' + (at ? ` (linha ${at.line}, coluna ${at.column})` : '') + ': ' + (error.message || 'erro de sintaxe.'));
}
let nodes = 0, depth = 0;
visit(document, { enter() { if (++nodes > 10000 || ++depth > 50)
throw new Error('GraphQL: limite de 10 mil nós e 50 níveis de AST.'); }, leave() { depth--; } });
const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { placeholder: { type: GraphQLString } } }) });
const errors = validate(schema, document, [
ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule,
KnownFragmentNamesRule, NoFragmentCyclesRule, NoUnusedFragmentsRule,
UniqueFragmentNamesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule,
NoUnusedVariablesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule,
]);
if (errors.length) {
const at = errors[0].locations?.[0];
throw new Error('Documento GraphQL inválido' + (at ? ` (linha ${at.line}, coluna ${at.column})` : '') + ': ' + errors[0].message);
}
return document;
}
function generateGraphqlPayload(values) {
const source = text(values.document, 'Documento GraphQL').trim();
const document = executable(source);
const operations = document.definitions.filter((definition) => definition.kind === Kind.OPERATION_DEFINITION);
const operationName = name(values.operationName, 'Nome da operação', true);
if (!operations.length)
throw new Error('Informe ao menos uma operação query ou mutation.');
if (operations.some(operation => operation.operation === OperationTypeNode.SUBSCRIPTION))
throw new Error('Subscriptions não são suportadas por este gerador de payload HTTP.');
if (!operationName && operations.length !== 1)
throw new Error('O documento contém várias operações: informe o nome da operação desejada.');
const selected = operationName ? operations.find(operation => operation.name?.value === operationName) : operations[0];
if (!selected)
throw new Error('Nome da operação não encontrado no documento.');
const variables = json(text(values.variables, 'Variáveis').trim() || '{}', 'Variáveis', true);
const declarations = selected.variableDefinitions ?? [];
const known = new Set(declarations.map(definition => definition.variable.name.value));
for (const key of Object.keys(variables))
if (!known.has(key))
throw new Error('Variável não declarada na operação selecionada: $' + key);
for (const declaration of declarations) {
const key = declaration.variable.name.value;
if (declaration.type.kind === Kind.NON_NULL_TYPE && declaration.defaultValue?.kind === Kind.NULL)
throw new Error('A variável não nula $' + key + ' não pode ter default null.');
if (declaration.type.kind === Kind.NON_NULL_TYPE && ((!Object.hasOwn(variables, key) && !declaration.defaultValue) || (Object.hasOwn(variables, key) && variables[key] === null)))
throw new Error('Informe um valor não nulo para $' + key);
}
return result({ query: source, variables, ...(operationName ? { operationName } : {}) });
}
return generateGraphqlPayload(values);
}
return convert(parameters);
}
if (variant === "query") {
const parameters = { ...{"field":"","selection":"","variableTypes":"{}","arguments":"{}","operationName":""}, ...values };
const GraphQLObjectType = __pacote0["GraphQLObjectType"];
const GraphQLSchema = __pacote0["GraphQLSchema"];
const GraphQLString = __pacote0["GraphQLString"];
const Kind = __pacote0["Kind"];
const OperationTypeNode = __pacote0["OperationTypeNode"];
const parse = __pacote0["parse"];
const parseType = __pacote0["parseType"];
const print = __pacote0["print"];
const validate = __pacote0["validate"];
const visit = __pacote0["visit"];
const ExecutableDefinitionsRule = __pacote0["ExecutableDefinitionsRule"];
const UniqueOperationNamesRule = __pacote0["UniqueOperationNamesRule"];
const LoneAnonymousOperationRule = __pacote0["LoneAnonymousOperationRule"];
const KnownFragmentNamesRule = __pacote0["KnownFragmentNamesRule"];
const NoFragmentCyclesRule = __pacote0["NoFragmentCyclesRule"];
const NoUnusedFragmentsRule = __pacote0["NoUnusedFragmentsRule"];
const UniqueFragmentNamesRule = __pacote0["UniqueFragmentNamesRule"];
const UniqueVariableNamesRule = __pacote0["UniqueVariableNamesRule"];
const NoUndefinedVariablesRule = __pacote0["NoUndefinedVariablesRule"];
const NoUnusedVariablesRule = __pacote0["NoUnusedVariablesRule"];
const UniqueArgumentNamesRule = __pacote0["UniqueArgumentNamesRule"];
const UniqueInputFieldNamesRule = __pacote0["UniqueInputFieldNamesRule"];
const isAlias = __pacote1["isAlias"];
const isMap = __pacote1["isMap"];
const isScalar = __pacote1["isScalar"];
const isSeq = __pacote1["isSeq"];
const LineCounter = __pacote1["LineCounter"];
const parseDocument = __pacote1["parseDocument"];
function convert(values) {
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
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);
}
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) {
throw new Error(label + ': ' + (cause instanceof Error ? cause.message : 'JSON inválido.'));
}
}
function name(input, label, optional = false) {
const value = text(input, label).trim();
if (optional && !value)
return '';
if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(value))
throw new Error(label + ': use um nome GraphQL, sem $, espaços, acentos ou pontuação.');
return value;
}
function executable(input) {
let document;
try {
document = parse(text(input, 'Documento GraphQL'), { maxTokens: 10000 });
}
catch (cause) {
const error = cause;
const at = error.locations?.[0];
throw new Error('GraphQL inválido' + (at ? ` (linha ${at.line}, coluna ${at.column})` : '') + ': ' + (error.message || 'erro de sintaxe.'));
}
let nodes = 0, depth = 0;
visit(document, { enter() { if (++nodes > 10000 || ++depth > 50)
throw new Error('GraphQL: limite de 10 mil nós e 50 níveis de AST.'); }, leave() { depth--; } });
const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { placeholder: { type: GraphQLString } } }) });
const errors = validate(schema, document, [
ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule,
KnownFragmentNamesRule, NoFragmentCyclesRule, NoUnusedFragmentsRule,
UniqueFragmentNamesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule,
NoUnusedVariablesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule,
]);
if (errors.length) {
const at = errors[0].locations?.[0];
throw new Error('Documento GraphQL inválido' + (at ? ` (linha ${at.line}, coluna ${at.column})` : '') + ': ' + errors[0].message);
}
return document;
}
function generateGraphqlQuery(values) {
const field = name(values.field, 'Campo raiz');
const operationName = name(values.operationName, 'Nome da operação', true);
const types = json(text(values.variableTypes, 'Tipos de variáveis').trim() || '{}', 'Tipos de variáveis', true);
const bindings = json(text(values.arguments, 'Argumentos').trim() || '{}', 'Argumentos', true);
const definitions = Object.entries(types).map(([key, type]) => {
name(key, 'Nome de variável');
if (typeof type !== 'string')
throw new Error('Tipo da variável $' + key + ': informe uma string como ID! ou [String!].');
return { kind: Kind.VARIABLE_DEFINITION, variable: { kind: Kind.VARIABLE, name: { kind: Kind.NAME, value: key } }, type: parseType(text(type, 'Tipo'), { maxTokens: 100 }), directives: [] };
});
const args = Object.entries(bindings).map(([key, variable]) => {
name(key, 'Nome de argumento');
if (typeof variable !== 'string')
throw new Error('Argumento ' + key + ': informe o nome da variável sem $.');
name(variable, 'Variável do argumento');
return { kind: Kind.ARGUMENT, name: { kind: Kind.NAME, value: key }, value: { kind: Kind.VARIABLE, name: { kind: Kind.NAME, value: variable } } };
});
const selection = text(values.selection, 'Campos de retorno').trim();
const parsed = selection ? parse('{\n' + selection + '\n}', { maxTokens: 10000 }) : null;
if (parsed && (parsed.definitions.length !== 1 || parsed.definitions[0].kind !== Kind.OPERATION_DEFINITION))
throw new Error('Informe somente campos de retorno, sem definições de operações ou fragments.');
const selectionSet = parsed ? parsed.definitions[0].selectionSet : undefined;
const document = { kind: Kind.DOCUMENT, definitions: [{
kind: Kind.OPERATION_DEFINITION, operation: OperationTypeNode.QUERY,
...(operationName ? { name: { kind: Kind.NAME, value: operationName } } : {}),
variableDefinitions: definitions, directives: [],
selectionSet: { kind: Kind.SELECTION_SET, selections: [{ kind: Kind.FIELD, name: { kind: Kind.NAME, value: field }, arguments: args, directives: [], ...(selectionSet ? { selectionSet } : {}) }] },
}] };
const output = print(document);
executable(output);
if (output.length > 1_000_000)
throw new Error('Query excede 1 milhão de caracteres.');
return output;
}
return generateGraphqlQuery(values);
}
return convert(parameters);
}
throw new Error("Selecione uma modalidade válida de API.");
}
return convertSelected();
}
import json
import math
import re
from graphql import parse, validate, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, KnownFragmentNamesRule, NoFragmentCyclesRule, NoUnusedFragmentsRule, UniqueFragmentNamesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule, NoUnusedVariablesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule
from graphql import parse, parse_type, print_ast, validate, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, KnownFragmentNamesRule, NoFragmentCyclesRule, NoUnusedFragmentsRule, UniqueFragmentNamesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule, NoUnusedVariablesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule
def executar(values):
variant = values.get("variant", "payload")
if variant == "payload":
parameters = {**{"document": "", "variables": "{}", "operationName": ""}, **values}
def convert(values):
def text(value, label):
if not isinstance(value, str): raise ValueError(label + ': informe texto')
if len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000: raise ValueError(label + ': limite de 100 mil caracteres')
return value
def read(source, label, object_only=False):
text(source, label)
if not source.strip(): raise ValueError(label + ': informe JSON')
def pairs(items):
output = {}
for key, value in items:
if key in output: raise ValueError('Chave duplicada: ' + key)
output[key] = value
return output
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 um objeto JSON')
return value
def output(value):
result = json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)
if len(result.encode('utf-16-le', errors='surrogatepass')) // 2 > 1000000: raise ValueError('Resultado excede 1 milhão de caracteres')
return result
def name(value, label, optional=False):
value = text(value, label).strip()
if optional and not value: return ''
if not re.fullmatch(r'[_A-Za-z][_0-9A-Za-z]*', value): raise ValueError(label + ': nome GraphQL inválido')
return value
def executable(source):
document = parse(text(source, 'Documento GraphQL'), max_tokens=10000)
count = 0
def walk(node, depth=1):
nonlocal count
if node is None or not hasattr(node, 'kind'): return
count += 1
if count > 10000 or depth > 50: raise ValueError('Limite de 10 mil nós e 50 níveis de AST')
for key in node.keys:
if key == 'loc': continue
child = getattr(node, key, None)
for item in child if isinstance(child, (tuple,list)) else (child,): walk(item, depth + 1)
walk(document)
schema = GraphQLSchema(query=GraphQLObjectType('Query', {'placeholder': GraphQLField(GraphQLString)}))
rules = (ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, KnownFragmentNamesRule, NoFragmentCyclesRule, NoUnusedFragmentsRule, UniqueFragmentNamesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule, NoUnusedVariablesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule)
errors = validate(schema, document, rules=rules)
if errors: raise ValueError('Documento GraphQL inválido: ' + errors[0].message)
return document
def generate_graphql_payload(values):
source = text(values['document'], 'Documento GraphQL').strip()
document = executable(source)
operations = [node for node in document.definitions if node.kind == 'operation_definition']
operation_name = name(values['operationName'], 'Nome da operação', True)
if not operations: raise ValueError('Informe query ou mutation')
if any(operation.operation.value == 'subscription' for operation in operations): raise ValueError('Subscriptions não suportadas')
if not operation_name and len(operations) != 1: raise ValueError('Selecione o nome da operação')
selected = next((operation for operation in operations if operation.name and operation.name.value == operation_name), None) if operation_name else operations[0]
if selected is None: raise ValueError('Operação não encontrada')
variables = read(text(values['variables'], 'Variáveis').strip() or '{}', 'Variáveis', True)
definitions = selected.variable_definitions or ()
known = {definition.variable.name.value for definition in definitions}
if any(key not in known for key in variables): raise ValueError('Variável não declarada na operação selecionada')
for definition in definitions:
key = definition.variable.name.value
if definition.type.kind == 'non_null_type' and definition.default_value and definition.default_value.kind == 'null_value': raise ValueError('Variável não nula não pode ter default null')
if definition.type.kind == 'non_null_type' and ((key not in variables and definition.default_value is None) or (key in variables and variables[key] is None)): raise ValueError('Informe valor não nulo para $' + key)
data = {'query': source, 'variables': variables}
if operation_name: data['operationName'] = operation_name
return output(data)
return generate_graphql_payload(values)
return convert(parameters)
if variant == "query":
parameters = {**{"field": "", "selection": "", "variableTypes": "{}", "arguments": "{}", "operationName": ""}, **values}
def convert(values):
def text(value, label):
if not isinstance(value, str): raise ValueError(label + ': informe texto')
if len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000: raise ValueError(label + ': limite de 100 mil caracteres')
return value
def read(source, label, object_only=False):
text(source, label)
if not source.strip(): raise ValueError(label + ': informe JSON')
def pairs(items):
output = {}
for key, value in items:
if key in output: raise ValueError('Chave duplicada: ' + key)
output[key] = value
return output
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 um objeto JSON')
return value
def name(value, label, optional=False):
value = text(value, label).strip()
if optional and not value: return ''
if not re.fullmatch(r'[_A-Za-z][_0-9A-Za-z]*', value): raise ValueError(label + ': nome GraphQL inválido')
return value
def executable(source):
document = parse(text(source, 'Documento GraphQL'), max_tokens=10000)
count = 0
def walk(node, depth=1):
nonlocal count
if node is None or not hasattr(node, 'kind'): return
count += 1
if count > 10000 or depth > 50: raise ValueError('Limite de 10 mil nós e 50 níveis de AST')
for key in node.keys:
if key == 'loc': continue
child = getattr(node, key, None)
for item in child if isinstance(child, (tuple,list)) else (child,): walk(item, depth + 1)
walk(document)
schema = GraphQLSchema(query=GraphQLObjectType('Query', {'placeholder': GraphQLField(GraphQLString)}))
rules = (ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, KnownFragmentNamesRule, NoFragmentCyclesRule, NoUnusedFragmentsRule, UniqueFragmentNamesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule, NoUnusedVariablesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule)
errors = validate(schema, document, rules=rules)
if errors: raise ValueError('Documento GraphQL inválido: ' + errors[0].message)
return document
def generate_graphql_query(values):
field = name(values['field'], 'Campo raiz')
operation_name = name(values['operationName'], 'Nome da operação', True)
types = read(text(values['variableTypes'], 'Tipos').strip() or '{}', 'Tipos', True)
bindings = read(text(values['arguments'], 'Argumentos').strip() or '{}', 'Argumentos', True)
definitions = []
for key, value in types.items():
name(key, 'Nome de variável')
if not isinstance(value, str): raise ValueError('Tipo deve ser string')
definitions.append('$' + key + ': ' + print_ast(parse_type(text(value, 'Tipo'), max_tokens=100)))
arguments = []
for key, value in bindings.items():
name(key, 'Nome de argumento')
if not isinstance(value, str): raise ValueError('Argumento deve indicar variável sem $')
arguments.append(key + ': $' + name(value, 'Variável do argumento'))
selection = text(values['selection'], 'Campos de retorno').strip()
if selection:
parsed = parse('{\n' + selection + '\n}', max_tokens=10000)
if len(parsed.definitions) != 1 or parsed.definitions[0].kind != 'operation_definition': raise ValueError('Informe somente campos de retorno')
selection = ' ' + print_ast(parsed.definitions[0].selection_set)
header = 'query' + (' ' + operation_name if operation_name else '') + ('(' + ', '.join(definitions) + ')' if definitions else '')
body = field + ('(' + ', '.join(arguments) + ')' if arguments else '') + selection
result = print_ast(executable(header + ' { ' + body + ' }'))
if len(result.encode('utf-16-le', errors='surrogatepass')) // 2 > 1000000: raise ValueError('Query excede limite de saída')
return result
return generate_graphql_query(values)
return convert(parameters)
raise ValueError("Selecione uma modalidade válida de API.")
<?php
require_once 'vendor/autoload.php';
use GraphQL\Language\Parser;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\NodeKind;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\ExecutableDefinitions;
use GraphQL\Validator\Rules\UniqueOperationNames;
use GraphQL\Validator\Rules\LoneAnonymousOperation;
use GraphQL\Validator\Rules\KnownFragmentNames;
use GraphQL\Validator\Rules\NoFragmentCycles;
use GraphQL\Validator\Rules\NoUnusedFragments;
use GraphQL\Validator\Rules\UniqueFragmentNames;
use GraphQL\Validator\Rules\UniqueVariableNames;
use GraphQL\Validator\Rules\NoUndefinedVariables;
use GraphQL\Validator\Rules\NoUnusedVariables;
use GraphQL\Validator\Rules\UniqueArgumentNames;
use GraphQL\Validator\Rules\UniqueInputFieldNames;
use GraphQL\Language\Printer;
function executar($values) {
$variant = $values["variant"] ?? "payload";
$convertSelected = function () use ($variant, $values) {
if ($variant === "payload") {
$parameters = array_replace(["document" => "", "variables" => "{}", "operationName" => ""], $values);
$convert = function ($values) {
if (!is_array($values)) throw new InvalidArgumentException("Informe um array associativo com os campos da ferramenta");
$text = function ($value, $label) {
if (!is_string($value)) throw new InvalidArgumentException($label.': informe texto');
if (!function_exists('iconv')) throw new RuntimeException('Requer iconv');
$utf16 = iconv('UTF-8', 'UTF-16LE', $value);
if ($utf16 === false || strlen($utf16) / 2 > 100000) throw new InvalidArgumentException($label.': UTF-8 inválido ou limite de 100 mil caracteres');
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) {
$result = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$result = preg_replace_callback('/^( +)/m', fn($match)=>str_repeat(' ', strlen($match[1])/2), $result);
if (strlen(iconv('UTF-8','UTF-16LE',$result))/2 > 1000000) throw new InvalidArgumentException('Resultado excede 1 milhão de caracteres');
return $result;
};
$name = function ($value, $label, $optional = false) use ($text) {
$value = trim($text($value, $label));
if ($optional && $value === '') return '';
if (!preg_match('/^[_A-Za-z][_0-9A-Za-z]*$/D', $value)) throw new InvalidArgumentException($label.': nome GraphQL inválido');
return $value;
};
$executable = function ($source) use ($text) {
$document = Parser::parse($text($source, 'Documento GraphQL'), ['maxTokens'=>10000]);
$count = 0;
$walk = function ($node, $depth = 1) use (&$walk, &$count) {
if (!$node instanceof Node) return;
if (++$count > 10000 || $depth > 50) throw new InvalidArgumentException('Limite de 10 mil nós e 50 níveis de AST');
foreach (get_object_vars($node) as $key=>$value) {
if ($key === 'loc') continue;
if ($value instanceof Node) $walk($value, $depth+1);
elseif (is_array($value) || $value instanceof Traversable) foreach ($value as $child) $walk($child, $depth+1);
}
};
$walk($document);
$schema = new Schema(['query'=>new ObjectType(['name'=>'Query','fields'=>['placeholder'=>['type'=>Type::string()]]])]);
$rules = [new ExecutableDefinitions(),new UniqueOperationNames(),new LoneAnonymousOperation(),new KnownFragmentNames(),new NoFragmentCycles(),new NoUnusedFragments(),new UniqueFragmentNames(),new UniqueVariableNames(),new NoUndefinedVariables(),new NoUnusedVariables(),new UniqueArgumentNames(),new UniqueInputFieldNames()];
$errors = DocumentValidator::validate($schema, $document, $rules);
if ($errors) throw new InvalidArgumentException('Documento GraphQL inválido: '.$errors[0]->getMessage());
return $document;
};
$generate_graphql_payload = function ($values) use ($text, $executable, $name, $read, $output) {
$source = trim($text($values['document'] ?? null, 'Documento GraphQL'));
$document = $executable($source);
$operations = [];
foreach ($document->definitions as $node) if ($node->kind === NodeKind::OPERATION_DEFINITION) $operations[] = $node;
$operationName = $name($values['operationName'] ?? null, 'Nome da operação', true);
if (!$operations) throw new InvalidArgumentException('Informe query ou mutation');
foreach ($operations as $operation) if ($operation->operation === 'subscription') throw new InvalidArgumentException('Subscriptions não suportadas');
if ($operationName === '' && count($operations) !== 1) throw new InvalidArgumentException('Selecione o nome da operação');
$selected = $operationName === '' ? $operations[0] : null;
if ($operationName !== '') foreach ($operations as $operation) if ($operation->name && $operation->name->value === $operationName) $selected = $operation;
if (!$selected) throw new InvalidArgumentException('Operação não encontrada');
$sourceVariables = trim($text($values['variables'] ?? null,'Variáveis'));
$variables = $read($sourceVariables === '' ? '{}' : $sourceVariables,'Variáveis',true);
$definitions = $selected->variableDefinitions;
$known = [];
foreach ($definitions as $definition) $known[$definition->variable->name->value] = true;
foreach (get_object_vars($variables) as $key=>$value) if (!isset($known[$key])) throw new InvalidArgumentException('Variável não declarada na operação selecionada');
foreach ($definitions as $definition) {
$key = $definition->variable->name->value;
if ($definition->type->kind === NodeKind::NON_NULL_TYPE && $definition->defaultValue && $definition->defaultValue->kind === NodeKind::NULL) throw new InvalidArgumentException('Variável não nula não pode ter default null');
if ($definition->type->kind === NodeKind::NON_NULL_TYPE && ((!property_exists($variables,$key) && $definition->defaultValue === null) || (property_exists($variables,$key) && $variables->{$key} === null))) throw new InvalidArgumentException('Informe valor não nulo para $'.$key);
}
$data = ['query'=>$source,'variables'=>$variables];
if ($operationName !== '') $data['operationName'] = $operationName;
return $output($data);
};
return $generate_graphql_payload($values);
};
return $convert($parameters);
}
if ($variant === "query") {
$parameters = array_replace(["field" => "", "selection" => "", "variableTypes" => "{}", "arguments" => "{}", "operationName" => ""], $values);
$convert = function ($values) {
if (!is_array($values)) throw new InvalidArgumentException("Informe um array associativo com os campos da ferramenta");
$text = function ($value, $label) {
if (!is_string($value)) throw new InvalidArgumentException($label.': informe texto');
if (!function_exists('iconv')) throw new RuntimeException('Requer iconv');
$utf16 = iconv('UTF-8', 'UTF-16LE', $value);
if ($utf16 === false || strlen($utf16) / 2 > 100000) throw new InvalidArgumentException($label.': UTF-8 inválido ou limite de 100 mil caracteres');
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;
};
$name = function ($value, $label, $optional = false) use ($text) {
$value = trim($text($value, $label));
if ($optional && $value === '') return '';
if (!preg_match('/^[_A-Za-z][_0-9A-Za-z]*$/D', $value)) throw new InvalidArgumentException($label.': nome GraphQL inválido');
return $value;
};
$executable = function ($source) use ($text) {
$document = Parser::parse($text($source, 'Documento GraphQL'), ['maxTokens'=>10000]);
$count = 0;
$walk = function ($node, $depth = 1) use (&$walk, &$count) {
if (!$node instanceof Node) return;
if (++$count > 10000 || $depth > 50) throw new InvalidArgumentException('Limite de 10 mil nós e 50 níveis de AST');
foreach (get_object_vars($node) as $key=>$value) {
if ($key === 'loc') continue;
if ($value instanceof Node) $walk($value, $depth+1);
elseif (is_array($value) || $value instanceof Traversable) foreach ($value as $child) $walk($child, $depth+1);
}
};
$walk($document);
$schema = new Schema(['query'=>new ObjectType(['name'=>'Query','fields'=>['placeholder'=>['type'=>Type::string()]]])]);
$rules = [new ExecutableDefinitions(),new UniqueOperationNames(),new LoneAnonymousOperation(),new KnownFragmentNames(),new NoFragmentCycles(),new NoUnusedFragments(),new UniqueFragmentNames(),new UniqueVariableNames(),new NoUndefinedVariables(),new NoUnusedVariables(),new UniqueArgumentNames(),new UniqueInputFieldNames()];
$errors = DocumentValidator::validate($schema, $document, $rules);
if ($errors) throw new InvalidArgumentException('Documento GraphQL inválido: '.$errors[0]->getMessage());
return $document;
};
$generate_graphql_query = function ($values) use ($name, $read, $text, $executable) {
$field = $name($values['field'] ?? null,'Campo raiz');
$operationName = $name($values['operationName'] ?? null,'Nome da operação',true);
$sourceTypes = trim($text($values['variableTypes'] ?? null,'Tipos'));
$sourceBindings = trim($text($values['arguments'] ?? null,'Argumentos'));
$types = $read($sourceTypes === '' ? '{}' : $sourceTypes,'Tipos',true);
$bindings = $read($sourceBindings === '' ? '{}' : $sourceBindings,'Argumentos',true);
$definitions = [];
foreach (get_object_vars($types) as $key=>$value) {
$name($key,'Nome de variável');
if (!is_string($value)) throw new InvalidArgumentException('Tipo deve ser string');
$definitions[] = '$'.$key.': '.Printer::doPrint(Parser::parseType($text($value,'Tipo'),['maxTokens'=>100]));
}
$arguments = [];
foreach (get_object_vars($bindings) as $key=>$value) {
$name($key,'Nome de argumento');
if (!is_string($value)) throw new InvalidArgumentException('Argumento deve indicar variável sem $');
$arguments[] = $key.': $'.$name($value,'Variável do argumento');
}
$selection = trim($text($values['selection'] ?? null,'Campos de retorno'));
if ($selection !== '') {
$parsed = Parser::parse("{\n".$selection."\n}", ['maxTokens'=>10000]);
if (count($parsed->definitions) !== 1 || $parsed->definitions[0]->kind !== NodeKind::OPERATION_DEFINITION) throw new InvalidArgumentException('Informe somente campos de retorno');
$selection = ' '.Printer::doPrint($parsed->definitions[0]->selectionSet);
}
$header = 'query'.($operationName !== '' ? ' '.$operationName : '').($definitions ? '('.implode(', ',$definitions).')' : '');
$body = $field.($arguments ? '('.implode(', ',$arguments).')' : '').$selection;
$result = rtrim(Printer::doPrint($executable($header.' { '.$body.' }')), "\n");
if (strlen(iconv('UTF-8','UTF-16LE',$result))/2 > 1000000) throw new InvalidArgumentException('Query excede limite de saída');
return $result;
};
return $generate_graphql_query($values);
};
return $convert($parameters);
}
throw new InvalidArgumentException("Selecione uma modalidade válida de API.");
};
return $convertSelected();
}