wetaca-cli 0.2.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +8 -1
- package/README.md +25 -2
- package/bin/wetaca.js +31 -13
- package/docs/GUIA.md +19 -1
- package/docs/agent-guide.md +25 -5
- package/docs/cli-spec.md +51 -4
- package/package.json +4 -1
- package/skill/SKILL.md +13 -1
- package/src/commands.js +92 -15
- package/src/guide.js +25 -5
- package/src/lib.js +95 -16
- package/src/report.js +547 -0
package/src/report.js
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
// wetaca-cli — `report`: turn a failure into a ready-to-send GitHub issue.
|
|
2
|
+
// Design rules for this module:
|
|
3
|
+
// - never send a secret (token, cookie, refresh-token) — redact before anything is stored;
|
|
4
|
+
// - never send personal data (email, phone, address, profile name) — redact + scrub argv;
|
|
5
|
+
// - never need a Wetaca session: `report` works offline, from the last stored error;
|
|
6
|
+
// - never publish without consent: `create` confirms and requires a GitHub credential.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import child_process from 'node:child_process';
|
|
12
|
+
import { createRequire } from 'node:module';
|
|
13
|
+
import { CliError, EXIT, VERSION, configDir, loadCreds, usageError } from './lib.js';
|
|
14
|
+
|
|
15
|
+
const require = createRequire(import.meta.url);
|
|
16
|
+
const PKG = require('../package.json');
|
|
17
|
+
const REPO_DEFAULT = (() => {
|
|
18
|
+
const m = String(PKG.repository?.url || '').match(/github\.com[:/]([^/]+)\/([^/.]+)/);
|
|
19
|
+
return m ? `${m[1]}/${m[2]}` : 'gorgueugr/wetaca-cli';
|
|
20
|
+
})();
|
|
21
|
+
|
|
22
|
+
const MARKER = 'wetaca-report-fingerprint';
|
|
23
|
+
const REDACTED = '«redacted»';
|
|
24
|
+
const MAX_BODY = 14000;
|
|
25
|
+
|
|
26
|
+
// ---------- redaction ----------
|
|
27
|
+
|
|
28
|
+
// Long strings that look like credentials in any shape we have seen in the wild:
|
|
29
|
+
// session JWTs, authorization headers, GitHub/npm tokens, cookie pairs, and the
|
|
30
|
+
// values of the flags that carry secrets or personal data. Several entries are
|
|
31
|
+
// functions because a replacer *function* does not expand `$1` in its return value.
|
|
32
|
+
const REDACTIONS = [
|
|
33
|
+
[/eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, () => REDACTED],
|
|
34
|
+
[/authorization:\s*(?:bearer|token)\s+\S+/gi, () => `authorization: ${REDACTED}`],
|
|
35
|
+
[/\b(bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi, (m, p1) => `${p1} ${REDACTED}`],
|
|
36
|
+
[/\b(gh[pousr]_[A-Za-z0-9]{20,}|npm_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, () => REDACTED],
|
|
37
|
+
[/\b((?:refresh-token|auth-token|customer-token|token-voucher-pending)=)[^;\s"']+/gi, (m, p1) => `${p1}${REDACTED}`],
|
|
38
|
+
[/(--(?:token|refresh-token|cookies|password|code)\s+)(?:"[^"]*"|'[^']*'|\S+)/gi, (m, p1) => `${p1}${REDACTED}`],
|
|
39
|
+
[/(--(?:street|number|floor|zipcode|city|notes|firstname|lastname|phone|email)=)[^\s]+/gi, (m, p1) => `${p1}${REDACTED}`],
|
|
40
|
+
[/[\w.+-]+@[\w-]+\.[\w.-]{2,}/g, () => 'user@example.com'],
|
|
41
|
+
// phone numbers with or without separators (+34 612 345 678)
|
|
42
|
+
[/(?:\+34[\s.-]?)?\b[6789]\d{2}[\s.-]?\d{3}[\s.-]?\d{3}\b/g, () => '«phone»'],
|
|
43
|
+
// Spanish street lines: "Calle Mayor 3", "Av. de la Constitución 12"
|
|
44
|
+
[/\b(?:Calle|C\/|Avenida|Av\.|Plaza|Paseo|Camino|Rúa|Carrer|Ctra\.)\s+[^,.;\n«»]{2,40}/gi, () => '«street»'],
|
|
45
|
+
// postal code followed by a city name ("18006 Granada")
|
|
46
|
+
[/\b\d{5}\s+[A-ZÁÉÍÓÚÑ][a-záéíóúñ]{2,}/g, () => '«zip city»'],
|
|
47
|
+
[/\b[A-Za-z0-9_-]{40,}\b/g, () => REDACTED],
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
function scrubPaths(s) {
|
|
51
|
+
const home = os.homedir();
|
|
52
|
+
if (home && home.length > 3) s = s.split(home).join('~');
|
|
53
|
+
return s.replace(/\b[A-Za-z]:\\Users\\[^\\\s"']+/gi, 'C:\\Users\\~');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Redacts one string; returns { value, count }.
|
|
57
|
+
function redactString(input) {
|
|
58
|
+
let s = String(input);
|
|
59
|
+
let count = 0;
|
|
60
|
+
for (const [re, to] of REDACTIONS) {
|
|
61
|
+
s = s.replace(re, (...args) => {
|
|
62
|
+
count++;
|
|
63
|
+
return typeof to === 'function' ? to(...args) : to;
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return { value: scrubPaths(s), count };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Deep redaction with a size cap. Returns { value, count }.
|
|
70
|
+
export function redact(input) {
|
|
71
|
+
let count = 0;
|
|
72
|
+
const walk = (v, depth) => {
|
|
73
|
+
if (v == null) return v;
|
|
74
|
+
if (typeof v === 'string') {
|
|
75
|
+
const r = redactString(v.length > 4000 ? v.slice(0, 4000) + '…' : v);
|
|
76
|
+
count += r.count;
|
|
77
|
+
return r.value;
|
|
78
|
+
}
|
|
79
|
+
if (typeof v === 'number' || typeof v === 'boolean') return v;
|
|
80
|
+
if (depth > 5) return '«deep»';
|
|
81
|
+
if (Array.isArray(v)) return v.slice(0, 40).map((x) => walk(x, depth + 1));
|
|
82
|
+
if (typeof v === 'object') {
|
|
83
|
+
const out = {};
|
|
84
|
+
for (const [k, x] of Object.entries(v).slice(0, 60)) out[k] = walk(x, depth + 1);
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
return String(v);
|
|
88
|
+
};
|
|
89
|
+
const value = walk(input, 0);
|
|
90
|
+
return { value, count };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ---------- argv scrubbing ----------
|
|
94
|
+
|
|
95
|
+
const SECRET_FLAGS = new Set(['token', 'refresh-token', 'cookies', 'password', 'code',
|
|
96
|
+
'street', 'number', 'floor', 'zipcode', 'city', 'notes', 'firstname', 'lastname', 'phone', 'email']);
|
|
97
|
+
// Positional args that are not ids but names / codes.
|
|
98
|
+
const NAME_POSITIONALS = {
|
|
99
|
+
profiles: ['pause', 'resume'],
|
|
100
|
+
vouchers: ['apply'],
|
|
101
|
+
giftcards: ['redeem'],
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// Rebuild the failing command with secrets and personal values removed, so the
|
|
105
|
+
// report can be pasted in a public issue.
|
|
106
|
+
export function scrubArgv(argv = []) {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (let i = 0; i < argv.length; i++) {
|
|
109
|
+
const a = String(argv[i]);
|
|
110
|
+
if (a.startsWith('--')) {
|
|
111
|
+
const eq = a.indexOf('=');
|
|
112
|
+
const key = (eq === -1 ? a.slice(2) : a.slice(2, eq)).toLowerCase();
|
|
113
|
+
if (SECRET_FLAGS.has(key)) {
|
|
114
|
+
if (eq !== -1) { out.push(`${a.slice(0, eq + 1)}${REDACTED}`); continue; }
|
|
115
|
+
out.push(a);
|
|
116
|
+
if (i + 1 < argv.length && !String(argv[i + 1]).startsWith('--')) { out.push(REDACTED); i++; }
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
out.push(a);
|
|
121
|
+
}
|
|
122
|
+
const [noun, verb] = out;
|
|
123
|
+
if (NAME_POSITIONALS[noun]?.includes(verb)) {
|
|
124
|
+
for (let i = 2; i < out.length; i++) {
|
|
125
|
+
if (String(out[i]).startsWith('-')) continue;
|
|
126
|
+
if (!/^-?\d+$/.test(String(out[i]))) out[i] = REDACTED;
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return out.map((x) => redactString(x).value);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---------- fingerprint ----------
|
|
134
|
+
|
|
135
|
+
const norm = (s) => String(s ?? '')
|
|
136
|
+
.toLowerCase()
|
|
137
|
+
.replace(/[0-9a-f]{8}-[0-9a-f-]{16,}/g, '#')
|
|
138
|
+
.replace(/\d+/g, '#')
|
|
139
|
+
.replace(/\s+/g, ' ')
|
|
140
|
+
.trim()
|
|
141
|
+
.slice(0, 160);
|
|
142
|
+
|
|
143
|
+
// Stable id for "the same failure": command + reason + message shape, version-independent
|
|
144
|
+
// so a fix released as 0.3.1 still dedupes against the 0.3.0 ticket.
|
|
145
|
+
export function fingerprintOf({ command, reason, message } = {}) {
|
|
146
|
+
const seed = [norm(command), norm(reason), norm(message)].join('|');
|
|
147
|
+
return 'wf-' + crypto.createHash('sha256').update(seed).digest('hex').slice(0, 10);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ---------- environment ----------
|
|
151
|
+
|
|
152
|
+
function hostOf(url) {
|
|
153
|
+
try { return new URL(url).host; } catch { return null; }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function npmVersion() {
|
|
157
|
+
try {
|
|
158
|
+
return child_process.execFileSync('npm', ['--version'], {
|
|
159
|
+
encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'],
|
|
160
|
+
shell: process.platform === 'win32', windowsHide: true,
|
|
161
|
+
}).trim() || null;
|
|
162
|
+
} catch { return null; }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function installMode() {
|
|
166
|
+
const entry = process.argv[1] || '';
|
|
167
|
+
return /[\\/]node_modules[\\/]/.test(entry) ? 'npm-global' : 'source-checkout';
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function collectEnvironment(ctx = {}) {
|
|
171
|
+
const profile = ctx.profile || 'default';
|
|
172
|
+
const creds = (() => { try { return loadCreds().profiles?.[profile] || {}; } catch { return {}; } })();
|
|
173
|
+
const env = {
|
|
174
|
+
cli_version: VERSION,
|
|
175
|
+
install: installMode(),
|
|
176
|
+
node: process.versions.node,
|
|
177
|
+
npm: npmVersion(),
|
|
178
|
+
os: `${process.platform} ${os.release()} (${process.arch})`,
|
|
179
|
+
shell: path.basename(process.env.SHELL || process.env.ComSpec || '') || null,
|
|
180
|
+
locale: process.env.LC_ALL || process.env.LANG || null,
|
|
181
|
+
terminal: !!process.stdin.isTTY,
|
|
182
|
+
profile,
|
|
183
|
+
// booleans only: never the values
|
|
184
|
+
session_token_present: !!creds.token,
|
|
185
|
+
refresh_token_present: !!creds.refreshToken,
|
|
186
|
+
config_dir: configDir(),
|
|
187
|
+
api_url_override: process.env.WETACA_API_URL ? hostOf(process.env.WETACA_API_URL) : null,
|
|
188
|
+
};
|
|
189
|
+
return redact(env).value;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function doctorTable(checks = []) {
|
|
193
|
+
if (!Array.isArray(checks) || !checks.length) return null;
|
|
194
|
+
return checks.map((c) => `${c.ok ? 'ok ' : 'FAIL'} ${c.check}: ${c.detail ?? ''}`).join('\n');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function projectFrames(err) {
|
|
198
|
+
const out = [];
|
|
199
|
+
for (const line of String(err?.stack || '').split('\n')) {
|
|
200
|
+
const m = line.match(/[\\/](src|bin)[\\/]([\w.-]+\.js):(\d+)(?::\d+)?/);
|
|
201
|
+
if (!m) continue;
|
|
202
|
+
out.push(`${m[2]}:${m[3]}`);
|
|
203
|
+
if (out.length >= 8) break;
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ---------- last error cache ----------
|
|
209
|
+
|
|
210
|
+
export function lastErrorPath() { return path.join(configDir(), 'last-error.json'); }
|
|
211
|
+
|
|
212
|
+
function categoryOf(code) {
|
|
213
|
+
return Object.entries(EXIT).find(([, v]) => v === code)?.[0]?.toLowerCase() || 'unexpected';
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function commandOf(argv = []) {
|
|
217
|
+
const pos = argv.filter((a) => !String(a).startsWith('-'));
|
|
218
|
+
return pos.slice(0, 2).join(' ').trim();
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Called from the CLI entry point on every failure. Must never throw and never
|
|
222
|
+
// slow a command down: a single small atomic write.
|
|
223
|
+
export function recordLastError(err, argv = process.argv.slice(2), { disabled = false } = {}) {
|
|
224
|
+
try {
|
|
225
|
+
if (disabled || process.env.WETACA_REPORT_CACHE === '0') return;
|
|
226
|
+
const command = commandOf(argv);
|
|
227
|
+
if (!command || command.startsWith('report')) return;
|
|
228
|
+
const code = err?.exitCode ?? EXIT.UNEXPECTED;
|
|
229
|
+
const reason = err?.extra?.reason || 'unexpected';
|
|
230
|
+
// Usage mistakes and declined confirmations are not bugs: they never become
|
|
231
|
+
// an issue, so they must not overwrite the last real failure.
|
|
232
|
+
if (code === EXIT.USAGE || reason === 'usage' || reason === 'confirmation_required' || reason === 'declined') return;
|
|
233
|
+
const rec = {
|
|
234
|
+
at: new Date().toISOString(),
|
|
235
|
+
command,
|
|
236
|
+
argv: scrubArgv(argv),
|
|
237
|
+
cli_version: VERSION,
|
|
238
|
+
node: process.versions.node,
|
|
239
|
+
platform: `${process.platform} ${process.arch}`,
|
|
240
|
+
error: redact({
|
|
241
|
+
code,
|
|
242
|
+
category: categoryOf(code),
|
|
243
|
+
reason: err?.extra?.reason || 'unexpected',
|
|
244
|
+
retryable: !!err?.extra?.retryable,
|
|
245
|
+
message: err?.message || String(err),
|
|
246
|
+
suggested_commands: err?.extra?.suggested_commands || [],
|
|
247
|
+
details: err?.extra?.details,
|
|
248
|
+
stack_frames: projectFrames(err),
|
|
249
|
+
}).value,
|
|
250
|
+
};
|
|
251
|
+
fs.mkdirSync(configDir(), { recursive: true });
|
|
252
|
+
const tmp = lastErrorPath() + '.tmp';
|
|
253
|
+
fs.writeFileSync(tmp, JSON.stringify(rec, null, 2) + '\n', { mode: 0o600 });
|
|
254
|
+
fs.renameSync(tmp, lastErrorPath());
|
|
255
|
+
} catch { /* the report cache must never break the CLI */ }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function readLastError() {
|
|
259
|
+
try { return JSON.parse(fs.readFileSync(lastErrorPath(), 'utf8')); } catch { return null; }
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---------- issue body ----------
|
|
263
|
+
|
|
264
|
+
function mdTable(rows) {
|
|
265
|
+
const body = rows.filter(([, v]) => v != null && v !== '').map(([k, v]) => `| ${k} | ${String(v).replace(/\|/g, '\\|')} |`);
|
|
266
|
+
return ['| field | value |', '|---|---|', ...body].join('\n');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function buildIssue({ title, failure, notes, expected, env, doctor }) {
|
|
270
|
+
const e = failure?.error || {};
|
|
271
|
+
const command = failure?.command || 'unknown';
|
|
272
|
+
const reason = e.reason || 'unexpected';
|
|
273
|
+
const fp = fingerprintOf({ command, reason, message: e.message });
|
|
274
|
+
const finalTitle = (title || `[report] wetaca ${command} — ${reason} (exit ${e.code ?? 1})`).slice(0, 180);
|
|
275
|
+
const repro = ['wetaca', ...(failure?.argv || [])].join(' ').trim();
|
|
276
|
+
|
|
277
|
+
const sections = [];
|
|
278
|
+
sections.push(`<!-- ${MARKER}: ${fp} -->`);
|
|
279
|
+
sections.push('## What happened');
|
|
280
|
+
sections.push([
|
|
281
|
+
`\`wetaca ${command}\` failed with exit code \`${e.code ?? 1}\` (\`${reason}\`)${e.category ? ` — category \`${e.category}\`` : ''}.`,
|
|
282
|
+
notes ? '\n' + notes : '',
|
|
283
|
+
].join('\n').trim());
|
|
284
|
+
|
|
285
|
+
if (expected) {
|
|
286
|
+
sections.push('## Expected');
|
|
287
|
+
sections.push(expected);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
sections.push('## Reproduce');
|
|
291
|
+
sections.push(['```', `$ ${repro}`, '```'].join('\n'));
|
|
292
|
+
|
|
293
|
+
sections.push('## Environment');
|
|
294
|
+
sections.push(mdTable(Object.entries(env || {})));
|
|
295
|
+
|
|
296
|
+
sections.push('## Error');
|
|
297
|
+
sections.push('```json');
|
|
298
|
+
sections.push(JSON.stringify({
|
|
299
|
+
code: e.code, category: e.category, reason: e.reason, retryable: e.retryable,
|
|
300
|
+
message: e.message, suggested_commands: e.suggested_commands,
|
|
301
|
+
...(e.details ? { details: e.details } : {}),
|
|
302
|
+
}, null, 2));
|
|
303
|
+
sections.push('```');
|
|
304
|
+
|
|
305
|
+
if (e.stack_frames?.length) {
|
|
306
|
+
sections.push('### Project frames');
|
|
307
|
+
sections.push(['```', ...e.stack_frames, '```'].join('\n'));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const dt = doctorTable(doctor?.checks);
|
|
311
|
+
if (dt) {
|
|
312
|
+
sections.push('## `wetaca doctor`');
|
|
313
|
+
sections.push(['```', dt, '```'].join('\n'));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const draft = sections.join('\n\n');
|
|
317
|
+
const redactedCount = (draft.match(/«redacted»|«phone»|«street»|«zip|user@example\.com|C:\\Users\\~/g) || []).length;
|
|
318
|
+
sections.push('---');
|
|
319
|
+
sections.push(`Reported by \`wetaca report\` from wetaca-cli \`${VERSION}\`${failure?.cli_version && failure.cli_version !== VERSION ? ` (failed on \`${failure.cli_version}\`)` : ''} · fingerprint \`${fp}\` · ${redactedCount} value(s) redacted.`);
|
|
320
|
+
sections.push('Tokens, cookies, authorization headers, e-mail addresses, phone numbers and delivery addresses are removed automatically before the report is written; the command line is scrubbed too (`--street`, `--city`, `--zipcode`, `--token`, voucher codes …).');
|
|
321
|
+
|
|
322
|
+
const body = sections.join('\n\n');
|
|
323
|
+
return { title: finalTitle, body: body.length > MAX_BODY ? body.slice(0, MAX_BODY) + '\n\n… (truncated)' : body, fingerprint: fp, redactions: redactedCount };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ---------- GitHub ----------
|
|
327
|
+
|
|
328
|
+
function repoFromFlags(flags) {
|
|
329
|
+
const repo = String(flags.repo || process.env.WETACA_REPORT_REPO || REPO_DEFAULT).trim();
|
|
330
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw usageError(`--repo must look like owner/name (got '${repo}').`);
|
|
331
|
+
return repo;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function githubToken() {
|
|
335
|
+
for (const k of ['GITHUB_TOKEN', 'GH_TOKEN', 'WETACA_REPORT_TOKEN']) {
|
|
336
|
+
if (process.env[k]?.trim()) return process.env[k].trim();
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
const out = child_process.execFileSync('gh', ['auth', 'token'], {
|
|
340
|
+
encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
|
|
341
|
+
}).trim();
|
|
342
|
+
if (out) return out;
|
|
343
|
+
} catch { /* gh missing or not logged in */ }
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async function ghApi(method, url, token, body) {
|
|
348
|
+
// GITHUB_API_URL is what GitHub Actions sets on GHES; WETACA_GITHUB_API lets tests
|
|
349
|
+
// (and enterprise installs) point at another API without touching the code.
|
|
350
|
+
const base = process.env.WETACA_GITHUB_API || process.env.GITHUB_API_URL || 'https://api.github.com';
|
|
351
|
+
const target = url.replace(/^https:\/\/api\.github\.com/, base.replace(/\/+$/, ''));
|
|
352
|
+
let res;
|
|
353
|
+
try {
|
|
354
|
+
res = await fetch(target, {
|
|
355
|
+
method,
|
|
356
|
+
headers: {
|
|
357
|
+
accept: 'application/vnd.github+json',
|
|
358
|
+
authorization: 'Bearer ' + token,
|
|
359
|
+
'x-github-api-version': '2022-11-28',
|
|
360
|
+
'user-agent': `wetaca-cli/${VERSION}`,
|
|
361
|
+
...(body ? { 'content-type': 'application/json' } : {}),
|
|
362
|
+
},
|
|
363
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
364
|
+
});
|
|
365
|
+
} catch (e) {
|
|
366
|
+
throw new CliError(EXIT.NETWORK, `Could not reach api.github.com: ${e.cause?.code || e.message}`,
|
|
367
|
+
{ reason: 'network', retryable: true });
|
|
368
|
+
}
|
|
369
|
+
const text = await res.text().catch(() => '');
|
|
370
|
+
let json = null;
|
|
371
|
+
try { json = text ? JSON.parse(text) : null; } catch { /* not JSON */ }
|
|
372
|
+
if (res.ok) return json;
|
|
373
|
+
if (res.status === 401 || res.status === 403) {
|
|
374
|
+
throw new CliError(EXIT.AUTH, `GitHub rejected the credentials (HTTP ${res.status})${json?.message ? ': ' + json.message : ''}. ` +
|
|
375
|
+
'Log in with `gh auth login` (scope repo) or export GITHUB_TOKEN.',
|
|
376
|
+
{ reason: 'github_auth', suggested_commands: ['gh auth login', 'GITHUB_TOKEN=… wetaca report create --yes'] });
|
|
377
|
+
}
|
|
378
|
+
if (res.status === 404) {
|
|
379
|
+
throw new CliError(EXIT.NOT_FOUND, `GitHub repo not found or the token cannot see it (HTTP 404).`,
|
|
380
|
+
{ reason: 'github_not_found', details: json });
|
|
381
|
+
}
|
|
382
|
+
throw new CliError(EXIT.API, `GitHub refused the request (HTTP ${res.status})${json?.message ? ': ' + json.message : ''}`,
|
|
383
|
+
{ reason: 'github_http_' + res.status, retryable: res.status >= 500, details: json });
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async function existingIssue(repo, fp, token) {
|
|
387
|
+
const q = `repo:${repo} is:issue in:body "${MARKER}: ${fp}"`;
|
|
388
|
+
const url = `https://api.github.com/search/issues?q=${encodeURIComponent(q)}&per_page=5`;
|
|
389
|
+
try {
|
|
390
|
+
const j = await ghApi('GET', url, token);
|
|
391
|
+
const hit = (j?.items || []).find((i) => String(i.body || '').includes(`${MARKER}: ${fp}`)) || (j?.items || [])[0];
|
|
392
|
+
if (hit) return { number: hit.number, url: hit.html_url, state: hit.state, title: hit.title };
|
|
393
|
+
} catch { /* search is best effort: never block filing the issue */ }
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function labelSet(repo, token, wanted = ['bug']) {
|
|
398
|
+
try {
|
|
399
|
+
const j = await ghApi('GET', `https://api.github.com/repos/${repo}/labels?per_page=100`, token);
|
|
400
|
+
const have = new Set((j || []).map((l) => l.name));
|
|
401
|
+
const ok = wanted.filter((l) => have.has(l));
|
|
402
|
+
return ok.length ? ok : [];
|
|
403
|
+
} catch { return []; }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function issueUrl(repo, { title, body, labels }) {
|
|
407
|
+
const params = new URLSearchParams({ title, body });
|
|
408
|
+
if (labels?.length) params.set('labels', labels.join(','));
|
|
409
|
+
return `https://github.com/${repo}/issues/new?${params.toString()}`;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function openInBrowser(url) {
|
|
413
|
+
try {
|
|
414
|
+
const { execSync } = child_process;
|
|
415
|
+
if (process.platform === 'win32') execSync(`rundll32 url.dll,FileProtocolHandler ${url}`, { stdio: 'ignore', windowsHide: true });
|
|
416
|
+
else if (process.platform === 'darwin') execSync(`open ${JSON.stringify(url)}`, { stdio: 'ignore' });
|
|
417
|
+
else execSync(`xdg-open ${JSON.stringify(url)}`, { stdio: 'ignore' });
|
|
418
|
+
return true;
|
|
419
|
+
} catch { return false; }
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function reportFile(fp) {
|
|
423
|
+
const dir = path.join(configDir(), 'reports');
|
|
424
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
425
|
+
return path.join(dir, `report-${fp}.md`);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ---------- command ----------
|
|
429
|
+
|
|
430
|
+
function failureFromFlags(flags) {
|
|
431
|
+
if (flags['error-file']) {
|
|
432
|
+
let raw;
|
|
433
|
+
try { raw = fs.readFileSync(String(flags['error-file']), 'utf8'); } catch (e) {
|
|
434
|
+
throw usageError('Could not read --error-file: ' + e.message);
|
|
435
|
+
}
|
|
436
|
+
let parsed;
|
|
437
|
+
try { parsed = JSON.parse(raw); } catch { throw usageError('--error-file must contain the JSON error wrapper (--error-format json).'); }
|
|
438
|
+
const err = parsed?.error || parsed;
|
|
439
|
+
return {
|
|
440
|
+
command: flags.command ? String(flags.command) : 'unknown',
|
|
441
|
+
argv: Array.isArray(parsed?.argv) ? parsed.argv : (flags.command ? String(flags.command).split(/\s+/) : []),
|
|
442
|
+
cli_version: VERSION,
|
|
443
|
+
error: {
|
|
444
|
+
code: err?.code ?? EXIT.UNEXPECTED, category: err?.category, reason: err?.reason,
|
|
445
|
+
retryable: err?.retryable, message: err?.message, suggested_commands: err?.suggested_commands,
|
|
446
|
+
details: err?.details, stack_frames: [],
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
return readLastError();
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export async function reportCmd(verb, args, flags, ctx, { doctor, confirm } = {}) {
|
|
454
|
+
if (verb === 'last') {
|
|
455
|
+
const rec = readLastError();
|
|
456
|
+
if (!rec) return { ok: true, hasError: false, note: 'No stored failure yet. The cache fills on the next failing command.' };
|
|
457
|
+
return { ok: true, hasError: true, path: lastErrorPath(), ...rec };
|
|
458
|
+
}
|
|
459
|
+
if (![undefined, 'show', 'create'].includes(verb)) {
|
|
460
|
+
throw usageError(`Report verbs: show | last | create (got '${verb}').`, { suggested_commands: ['wetaca report show'] });
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const failure = failureFromFlags(flags);
|
|
464
|
+
if (!failure && !flags.title && !flags.notes) {
|
|
465
|
+
throw usageError('Nothing to report: no stored failure. Run the failing command first, or pass --error-file FILE / --title T --notes "…".');
|
|
466
|
+
}
|
|
467
|
+
const repo = repoFromFlags(flags);
|
|
468
|
+
const env = collectEnvironment(ctx);
|
|
469
|
+
const doctorData = flags.doctor && typeof doctor === 'function' ? await doctor([], flags, ctx) : null;
|
|
470
|
+
|
|
471
|
+
const issue = buildIssue({
|
|
472
|
+
title: flags.title ? String(flags.title) : undefined,
|
|
473
|
+
failure,
|
|
474
|
+
notes: flags.notes ? String(flags.notes) : undefined,
|
|
475
|
+
expected: flags.expected ? String(flags.expected) : undefined,
|
|
476
|
+
env,
|
|
477
|
+
doctor: doctorData,
|
|
478
|
+
});
|
|
479
|
+
const file = reportFile(issue.fingerprint);
|
|
480
|
+
fs.writeFileSync(file, `# ${issue.title}\n\n${issue.body}\n`, { mode: 0o600 });
|
|
481
|
+
|
|
482
|
+
const base = {
|
|
483
|
+
ok: true,
|
|
484
|
+
fingerprint: issue.fingerprint,
|
|
485
|
+
title: issue.title,
|
|
486
|
+
body: issue.body,
|
|
487
|
+
redactions: issue.redactions,
|
|
488
|
+
report_path: file,
|
|
489
|
+
repo,
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
if (verb !== 'create') {
|
|
493
|
+
const urlBody = issue.body.length > 6000
|
|
494
|
+
? issue.body.slice(0, 6000) + `\n\n… (body truncated in this URL — full report at ${file})`
|
|
495
|
+
: issue.body;
|
|
496
|
+
const url = issueUrl(repo, { title: issue.title, body: urlBody, labels: ['bug'] });
|
|
497
|
+
if (flags.open) openInBrowser(url);
|
|
498
|
+
return {
|
|
499
|
+
...base,
|
|
500
|
+
mode: 'manual',
|
|
501
|
+
issue_url: url,
|
|
502
|
+
opened: !!flags.open,
|
|
503
|
+
next: [
|
|
504
|
+
'wetaca report create --yes (needs gh auth login or GITHUB_TOKEN)',
|
|
505
|
+
'wetaca report show --open (pre-filled form in the browser, no credentials)',
|
|
506
|
+
],
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const payload = { title: issue.title, body: issue.body, labels: ['bug'] };
|
|
511
|
+
if (ctx.dryRun) return { ...base, dryRun: true, wouldSend: { repo, ...payload } };
|
|
512
|
+
|
|
513
|
+
const token = await githubToken();
|
|
514
|
+
if (!token) {
|
|
515
|
+
throw new CliError(EXIT.AUTH,
|
|
516
|
+
'No GitHub credential found: set GITHUB_TOKEN (or GH_TOKEN), or run `gh auth login` once (scope repo). ' +
|
|
517
|
+
'Without a credential, use `wetaca report show --open` to file it by hand.',
|
|
518
|
+
{ reason: 'github_auth_required', suggested_commands: ['gh auth login', 'wetaca report show --open'] });
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const dup = flags.force ? null : await existingIssue(repo, issue.fingerprint, token);
|
|
522
|
+
if (dup) {
|
|
523
|
+
if (flags.open) openInBrowser(dup.url);
|
|
524
|
+
return { ...base, mode: 'existing', issue: dup, note: `An issue with fingerprint ${issue.fingerprint} is already open; pass --force to file another.` };
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Confirmation shows exactly what would become public.
|
|
528
|
+
const preview = issue.body.length > 2000 ? issue.body.slice(0, 2000) + '\n…' : issue.body;
|
|
529
|
+
await confirmOrThrow(confirm, flags, `Open this issue on github.com/${repo}?\n\n${issue.title}\n\n${preview}\n\n(full report: ${file})`);
|
|
530
|
+
|
|
531
|
+
const labels = await labelSet(repo, token, payload.labels);
|
|
532
|
+
const created = await ghApi('POST', `https://api.github.com/repos/${repo}/issues`, token,
|
|
533
|
+
{ title: payload.title, body: payload.body, ...(labels.length ? { labels } : {}) });
|
|
534
|
+
const out = { ...base, mode: 'created', issue: { number: created.number, url: created.html_url, state: created.state, labels: (created.labels || []).map((l) => l.name) } };
|
|
535
|
+
if (flags.open) { openInBrowser(created.html_url); out.opened = true; }
|
|
536
|
+
return out;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// `confirm` lives in commands.js; the dispatcher injects it so this module stays
|
|
540
|
+
// usable on its own (no import cycle, no TTY assumptions in tests).
|
|
541
|
+
async function confirmOrThrow(confirm, flags, summary) {
|
|
542
|
+
if (typeof confirm !== 'function') {
|
|
543
|
+
if (flags.yes) return;
|
|
544
|
+
throw usageError('Real-effect operation; confirmation required. Repeat with --yes.');
|
|
545
|
+
}
|
|
546
|
+
return confirm(flags, summary);
|
|
547
|
+
}
|