api-cli/scripts/build.js
2026-11-28 15:28:06 +02:00

147 lines
6 KiB
JavaScript

#!/usr/bin/env node
/*
* Builds the aio command of one brand.
* node scripts/build.js --base https://api.mozout.com --brand "<name>" [--docs https://docs.<brand>] [--mcp-name <name>-ai] [--out dist/<host>/]
* Writes to --out (default dist/<API host>/):
* aio.js the command with the address and the brand built in (chmod 755)
* aio-<version>.tgz npm package (npm install -g <tgz url>), made here without npm or tar
* SHA256SUMS checksums of both files
* No dependencies; the result is always the same for the same inputs (fixed dates).
*/
'use strict';
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const crypto = require('crypto');
const ROOT = path.resolve(__dirname, '..');
const SRC = path.join(ROOT, 'bin', 'aio.js');
const START = '/* aio-build:start */';
const END = '/* aio-build:end */';
const MTIME = Date.UTC(2026, 10, 17) / 1000; // fixed dates in the tgz
function fail(msg) { process.stderr.write('build: ' + msg + '\n'); process.exit(2); }
function args(argv) {
const o = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith('--')) { fail('argumento inesperado: ' + a); }
const eq = a.indexOf('=');
const k = (eq > 0 ? a.slice(2, eq) : a.slice(2));
const v = eq > 0 ? a.slice(eq + 1) : argv[++i];
if (v === undefined) { fail('falta o valor de --' + k); }
o[k] = v;
}
return o;
}
const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
function brandConfig(o) {
if (!o.base) { fail('falta --base https://api.mozout.com'); }
if (!o.brand) { fail('falta --brand "<nome>"'); }
let u;
try { u = new URL(o.base); } catch (e) { fail('--base não é um URL: ' + o.base); }
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && /^(127\.0\.0\.1|localhost)$/.test(u.hostname))) { fail('--base tem de ser https'); }
const base = (u.origin + u.pathname).replace(/\/+$/, '').replace(/\/v1$/, '');
const brand = String(o.brand).trim();
if (!brand || brand.length > 60 || /[\r\n]/.test(brand)) { fail('--brand inválido'); }
const docs = (o.docs || (u.protocol + '//' + u.host.replace(/^api\./, 'docs.'))).replace(/\/+$/, '');
const mcpName = o['mcp-name'] || (slug(brand) + '-ai');
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(mcpName)) { fail('--mcp-name inválido'); }
return { base, brand, docs, mcpName, host: u.host };
}
function render(src, cfg) {
const a = src.indexOf(START), b = src.indexOf(END);
if (a < 0 || b < a) { fail('marcadores do bloco BUILD não encontrados em bin/aio.js'); }
const block = START + '\nconst BUILD = ' + JSON.stringify({ base: cfg.base, brand: cfg.brand, docs: cfg.docs, mcpName: cfg.mcpName }, null, 2) + ';\n';
return src.slice(0, a) + block + src.slice(b);
}
function version(src) {
const m = /const VERSION = '([0-9]+\.[0-9]+\.[0-9]+[^']*)'/.exec(src);
if (!m) { fail('VERSION não encontrada'); }
return m[1];
}
function brandText(s, cfg) {
return s.split('https://api.mozout.com').join(cfg.base)
.split('https://docs.<marca>').join(cfg.docs)
.split('<marca>-ai').join(cfg.mcpName)
.split('<Marca>').join(cfg.brand);
}
/* minimal ustar tar (regular files, names up to 100 characters) */
function tarEntry(name, data, mode) {
const h = Buffer.alloc(512, 0);
const put = (str, off, len) => { Buffer.from(str, 'utf8').copy(h, off, 0, len); };
const oct = (n, len) => n.toString(8).padStart(len - 1, '0') + '\0';
if (Buffer.byteLength(name) > 100) { fail('nome longo de mais para o tar: ' + name); }
put(name, 0, 100);
put(oct(mode, 8), 100, 8);
put(oct(0, 8), 108, 8);
put(oct(0, 8), 116, 8);
put(oct(data.length, 12), 124, 12);
put(oct(MTIME, 12), 136, 12);
h.fill(' ', 148, 156);
h[156] = '0'.charCodeAt(0);
put('ustar\0', 257, 6);
put('00', 263, 2);
let sum = 0;
for (let i = 0; i < 512; i++) { sum += h[i]; }
put(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8);
const pad = Buffer.alloc((512 - (data.length % 512)) % 512, 0);
return Buffer.concat([h, data, pad]);
}
function tgz(files) {
const parts = files.map((f) => tarEntry(f.name, f.data, f.mode));
parts.push(Buffer.alloc(1024, 0));
return zlib.gzipSync(Buffer.concat(parts), { level: 9 });
}
const sha = (b) => crypto.createHash('sha256').update(b).digest('hex');
function main() {
const o = args(process.argv.slice(2));
const cfg = brandConfig(o);
const src = fs.readFileSync(SRC, 'utf8');
const ver = version(src);
const outDir = path.resolve(o.out || path.join(ROOT, 'dist', cfg.host));
fs.mkdirSync(outDir, { recursive: true });
const js = Buffer.from(render(src, cfg), 'utf8');
const pkgSrc = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const pkg = {
name: pkgSrc.name,
version: ver,
description: cfg.brand + ' All in One AI: ' + pkgSrc.description_brand,
bin: { aio: 'bin/aio.js' },
files: ['bin/aio.js', 'README.md', 'LICENSE'],
engines: pkgSrc.engines,
license: pkgSrc.license,
homepage: cfg.docs + '/cli/'
};
const readme = Buffer.from(brandText(fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8'), cfg), 'utf8');
const license = Buffer.from(brandText(fs.readFileSync(path.join(ROOT, 'LICENSE'), 'utf8'), cfg), 'utf8');
const jsPath = path.join(outDir, 'aio.js');
fs.writeFileSync(jsPath, js);
fs.chmodSync(jsPath, 0o755);
const tgzName = 'aio-' + ver + '.tgz';
const pack = tgz([
{ name: 'package/package.json', data: Buffer.from(JSON.stringify(pkg, null, 2) + '\n'), mode: 0o644 },
{ name: 'package/bin/aio.js', data: js, mode: 0o755 },
{ name: 'package/README.md', data: readme, mode: 0o644 },
{ name: 'package/LICENSE', data: license, mode: 0o644 }
]);
fs.writeFileSync(path.join(outDir, tgzName), pack);
const sums = sha(js) + ' aio.js\n' + sha(pack) + ' ' + tgzName + '\n';
fs.writeFileSync(path.join(outDir, 'SHA256SUMS'), sums);
process.stdout.write(JSON.stringify({ out: outDir, version: ver, base: cfg.base, brand: cfg.brand, docs: cfg.docs, mcpName: cfg.mcpName, files: ['aio.js', tgzName, 'SHA256SUMS'] }) + '\n');
}
main();