JavaScript Python PHP
function executar(values) {
function lgText(value) { if (typeof value !== 'string' || value.length > 100000 || !value.isWellFormed())
throw new Error('Use texto Unicode válido de até 100 mil caracteres por campo.'); return value; }
function generateLogicUuid(v) {
const version = lgChoice(v, 'version', ['4', '7']), count = lgInt(v, 'count', 1, 500), format = lgChoice(v, 'format', ['Texto', 'JSON']);
const values = Array.from({ length: count }, () => generateUuid(version));
return format === 'JSON' ? lgJson(values) : { text: values.join('\n'), file: 'uuids.txt' };
}
function generateUuid(version, now = Date.now()) {
if (!Number.isSafeInteger(now) || now < 0 || now > 281474976710655)
throw new Error('Timestamp inválido.');
const bytes = crypto.getRandomValues(new Uint8Array(16));
if (version === '4')
bytes[6] = (bytes[6] & 15) | 64;
else if (version === '7') {
let timestamp = BigInt(now);
for (let index = 5; index >= 0; index--) {
bytes[index] = Number(timestamp & BigInt(255));
timestamp >>= BigInt(8);
}
bytes[6] = (bytes[6] & 15) | 112;
}
else if (version === '1') {
if (!uuidNodeInitialized) {
crypto.getRandomValues(uuidNode);
uuidNode[0] |= 1; // Multicast: nó aleatório, sem MAC do dispositivo.
v1Sequence = secureInt(16384);
uuidNodeInitialized = true;
}
let timestamp = BigInt(now) * BigInt(10000) + BigInt('122192928000000000');
if (timestamp <= lastV1Timestamp) {
if (timestamp < lastV1Timestamp - BigInt(10000))
v1Sequence = (v1Sequence + 1) & 16383;
timestamp = lastV1Timestamp + BigInt(1);
}
lastV1Timestamp = timestamp;
const low = Number(timestamp & BigInt('0xffffffff'));
bytes[0] = low >>> 24;
bytes[1] = low >>> 16;
bytes[2] = low >>> 8;
bytes[3] = low;
const mid = Number((timestamp >> BigInt(32)) & BigInt('0xffff'));
bytes[4] = mid >>> 8;
bytes[5] = mid;
const high = Number((timestamp >> BigInt(48)) & BigInt('0xfff'));
bytes[6] = (high >>> 8) | 16;
bytes[7] = high;
bytes[8] = v1Sequence >>> 8;
bytes[9] = v1Sequence;
bytes.set(uuidNode, 10);
}
else
throw new Error('Escolha UUID v1, v4 ou v7.');
bytes[8] = (bytes[8] & 63) | 128;
return uuidString(bytes);
}
function lgInt(v, key, min, max) { const raw = v[key], n = Number(raw); if (!/^-?\d+$/.test(raw ?? '') || !Number.isSafeInteger(n) || n < min || n > max)
throw new Error(`${key}: informe um inteiro de ${min} a ${max}.`); return n; }
function lgChoice(v, key, choices) { if (!choices.includes(v[key]))
throw new Error(`Opção inválida: ${key}.`); return v[key]; }
function lgJson(value, compact = false) { const text = JSON.stringify(value, null, compact ? undefined : 2); if (text.length > 1000000)
throw new Error('Resultado excede 1 milhão de caracteres. Reduza os limites.'); return { text, file: 'resultado.json' }; }
function secureInt(maximum) {
if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 0x100000000)
throw new Error('Intervalo aleatório inválido.');
const buffer = new Uint32Array(1);
const limit = Math.floor(0x100000000 / maximum) * maximum;
do {
crypto.getRandomValues(buffer);
} while (buffer[0] >= limit);
return buffer[0] % maximum;
}
const uuidNode = new Uint8Array(6);
let uuidNodeInitialized = false;
let lastV1Timestamp = BigInt(0);
let v1Sequence = 0;
function uuidString(bytes) {
const hex = [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
for (const value of Object.values(values)) lgText(value);
return generateLogicUuid(values);
}
import json
import re
import secrets
import time
def executar(values):
def integer(key, low, high):
raw = values.get(key, '')
if not re.fullmatch(r'-?[0-9]+', raw) or not low <= int(raw) <= high:
raise ValueError(f'{key}: informe um inteiro de {low} a {high}.')
return int(raw)
def choice(key, options):
if values.get(key) not in options:
raise ValueError('Opção inválida: ' + key)
return values[key]
def output(value, compact=False):
text = json.dumps(value, ensure_ascii=False, indent=None if compact else 2, separators=(',', ':') if compact else (',', ': '), allow_nan=False)
if len(text.encode('utf-16-le')) // 2 > 1000000:
raise ValueError('Resultado excede 1 milhão de caracteres. Reduza os limites.')
return {'text': text, 'file': 'resultado.json'}
for value in values.values():
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > 100000:
raise ValueError('Use texto Unicode válido de até 100 mil caracteres por campo.')
value.encode('utf-8')
version = choice('version', ['4', '7'])
count = integer('count', 1, 500)
form = choice('format', ['Texto', 'JSON'])
result = []
for _ in range(count):
data = bytearray(secrets.token_bytes(16))
if version == '7':
data[:6] = (time.time_ns() // 1000000).to_bytes(6, 'big')
data[6] = (data[6] & 15) | (int(version) << 4)
data[8] = (data[8] & 63) | 128
hexed = data.hex()
result.append(f'{hexed[:8]}-{hexed[8:12]}-{hexed[12:16]}-{hexed[16:20]}-{hexed[20:]}')
return output(result) if form == 'JSON' else {'text': '\n'.join(result), 'file': 'uuids.txt'}
<?php
function executar(array $values): array {
// PHP 8.1+ de 64 bits, JSON, PCRE e iconv.
$integer = static function (string $key, int $low, int $high) use ($values): int {
$raw = $values[$key] ?? '';
if (!preg_match('/^-?[0-9]+$/D', $raw) || strlen(ltrim($raw, '-0')) > 10 || (int)$raw < $low || (int)$raw > $high) throw new InvalidArgumentException("$key: informe um inteiro de $low a $high.");
return (int)$raw;
};
$choice = static function (string $key, array $options) use ($values): string {
if (!in_array($values[$key] ?? null, $options, true)) throw new InvalidArgumentException('Opção inválida: ' . $key);
return $values[$key];
};
$output = static function ($value, bool $compact = false): array {
$flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR;
$text = json_encode($value, $flags | ($compact ? 0 : JSON_PRETTY_PRINT));
if (!$compact) $text = preg_replace_callback('/^ +/m', static fn($m) => str_repeat(' ', intdiv(strlen($m[0]), 2)), $text);
if (strlen(iconv('UTF-8', 'UTF-16LE', $text)) / 2 > 1000000) throw new InvalidArgumentException('Resultado excede 1 milhão de caracteres. Reduza os limites.');
return ['text' => $text, 'file' => 'resultado.json'];
};
foreach ($values as $value) {
if (!is_string($value) || preg_match('//u', $value) !== 1 || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > 100000) throw new InvalidArgumentException('Use texto Unicode válido de até 100 mil caracteres por campo.');
}
$version = $choice('version', ['4', '7']);
$count = $integer('count', 1, 500);
$format = $choice('format', ['Texto', 'JSON']);
$result = [];
for ($i = 0; $i < $count; $i++) {
$bytes = random_bytes(16);
if ($version === '7') {
$timestamp = (int)floor(microtime(true) * 1000);
for ($j = 5; $j >= 0; $j--) { $bytes[$j] = chr($timestamp & 255); $timestamp >>= 8; }
}
$bytes[6] = chr((ord($bytes[6]) & 15) | ((int)$version << 4));
$bytes[8] = chr((ord($bytes[8]) & 63) | 128);
$hex = bin2hex($bytes);
$result[] = substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-' . substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-' . substr($hex, 20);
}
return $format === 'JSON' ? $output($result) : ['text' => implode("\n", $result), 'file' => 'uuids.txt'];
}