JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
function generateInfraDocker(v) {
const stack = infraChoice(v.stack, ['Node.js', 'Python ASGI']), name = infraName(v.name, 'Serviço'), port = infraInteger(v.port, 'Porta da aplicação', 1024, 65535), hostPort = infraInteger(v.hostPort, 'Porta no host', 1, 65535);
const build = infraChoice(v.build, ['Sim', 'Não']) === 'Sim', volume = infraChoice(v.volume, ['Sim', 'Não']) === 'Sim', dependency = infraChoice(v.dependency, ['Nenhum', 'Redis', 'PostgreSQL']), health = infraChoice(v.health, ['Sim', 'Não']) === 'Sim';
if (['redis', 'postgres'].includes(name) && dependency !== 'Nenhum')
throw new Error('O nome do serviço não pode colidir com redis/postgres.');
const environment = infraEnvironment(v.environment);
if (Object.keys(environment).some(key => ['PORT', 'HOSTNAME'].includes(key)))
throw new Error('PORT e HOSTNAME são reservados pelo gerador.');
const path = health ? infraHealthPath(v.healthPath) : '/';
let dockerfile = '', command = [];
if (stack === 'Node.js') {
command = ['node', '-e', `fetch(${JSON.stringify(`http://127.0.0.1:${port}${path}`)}, {redirect:'error',signal:AbortSignal.timeout(3000)}).then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))`];
dockerfile = '# Revise scripts e lockfile antes de construir.\nFROM node:22-alpine\nRUN mkdir -p /app/data && chown -R node:node /app\nWORKDIR /app\nUSER node\nCOPY --chown=node:node package.json package-lock.json ./\nRUN npm ci\nCOPY --chown=node:node . .\n' + (build ? 'RUN npm run build\n' : '') + `ENV NODE_ENV=production\nENV PORT=${port}\nENV HOSTNAME=0.0.0.0\nEXPOSE ${port}\n` + (health ? 'HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ' + JSON.stringify(command) + '\n' : '') + 'CMD ["npm","start"]\n';
}
else {
if (!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*$/.test(v.module))
throw new Error('Módulo ASGI inválido; use pacote.modulo:app.');
command = ['python', '-c', `import http.client,sys; c=http.client.HTTPConnection('127.0.0.1',${port},timeout=3); c.request('GET',${JSON.stringify(path)}); r=c.getresponse(); sys.exit(0 if 200<=r.status<300 else 1)`];
dockerfile = 'FROM python:3.12-slim\nRUN useradd --system --uid 10001 --create-home app && mkdir -p /app/data && chown -R app:app /app\nWORKDIR /app\nCOPY requirements.txt ./\nRUN pip install --no-cache-dir -r requirements.txt\nCOPY --chown=app:app . .\nUSER app\nENV PYTHONUNBUFFERED=1\n' + `ENV PORT=${port}\nEXPOSE ${port}\n` + (health ? 'HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ' + JSON.stringify(command) + '\n' : '') + 'CMD ' + JSON.stringify(['python', '-m', 'uvicorn', v.module, '--host', '0.0.0.0', '--port', String(port)]) + '\n';
}
const escaped = Object.fromEntries(Object.entries(environment).map(([key, value]) => [key, value.replace(/\$/g, '$$$$')]));
const bind = infraChoice(v.bind, ['127.0.0.1', '0.0.0.0']);
const app = { build: '.', ports: [`${bind}:${hostPort}:${port}`], environment: { ...escaped, PORT: String(port), ...(stack === 'Node.js' ? { HOSTNAME: '0.0.0.0' } : {}) }, restart: 'unless-stopped' };
if (health)
app.healthcheck = { test: ['CMD', ...command], interval: '30s', timeout: '5s', start_period: '30s', retries: 3 };
const services = { [name]: app }, volumes = {};
if (volume) {
app.volumes = ['app_data:/app/data'];
volumes.app_data = {};
}
if (dependency !== 'Nenhum') {
const service = dependency === 'Redis' ? 'redis' : 'postgres';
app.depends_on = { [service]: { condition: 'service_healthy' } };
if (dependency === 'Redis') {
services.redis = { image: 'redis:7-alpine', volumes: ['redis_data:/data'], healthcheck: { test: ['CMD', 'redis-cli', 'ping'], interval: '10s', timeout: '5s', retries: 5 } };
volumes.redis_data = {};
}
else {
services.postgres = { image: 'postgres:16-alpine', environment: { POSTGRES_DB: 'app', POSTGRES_USER: 'app', POSTGRES_PASSWORD: '${POSTGRES_PASSWORD:?Defina POSTGRES_PASSWORD no ambiente do Compose}' }, volumes: ['postgres_data:/var/lib/postgresql/data'], healthcheck: { test: ['CMD', 'pg_isready', '-U', 'app', '-d', 'app'], interval: '10s', timeout: '5s', retries: 5 } };
volumes.postgres_data = {};
}
}
const compose = infraYaml({ services, ...(Object.keys(volumes).length ? { volumes } : {}) });
const ignore = 'node_modules/\n.next/\n.venv/\n__pycache__/\n.git/\n.env\n.env.*\n!.env.example\n*.log\n';
return infraBundle([{ name: 'Dockerfile', content: dockerfile }, { name: 'compose.yaml', content: compose }, { name: '.dockerignore', content: ignore }], ['Arquivos para revisão: nenhum build/contêiner foi executado. A aplicação precisa implementar o healthcheck e escutar na porta configurada.', 'Redis/PostgreSQL são serviços internos de exemplo. Configure autenticação, persistência e acessos conforme seu ambiente; a aplicação ainda precisa configurar sua conexão.', 'O Node mantém dependências de build nesta imagem para atender scripts genéricos. Ajuste uma imagem multi-stage conforme a saída real do projeto.']);
}
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 infraInteger(value, label, min, max) {
if (!/^\d{1,10}$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
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;
}
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);
}
function infraYaml(value) { return stringify(value, { indent: 2, lineWidth: 0, defaultStringType: 'QUOTE_DOUBLE' }); }
function infraBundle(files, notes = []) {
return { text: files.map(f => `===== ${f.name} =====\n${f.content}`).join('\n\n'), files, notes };
}
function infraName(value, label, max = 63) {
if (typeof value !== 'string' || value.length > max || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value))
throw new Error(`${label}: use um nome DNS minúsculo de 1 a ${max} caracteres, com números ou hífens internos.`);
return value;
}
function infraHealthPath(value) {
if (value.length > 200 || !/^\/[A-Za-z0-9/_.-]*$/.test(value) || value.split('/').includes('..'))
throw new Error('Use um caminho HTTP simples iniciado por /, sem parâmetros, espaços ou segmentos ...');
return value;
}
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 generateInfraDocker(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm abaixo; a implementação completa está visível.
source = r'''
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
function generateInfraDocker(v) {
const stack = infraChoice(v.stack, ['Node.js', 'Python ASGI']), name = infraName(v.name, 'Serviço'), port = infraInteger(v.port, 'Porta da aplicação', 1024, 65535), hostPort = infraInteger(v.hostPort, 'Porta no host', 1, 65535);
const build = infraChoice(v.build, ['Sim', 'Não']) === 'Sim', volume = infraChoice(v.volume, ['Sim', 'Não']) === 'Sim', dependency = infraChoice(v.dependency, ['Nenhum', 'Redis', 'PostgreSQL']), health = infraChoice(v.health, ['Sim', 'Não']) === 'Sim';
if (['redis', 'postgres'].includes(name) && dependency !== 'Nenhum')
throw new Error('O nome do serviço não pode colidir com redis/postgres.');
const environment = infraEnvironment(v.environment);
if (Object.keys(environment).some(key => ['PORT', 'HOSTNAME'].includes(key)))
throw new Error('PORT e HOSTNAME são reservados pelo gerador.');
const path = health ? infraHealthPath(v.healthPath) : '/';
let dockerfile = '', command = [];
if (stack === 'Node.js') {
command = ['node', '-e', `fetch(${JSON.stringify(`http://127.0.0.1:${port}${path}`)}, {redirect:'error',signal:AbortSignal.timeout(3000)}).then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))`];
dockerfile = '# Revise scripts e lockfile antes de construir.\nFROM node:22-alpine\nRUN mkdir -p /app/data && chown -R node:node /app\nWORKDIR /app\nUSER node\nCOPY --chown=node:node package.json package-lock.json ./\nRUN npm ci\nCOPY --chown=node:node . .\n' + (build ? 'RUN npm run build\n' : '') + `ENV NODE_ENV=production\nENV PORT=${port}\nENV HOSTNAME=0.0.0.0\nEXPOSE ${port}\n` + (health ? 'HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ' + JSON.stringify(command) + '\n' : '') + 'CMD ["npm","start"]\n';
}
else {
if (!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*$/.test(v.module))
throw new Error('Módulo ASGI inválido; use pacote.modulo:app.');
command = ['python', '-c', `import http.client,sys; c=http.client.HTTPConnection('127.0.0.1',${port},timeout=3); c.request('GET',${JSON.stringify(path)}); r=c.getresponse(); sys.exit(0 if 200<=r.status<300 else 1)`];
dockerfile = 'FROM python:3.12-slim\nRUN useradd --system --uid 10001 --create-home app && mkdir -p /app/data && chown -R app:app /app\nWORKDIR /app\nCOPY requirements.txt ./\nRUN pip install --no-cache-dir -r requirements.txt\nCOPY --chown=app:app . .\nUSER app\nENV PYTHONUNBUFFERED=1\n' + `ENV PORT=${port}\nEXPOSE ${port}\n` + (health ? 'HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ' + JSON.stringify(command) + '\n' : '') + 'CMD ' + JSON.stringify(['python', '-m', 'uvicorn', v.module, '--host', '0.0.0.0', '--port', String(port)]) + '\n';
}
const escaped = Object.fromEntries(Object.entries(environment).map(([key, value]) => [key, value.replace(/\$/g, '$$$$')]));
const bind = infraChoice(v.bind, ['127.0.0.1', '0.0.0.0']);
const app = { build: '.', ports: [`${bind}:${hostPort}:${port}`], environment: { ...escaped, PORT: String(port), ...(stack === 'Node.js' ? { HOSTNAME: '0.0.0.0' } : {}) }, restart: 'unless-stopped' };
if (health)
app.healthcheck = { test: ['CMD', ...command], interval: '30s', timeout: '5s', start_period: '30s', retries: 3 };
const services = { [name]: app }, volumes = {};
if (volume) {
app.volumes = ['app_data:/app/data'];
volumes.app_data = {};
}
if (dependency !== 'Nenhum') {
const service = dependency === 'Redis' ? 'redis' : 'postgres';
app.depends_on = { [service]: { condition: 'service_healthy' } };
if (dependency === 'Redis') {
services.redis = { image: 'redis:7-alpine', volumes: ['redis_data:/data'], healthcheck: { test: ['CMD', 'redis-cli', 'ping'], interval: '10s', timeout: '5s', retries: 5 } };
volumes.redis_data = {};
}
else {
services.postgres = { image: 'postgres:16-alpine', environment: { POSTGRES_DB: 'app', POSTGRES_USER: 'app', POSTGRES_PASSWORD: '${POSTGRES_PASSWORD:?Defina POSTGRES_PASSWORD no ambiente do Compose}' }, volumes: ['postgres_data:/var/lib/postgresql/data'], healthcheck: { test: ['CMD', 'pg_isready', '-U', 'app', '-d', 'app'], interval: '10s', timeout: '5s', retries: 5 } };
volumes.postgres_data = {};
}
}
const compose = infraYaml({ services, ...(Object.keys(volumes).length ? { volumes } : {}) });
const ignore = 'node_modules/\n.next/\n.venv/\n__pycache__/\n.git/\n.env\n.env.*\n!.env.example\n*.log\n';
return infraBundle([{ name: 'Dockerfile', content: dockerfile }, { name: 'compose.yaml', content: compose }, { name: '.dockerignore', content: ignore }], ['Arquivos para revisão: nenhum build/contêiner foi executado. A aplicação precisa implementar o healthcheck e escutar na porta configurada.', 'Redis/PostgreSQL são serviços internos de exemplo. Configure autenticação, persistência e acessos conforme seu ambiente; a aplicação ainda precisa configurar sua conexão.', 'O Node mantém dependências de build nesta imagem para atender scripts genéricos. Ajuste uma imagem multi-stage conforme a saída real do projeto.']);
}
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 infraInteger(value, label, min, max) {
if (!/^\d{1,10}$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
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;
}
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);
}
function infraYaml(value) { return stringify(value, { indent: 2, lineWidth: 0, defaultStringType: 'QUOTE_DOUBLE' }); }
function infraBundle(files, notes = []) {
return { text: files.map(f => `===== ${f.name} =====\n${f.content}`).join('\n\n'), files, notes };
}
function infraName(value, label, max = 63) {
if (typeof value !== 'string' || value.length > max || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value))
throw new Error(`${label}: use um nome DNS minúsculo de 1 a ${max} caracteres, com números ou hífens internos.`);
return value;
}
function infraHealthPath(value) {
if (value.length > 200 || !/^\/[A-Za-z0-9/_.-]*$/.test(value) || value.split('/').includes('..'))
throw new Error('Use um caminho HTTP simples iniciado por /, sem parâmetros, espaços ou segmentos ...');
return value;
}
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 generateInfraDocker(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:await executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
'''
process = subprocess.run(["node", "--input-type=module", "-e", source], input=json.dumps(values, ensure_ascii=True), capture_output=True, text=True, timeout=15, check=True)
response = json.loads(process.stdout)
if not response["ok"]:
raise ValueError(response["error"])
return response["result"]
<?php
function executar(array $values): array {
// Requer Node.js 22+ e os pacotes npm abaixo; a implementação completa está visível.
$source = <<<'JAVASCRIPT'
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
function generateInfraDocker(v) {
const stack = infraChoice(v.stack, ['Node.js', 'Python ASGI']), name = infraName(v.name, 'Serviço'), port = infraInteger(v.port, 'Porta da aplicação', 1024, 65535), hostPort = infraInteger(v.hostPort, 'Porta no host', 1, 65535);
const build = infraChoice(v.build, ['Sim', 'Não']) === 'Sim', volume = infraChoice(v.volume, ['Sim', 'Não']) === 'Sim', dependency = infraChoice(v.dependency, ['Nenhum', 'Redis', 'PostgreSQL']), health = infraChoice(v.health, ['Sim', 'Não']) === 'Sim';
if (['redis', 'postgres'].includes(name) && dependency !== 'Nenhum')
throw new Error('O nome do serviço não pode colidir com redis/postgres.');
const environment = infraEnvironment(v.environment);
if (Object.keys(environment).some(key => ['PORT', 'HOSTNAME'].includes(key)))
throw new Error('PORT e HOSTNAME são reservados pelo gerador.');
const path = health ? infraHealthPath(v.healthPath) : '/';
let dockerfile = '', command = [];
if (stack === 'Node.js') {
command = ['node', '-e', `fetch(${JSON.stringify(`http://127.0.0.1:${port}${path}`)}, {redirect:'error',signal:AbortSignal.timeout(3000)}).then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))`];
dockerfile = '# Revise scripts e lockfile antes de construir.\nFROM node:22-alpine\nRUN mkdir -p /app/data && chown -R node:node /app\nWORKDIR /app\nUSER node\nCOPY --chown=node:node package.json package-lock.json ./\nRUN npm ci\nCOPY --chown=node:node . .\n' + (build ? 'RUN npm run build\n' : '') + `ENV NODE_ENV=production\nENV PORT=${port}\nENV HOSTNAME=0.0.0.0\nEXPOSE ${port}\n` + (health ? 'HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ' + JSON.stringify(command) + '\n' : '') + 'CMD ["npm","start"]\n';
}
else {
if (!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*$/.test(v.module))
throw new Error('Módulo ASGI inválido; use pacote.modulo:app.');
command = ['python', '-c', `import http.client,sys; c=http.client.HTTPConnection('127.0.0.1',${port},timeout=3); c.request('GET',${JSON.stringify(path)}); r=c.getresponse(); sys.exit(0 if 200<=r.status<300 else 1)`];
dockerfile = 'FROM python:3.12-slim\nRUN useradd --system --uid 10001 --create-home app && mkdir -p /app/data && chown -R app:app /app\nWORKDIR /app\nCOPY requirements.txt ./\nRUN pip install --no-cache-dir -r requirements.txt\nCOPY --chown=app:app . .\nUSER app\nENV PYTHONUNBUFFERED=1\n' + `ENV PORT=${port}\nEXPOSE ${port}\n` + (health ? 'HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ' + JSON.stringify(command) + '\n' : '') + 'CMD ' + JSON.stringify(['python', '-m', 'uvicorn', v.module, '--host', '0.0.0.0', '--port', String(port)]) + '\n';
}
const escaped = Object.fromEntries(Object.entries(environment).map(([key, value]) => [key, value.replace(/\$/g, '$$$$')]));
const bind = infraChoice(v.bind, ['127.0.0.1', '0.0.0.0']);
const app = { build: '.', ports: [`${bind}:${hostPort}:${port}`], environment: { ...escaped, PORT: String(port), ...(stack === 'Node.js' ? { HOSTNAME: '0.0.0.0' } : {}) }, restart: 'unless-stopped' };
if (health)
app.healthcheck = { test: ['CMD', ...command], interval: '30s', timeout: '5s', start_period: '30s', retries: 3 };
const services = { [name]: app }, volumes = {};
if (volume) {
app.volumes = ['app_data:/app/data'];
volumes.app_data = {};
}
if (dependency !== 'Nenhum') {
const service = dependency === 'Redis' ? 'redis' : 'postgres';
app.depends_on = { [service]: { condition: 'service_healthy' } };
if (dependency === 'Redis') {
services.redis = { image: 'redis:7-alpine', volumes: ['redis_data:/data'], healthcheck: { test: ['CMD', 'redis-cli', 'ping'], interval: '10s', timeout: '5s', retries: 5 } };
volumes.redis_data = {};
}
else {
services.postgres = { image: 'postgres:16-alpine', environment: { POSTGRES_DB: 'app', POSTGRES_USER: 'app', POSTGRES_PASSWORD: '${POSTGRES_PASSWORD:?Defina POSTGRES_PASSWORD no ambiente do Compose}' }, volumes: ['postgres_data:/var/lib/postgresql/data'], healthcheck: { test: ['CMD', 'pg_isready', '-U', 'app', '-d', 'app'], interval: '10s', timeout: '5s', retries: 5 } };
volumes.postgres_data = {};
}
}
const compose = infraYaml({ services, ...(Object.keys(volumes).length ? { volumes } : {}) });
const ignore = 'node_modules/\n.next/\n.venv/\n__pycache__/\n.git/\n.env\n.env.*\n!.env.example\n*.log\n';
return infraBundle([{ name: 'Dockerfile', content: dockerfile }, { name: 'compose.yaml', content: compose }, { name: '.dockerignore', content: ignore }], ['Arquivos para revisão: nenhum build/contêiner foi executado. A aplicação precisa implementar o healthcheck e escutar na porta configurada.', 'Redis/PostgreSQL são serviços internos de exemplo. Configure autenticação, persistência e acessos conforme seu ambiente; a aplicação ainda precisa configurar sua conexão.', 'O Node mantém dependências de build nesta imagem para atender scripts genéricos. Ajuste uma imagem multi-stage conforme a saída real do projeto.']);
}
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 infraInteger(value, label, min, max) {
if (!/^\d{1,10}$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
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;
}
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);
}
function infraYaml(value) { return stringify(value, { indent: 2, lineWidth: 0, defaultStringType: 'QUOTE_DOUBLE' }); }
function infraBundle(files, notes = []) {
return { text: files.map(f => `===== ${f.name} =====\n${f.content}`).join('\n\n'), files, notes };
}
function infraName(value, label, max = 63) {
if (typeof value !== 'string' || value.length > max || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value))
throw new Error(`${label}: use um nome DNS minúsculo de 1 a ${max} caracteres, com números ou hífens internos.`);
return value;
}
function infraHealthPath(value) {
if (value.length > 200 || !/^\/[A-Za-z0-9/_.-]*$/.test(value) || value.split('/').includes('..'))
throw new Error('Use um caminho HTTP simples iniciado por /, sem parâmetros, espaços ou segmentos ...');
return value;
}
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 generateInfraDocker(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:await 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)) { $n = fwrite($pipes[0], substr($payload, $offset)); if ($n === false || $n === 0) { proc_terminate($process); foreach ($pipes as $pipe) fclose($pipe); proc_close($process); throw new RuntimeException("Falha ao enviar a entrada."); } $offset += $n; }
fclose($pipes[0]); stream_set_timeout($pipes[1], 15); $output = stream_get_contents($pipes[1]); $timeout = stream_get_meta_data($pipes[1])["timed_out"]; fclose($pipes[1]); if ($timeout) proc_terminate($process); stream_get_contents($pipes[2]); fclose($pipes[2]); $status = proc_close($process);
if ($timeout || $status !== 0) throw new RuntimeException("Falha técnica ou timeout no Node.js; confira as dependências npm.");
$response = json_decode($output, true, 512, JSON_THROW_ON_ERROR); if (!$response["ok"]) throw new InvalidArgumentException($response["error"]);
return $response["result"];
}