maestri-remote/.context/skills/azure-boards-work-item-and-pr/scripts/comment.mjs

110 lines
5.7 KiB
JavaScript

#!/usr/bin/env node
// Posta (ou edita) um comentário num work item do Azure Boards preservando UTF-8, e confirma com GET.
// Uso:
// node comment.mjs --org <org> --project <projeto> --id <workItemId> --file <arquivo.html> [--comment-id <id>] [--dry-run]
// O arquivo contém o texto do comentário em HTML (UTF-8), gravado pela ferramenta de arquivos do cliente.
// --comment-id troca o POST por PATCH no comentário existente. --dry-run não escreve nada: valida o
// texto, obtém o token, lê os comentários atuais e mostra o que seria enviado.
// Requer Node 18+ (fetch nativo) e `az` autenticado. Sem dependências npm.
import { readFileSync } from 'node:fs';
import { azDevOpsToken, isLoginPage, loginPageMessage } from '../../../scripts/az-devops-token.mjs';
const API = 'api-version=7.1-preview.4';
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith('--')) continue;
const key = a.slice(2);
const next = argv[i + 1];
if (next === undefined || next.startsWith('--')) out[key] = true;
else { out[key] = next; i++; }
}
return out;
}
// Sem process.exit(): no Windows, sair à força com handles do fetch abertos derruba o Node (assert do libuv).
class Fail extends Error {}
class UsageFail extends Fail {}
function fail(msg) { throw new Fail(msg); }
const USAGE = 'uso: node comment.mjs --org <org> --project <projeto> --id <workItemId> --file <arquivo.html> [--comment-id <id>] [--dry-run]';
// --help/-h: uso no stdout e código 0, antes de validar qualquer parâmetro.
if (process.argv.slice(2).some((a) => a === '--help' || a === '-h')) { console.log(USAGE); process.exit(0); }
async function getToken(org) {
// Pedido no tenant da organização (ver az-devops-token.mjs); a falha já traz o `az login` certo.
try { return await azDevOpsToken(org); } catch (e) { return fail(e.message); }
}
async function call(method, url, token, body) {
const res = await fetch(url, {
method,
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json; charset=utf-8' },
body: body === undefined ? undefined : Buffer.from(JSON.stringify(body), 'utf8'),
});
// Token de outro tenant: o fetch segue o 302 para a página de login e devolve 203 com ok=true.
if (isLoginPage(res)) fail(await loginPageMessage(res, url, token));
const text = await res.text();
if (!res.ok) fail(`${method} ${url.split('?')[0]} -> HTTP ${res.status}: ${text.slice(0, 500)}`);
return text ? JSON.parse(text) : null;
}
const BOM = String.fromCharCode(0xfeff);
const REPLACEMENT = String.fromCharCode(0xfffd); // caractere que aparece no lugar de acento corrompido
// Assinatura de IA não vai para o DevOps (regra 18 do AGENTS.md da raiz).
const AI_SIGNATURE = /co-authored-by\s*:|claude-session\s*:|claude\.ai\/code\/session|generated (with|by) \[?(claude|ai\b)|\u{1F916}/iu;
async function main() {
const args = parseArgs(process.argv.slice(2));
for (const k of ['org', 'project', 'id', 'file']) if (!args[k] || args[k] === true) throw new UsageFail(`falta --${k}.`);
const org = String(args.org).replace(/\/+$/, '');
const orgUrl = org.startsWith('http') ? org : 'https://dev.azure.com/' + org;
const base = `${orgUrl}/${encodeURIComponent(args.project)}/_apis/wit/workItems/${args.id}/comments`;
let text = readFileSync(args.file, 'utf8');
if (text.startsWith(BOM)) text = text.slice(1);
text = text.trim();
if (!text) fail('arquivo de comentário vazio.');
if (text.includes('\\n')) fail('o texto tem "\\n" literal; o campo é HTML, use <br> para quebrar linha.');
if (text.includes(REPLACEMENT)) fail('o texto já contém U+FFFD (caractere corrompido); regrave o arquivo em UTF-8.');
const sig = AI_SIGNATURE.exec(text);
if (sig) fail(`o texto tem assinatura de IA ("${sig[0]}"); retire-a antes de enviar (regra 18 do AGENTS.md da raiz).`);
const token = await getToken(org);
if (args['dry-run']) {
const list = await call('GET', `${base}?${API}`, token);
const method = args['comment-id'] ? 'PATCH' : 'POST';
const target = args['comment-id'] ? `${base}/${args['comment-id']}` : base;
console.log(`[dry-run] work item ${args.id}: ${list.totalCount ?? list.count ?? 0} comentário(s) hoje.`);
console.log(`[dry-run] enviaria ${method} ${target}?${API}`);
console.log(`[dry-run] texto (${[...text].length} caracteres): ${text}`);
return;
}
const written = args['comment-id']
? await call('PATCH', `${base}/${args['comment-id']}?${API}`, token, { text })
: await call('POST', `${base}?${API}`, token, { text });
// POST/PATCH devolvem 200 mesmo com texto corrompido: relê e compara.
// O servidor pode normalizar o HTML, então a comparação que importa é a dos caracteres não ASCII.
const check = await call('GET', `${base}/${written.id}?${API}`, token);
const nonAscii = [...new Set([...text].filter((c) => c.codePointAt(0) > 127))];
const readBack = (check && check.text) || '';
const missing = nonAscii.filter((c) => !readBack.includes(c));
if (readBack.includes(REPLACEMENT) || missing.length) {
fail(`comentário ${written.id} gravado, mas a acentuação não voltou íntegra (faltam: ${missing.join(' ')}). Corrija com --comment-id ${written.id}.`);
}
const same = readBack === text ? 'idêntico ao enviado' : 'com acentuação íntegra (HTML normalizado pelo servidor)';
console.log(`OK: comentário ${written.id} ${args['comment-id'] ? 'editado' : 'criado'} no work item ${args.id}; texto relido ${same}.`);
}
// Erro de uso (parâmetro obrigatório ausente) sai com 2, junto com o uso; os demais, com 1.
main().catch((e) => {
console.error('ERRO: ' + (e instanceof Fail ? e.message : (e && e.stack) || e));
if (e instanceof UsageFail) console.error(USAGE);
process.exitCode = e instanceof UsageFail ? 2 : 1;
});