@ihyeon/error-to-test 0.0.0-stage → 0.1.1

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/dist/cli.js ADDED
@@ -0,0 +1,146 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { resolve } from 'node:path';
4
+ import { analyzeErrors } from "./analysis.js";
5
+ import { readBoundedFile, verifyBundle, writeBundle } from "./artifacts.js";
6
+ import { redactText } from "./redact.js";
7
+ import { linkFlowQaReport } from "./results.js";
8
+ const help = `Error to Test — local error analysis and regression TC drafts
9
+
10
+ error-to-test analyze --input errors.json --profile profile.json --out new-directory
11
+ error-to-test analyze --input error.txt --format text --page /items --out new-directory
12
+ error-to-test analyze --error "TypeError: item is undefined" --page /items --out new-directory
13
+ cat error.txt | error-to-test analyze --input - --format text --out new-directory
14
+ error-to-test verify new-directory [--input errors.json] [--profile profile.json]
15
+ error-to-test link-run new-directory --report path/to/qa-report.json
16
+
17
+ Options:
18
+ --input FILE SDK export, manual JSON, or plain error text (- for stdin)
19
+ --error TEXT Submit a single error directly; remaining lines are its stack
20
+ --format auto|json|text Auto rejects malformed JSON-looking input
21
+ --profile FILE Confirmed app scenarios and explicit assertions (optional)
22
+ --project NAME Metadata for a manual report
23
+ --environment NAME Metadata for a manual report
24
+ --release NAME Metadata for a manual report
25
+ --page PATH Page reported for a manual error
26
+ --type TYPE javascript|promise|react|console|http|network|manual
27
+ --runtime RUNTIME browser|webview-ios|webview-android|unknown (manual input)
28
+ --reproduce TEXT Reported action (--error only; repeatable)
29
+ --precondition TEXT Reported setup (--error only; repeatable)
30
+ --expected TEXT Reported intended result (--error only)
31
+ --expected-source TEXT Expected-result source (--error only)
32
+ --from ISO --to ISO Filter observed timestamps; undated reports are excluded
33
+ --top N Generate TCs for the first N ranked groups (1..100)
34
+ --out DIRECTORY New directory; existing files are never overwritten
35
+ --reviewed Acknowledge review; unresolved questions still block cases
36
+ --report FILE Normalized Flow QA report (link-run only)
37
+
38
+ No model call or browser execution occurs. Review report.md and cases/error-to-test.json first.
39
+ Use a local file or stdin for private errors; avoid secrets in shell history.
40
+ `;
41
+ async function stdinText() {
42
+ if (process.stdin.isTTY)
43
+ throw new Error('--input - requires piped input.');
44
+ const chunks = [];
45
+ let bytes = 0;
46
+ for await (const chunk of process.stdin) {
47
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
48
+ bytes += buffer.length;
49
+ if (bytes > 10 * 1024 * 1024)
50
+ throw new Error('Input must be 10 MiB or smaller.');
51
+ chunks.push(buffer);
52
+ }
53
+ return Buffer.concat(chunks).toString('utf8');
54
+ }
55
+ export async function main(args = process.argv.slice(2)) {
56
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, strict: true, options: {
57
+ help: { type: 'boolean', short: 'h' }, input: { type: 'string' }, error: { type: 'string' }, report: { type: 'string' },
58
+ format: { type: 'string' }, profile: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
59
+ release: { type: 'string' }, page: { type: 'string' }, type: { type: 'string' }, runtime: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' },
60
+ top: { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
61
+ reproduce: { type: 'string', multiple: true }, precondition: { type: 'string', multiple: true },
62
+ expected: { type: 'string' }, 'expected-source': { type: 'string' },
63
+ } });
64
+ if (values.help || positionals.length === 0) {
65
+ process.stdout.write(help);
66
+ return;
67
+ }
68
+ const command = positionals[0];
69
+ if (command === 'link-run') {
70
+ if (positionals.length !== 2 || !positionals[1] || !values.report)
71
+ throw new Error('link-run requires a bundle directory and --report.');
72
+ if (Object.keys(values).some(key => key !== 'report' && key !== 'help'))
73
+ throw new Error('Unsupported option for link-run.');
74
+ let report;
75
+ try {
76
+ report = JSON.parse(await readBoundedFile(resolve(values.report), 2 * 1024 * 1024));
77
+ }
78
+ catch {
79
+ throw new Error('The Flow QA report must be a JSON file within 2 MiB.');
80
+ }
81
+ const file = await linkFlowQaReport(resolve(positionals[1]), report);
82
+ process.stdout.write(`Run linked: ${file}\nSource issues were not automatically closed.\n`);
83
+ return;
84
+ }
85
+ if (command === 'verify') {
86
+ if (positionals.length !== 2 || !positionals[1])
87
+ throw new Error('verify requires one bundle directory.');
88
+ if (Object.keys(values).some(key => !['input', 'profile', 'help'].includes(key)))
89
+ throw new Error('Unsupported option for verify.');
90
+ const result = await verifyBundle(resolve(positionals[1]), {
91
+ ...(values.input ? { input: await readBoundedFile(resolve(values.input)) } : {}),
92
+ ...(values.profile ? { profile: await readBoundedFile(resolve(values.profile), 1024 * 1024) } : {}),
93
+ });
94
+ process.stdout.write(`Bundle verified. Suite: ${result.suite ? 'present' : 'none'}; review: ${result.reviewed ? 'acknowledged' : 'pending'}; original input: ${result.sourceChecked ? 'checked' : 'not supplied'}.\n`);
95
+ return;
96
+ }
97
+ if (command !== 'analyze' || positionals.length !== 1)
98
+ throw new Error('Use analyze, verify, or link-run. See --help.');
99
+ if (values.report)
100
+ throw new Error('--report applies to link-run only.');
101
+ if ((values.input === undefined) === (values.error === undefined))
102
+ throw new Error('Provide exactly one of --input or --error.');
103
+ const format = values.format ?? 'auto';
104
+ if (format !== 'auto' && format !== 'json' && format !== 'text')
105
+ throw new Error('--format must be auto, json, or text.');
106
+ const types = ['javascript', 'promise', 'react', 'console', 'http', 'network', 'manual'];
107
+ if (values.type !== undefined && !types.includes(values.type))
108
+ throw new Error('--type is not supported.');
109
+ if (values.runtime !== undefined && !['browser', 'webview-ios', 'webview-android', 'unknown'].includes(values.runtime))
110
+ throw new Error('--runtime is not supported.');
111
+ let content;
112
+ let inputFormat = format;
113
+ if (values.error !== undefined) {
114
+ if (values.format !== undefined)
115
+ throw new Error('--format applies to --input; direct --error is a manual report.');
116
+ const [message, ...stack] = values.error.trim().split(/\r?\n/);
117
+ const error = { message, ...(stack.length ? { stack: stack.join('\n') } : {}),
118
+ ...(values.project ? { project: values.project } : {}), ...(values.environment ? { environment: values.environment } : {}),
119
+ ...(values.release ? { release: values.release } : {}), ...(values.page ? { page: values.page } : {}),
120
+ ...(values.type ? { type: values.type } : {}), reproduction: values.reproduce ?? [], preconditions: values.precondition ?? [],
121
+ ...(values.runtime ? { runtime: values.runtime } : {}),
122
+ ...(values.expected ? { expected: values.expected } : {}), ...(values['expected-source'] ? { expectedSource: values['expected-source'] } : {}),
123
+ };
124
+ content = JSON.stringify({ schemaVersion: 'error-to-test/manual-1', errors: [error] });
125
+ inputFormat = 'json';
126
+ }
127
+ else {
128
+ if (values.reproduce || values.precondition || values.expected || values['expected-source'])
129
+ throw new Error('Reported context options require --error. Use manual JSON or a profile for file input.');
130
+ content = values.input === '-' ? await stdinText() : await readBoundedFile(resolve(values.input));
131
+ }
132
+ const analysis = analyzeErrors(content, {
133
+ format: inputFormat, ...(values.profile ? { profile: await readBoundedFile(resolve(values.profile), 1024 * 1024) } : {}),
134
+ project: values.project, environment: values.environment, release: values.release, page: values.page, type: values.type, runtime: values.runtime,
135
+ from: values.from, to: values.to, ...(values.top !== undefined ? { top: Number(values.top) } : {}),
136
+ });
137
+ const out = resolve(values.out ?? `.error-to-test/run-${Date.now()}-${randomUUID().slice(0, 8)}`);
138
+ const files = await writeBundle(out, analysis, { reviewed: values.reviewed });
139
+ const drafts = analysis.candidates.filter(candidate => candidate.state === 'draft').length;
140
+ process.stdout.write(`${analysis.groups.length} error groups; ${analysis.candidates.length} TC candidates (${drafts} drafts, ${analysis.candidates.length - drafts} need context).\n`);
141
+ process.stdout.write(`Review ${resolve(out, 'report.md')}\n${files.length} artifacts written. Review acknowledgment: ${values.reviewed ? 'yes' : 'pending'}.\n`);
142
+ }
143
+ export function reportCliError(error) {
144
+ process.stderr.write(`Error to Test: ${redactText(error instanceof Error ? error.message : 'The command failed.')}\n`);
145
+ process.exitCode = 1;
146
+ }
@@ -0,0 +1,4 @@
1
+ import type { Analysis, FlowQaExport } from '../types.ts';
2
+ export declare function exportFlowQa(analysis: Analysis, options?: {
3
+ reviewed?: boolean;
4
+ }): FlowQaExport;
@@ -0,0 +1,122 @@
1
+ import { hash } from "../validation.js";
2
+ import { redactText } from "../redact.js";
3
+ const reviewQuestion = 'Review this draft case and confirm its requirement, steps, and assertion before execution.';
4
+ const blockedStep = { type: 'act', instruction: 'Collect the missing reproduction steps; do not execute this blocked case.' };
5
+ function safe(value) {
6
+ return redactText(value);
7
+ }
8
+ function quoted(value) {
9
+ return JSON.stringify(safe(value));
10
+ }
11
+ function stepNeedsRedaction(step) {
12
+ return JSON.stringify(step) !== JSON.stringify(step, (_key, value) => typeof value === 'string' ? safe(value) : value);
13
+ }
14
+ function exportCase(candidate, reviewed) {
15
+ const unsafeStep = candidate.steps.some(stepNeedsRedaction);
16
+ const questions = [...candidate.questions.map(safe)];
17
+ if (unsafeStep)
18
+ questions.push('Execution steps contain sensitive data; provide reviewed, safe steps before running.');
19
+ if (candidate.state !== 'draft' && !questions.length)
20
+ questions.push('Resolve missing context before running this case.');
21
+ if (!reviewed)
22
+ questions.push(reviewQuestion);
23
+ const uniqueQuestions = [...new Set(questions)];
24
+ const runnable = candidate.state === 'draft' && !unsafeStep && uniqueQuestions.length === 0;
25
+ const id = candidate.id;
26
+ const requirementId = `R_${hash(`${candidate.groupId}:${candidate.ruleId ?? 'manual'}`).slice(0, 16)}`;
27
+ const requirementText = candidate.expected
28
+ ? `Expected behavior: ${safe(candidate.expected.text)} (source: ${safe(candidate.expected.source)})`
29
+ : 'Expected behavior unresolved: identify the intended outcome and its authoritative source.';
30
+ if (requirementText.length > 8192)
31
+ throw new Error(`Flow QA requirement for ${id} exceeds 8192 characters.`);
32
+ const test = {
33
+ id,
34
+ title: safe(candidate.title),
35
+ requirementIds: [requirementId],
36
+ preconditions: candidate.preconditions.map(safe),
37
+ questions: uniqueQuestions,
38
+ steps: runnable ? candidate.steps : unsafeStep || !candidate.steps.length ? [blockedStep] : candidate.steps,
39
+ };
40
+ return { requirement: { id: requirementId, text: requirementText }, test };
41
+ }
42
+ export function exportFlowQa(analysis, options = {}) {
43
+ if (analysis.candidates.length > 100)
44
+ throw new Error(`Flow QA supports at most 100 cases; received ${analysis.candidates.length}. Narrow the analysis before export.`);
45
+ const reviewed = options.reviewed === true;
46
+ const exported = analysis.candidates.map((candidate) => exportCase(candidate, reviewed));
47
+ const lines = [
48
+ '# Error to test review',
49
+ '',
50
+ `Source SHA-256: ${analysis.source.sha256}`,
51
+ `Candidate count: ${analysis.candidates.length}`,
52
+ `Review acknowledged: ${reviewed ? 'yes' : 'no'}`,
53
+ '',
54
+ ];
55
+ if (!exported.length)
56
+ lines.push('No test cases were generated from this analysis.', '');
57
+ for (const [index, item] of exported.entries()) {
58
+ const candidate = analysis.candidates[index];
59
+ lines.push(`## ${index + 1}. ${quoted(candidate.title)}`, '');
60
+ lines.push(`- Case ID: ${item.test.id}`);
61
+ lines.push(`- State: ${candidate.state}`);
62
+ lines.push(`- Group ID: ${quoted(candidate.groupId)}`);
63
+ if (candidate.ruleId)
64
+ lines.push(`- Scenario rule: ${quoted(candidate.ruleId)}`);
65
+ lines.push(`- Requirement: ${quoted(item.requirement.text)}`);
66
+ lines.push(`- Event IDs: ${candidate.eventIds.map(quoted).join(', ') || 'none'}`);
67
+ lines.push('- Observed facts:');
68
+ for (const fact of candidate.facts)
69
+ lines.push(` - ${quoted(fact)}`);
70
+ if (!candidate.facts.length)
71
+ lines.push(' - none');
72
+ lines.push('- Hypotheses:');
73
+ for (const hypothesis of candidate.hypotheses)
74
+ lines.push(` - ${quoted(hypothesis)}`);
75
+ if (!candidate.hypotheses.length)
76
+ lines.push(' - none');
77
+ lines.push('- Reported reproduction:');
78
+ for (const action of candidate.reproduction)
79
+ lines.push(` - ${quoted(action)}`);
80
+ if (!candidate.reproduction.length)
81
+ lines.push(' - missing');
82
+ lines.push('- Missing information / review questions:');
83
+ for (const question of item.test.questions)
84
+ lines.push(` - ${quoted(question)}`);
85
+ if (!item.test.questions.length)
86
+ lines.push(' - none');
87
+ lines.push('- Flow QA steps:');
88
+ for (const step of item.test.steps)
89
+ lines.push(` - ${quoted(JSON.stringify(step))}`);
90
+ lines.push('');
91
+ }
92
+ const flow = `${lines.join('\n')}\n`;
93
+ if (Buffer.byteLength(flow) > 128_000)
94
+ throw new Error('The generated flow exceeds Flow QA\'s 128 KB source limit. Narrow the selected groups or scenario details.');
95
+ const flowSha256 = hash(flow);
96
+ const result = {
97
+ flow,
98
+ provenance: {
99
+ schemaVersion: 'error-to-test/provenance-1',
100
+ inputSha256: analysis.source.sha256,
101
+ analysisSha256: hash(`${JSON.stringify(analysis, null, 2)}\n`),
102
+ ...(analysis.source.profileSha256 ? { profileSha256: analysis.source.profileSha256 } : {}),
103
+ flowSha256,
104
+ reviewed,
105
+ mappings: analysis.candidates.map((candidate) => ({ caseId: candidate.id, candidateId: candidate.id, groupId: candidate.groupId, eventIds: [...candidate.eventIds] })),
106
+ },
107
+ };
108
+ if (exported.length) {
109
+ const suite = {
110
+ schemaVersion: 'flow-qa/suite-1', platform: 'web', id: 'error_to_test', title: 'Error to test candidates',
111
+ source: { file: 'flows/error-to-test.md', sha256: flowSha256 },
112
+ requirements: exported.map((item) => item.requirement),
113
+ cases: exported.map((item) => item.test),
114
+ };
115
+ result.suite = suite;
116
+ const suiteText = `${JSON.stringify(suite, null, 2)}\n`;
117
+ if (Buffer.byteLength(suiteText) > 512 * 1024)
118
+ throw new Error('The generated suite exceeds Flow QA UI\'s 512 KiB limit. Narrow the selected groups or scenario details.');
119
+ result.provenance.suiteSha256 = hash(suiteText);
120
+ }
121
+ return result;
122
+ }
@@ -0,0 +1,2 @@
1
+ import type { ErrorObservation, IssueGroup } from './types.ts';
2
+ export declare function groupObservations(observations: ErrorObservation[]): IssueGroup[];
@@ -0,0 +1,73 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { hash } from "./validation.js";
3
+ import { pagePath } from "./redact.js";
4
+ function sourceFrame(stack) {
5
+ if (!stack)
6
+ return '';
7
+ const lines = stack.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
8
+ const frame = lines.find((line) => /\bat\s+|@|:\d+(?::\d+)?/.test(line));
9
+ return frame ?? '';
10
+ }
11
+ function signature(item) {
12
+ const network = item.network;
13
+ const site = network
14
+ ? `${network.method.toUpperCase()} ${pagePath(network.url)} ${network.status ?? ''}`
15
+ : sourceFrame(item.stack ?? item.componentStack);
16
+ return [item.name ?? '', item.message, site].join(' | ');
17
+ }
18
+ function sharedContext(observations) {
19
+ const conflicts = [];
20
+ const common = (field) => {
21
+ const first = observations[0][field];
22
+ if (observations.every((item) => isDeepStrictEqual(item[field], first)))
23
+ return first;
24
+ conflicts.push(`Conflicting ${field} across reports.`);
25
+ return undefined;
26
+ };
27
+ const expected = common('expected');
28
+ const expectedSource = common('expectedSource');
29
+ const reproduction = common('reproduction');
30
+ const preconditions = common('preconditions');
31
+ const steps = common('steps');
32
+ const questions = [...new Set(observations.flatMap((item) => item.questions))].sort();
33
+ return {
34
+ ...(expected === undefined ? {} : { expected }),
35
+ ...(expectedSource === undefined ? {} : { expectedSource }),
36
+ ...(reproduction === undefined ? {} : { reproduction }),
37
+ ...(preconditions === undefined ? {} : { preconditions }),
38
+ ...(steps === undefined ? {} : { steps }),
39
+ questions, conflicts,
40
+ };
41
+ }
42
+ export function groupObservations(observations) {
43
+ const groups = new Map();
44
+ for (const item of observations) {
45
+ const path = pagePath(item.page);
46
+ const sig = signature(item);
47
+ const key = JSON.stringify([item.project, item.environment, item.release, item.runtime, item.type, path, sig]);
48
+ const id = `group-${hash(key).slice(0, 16)}`;
49
+ let group = groups.get(key);
50
+ if (!group) {
51
+ group = {
52
+ id, fingerprintVersion: 1, project: item.project, environment: item.environment,
53
+ release: item.release, runtime: item.runtime, type: item.type, pagePath: path,
54
+ signature: sig, message: item.message, count: 0, viewCount: 0, eventIds: [], evidence: [],
55
+ };
56
+ groups.set(key, group);
57
+ }
58
+ group.count++;
59
+ group.eventIds.push(item.id);
60
+ group.evidence.push(item);
61
+ if (item.occurredAt && (!group.lastOccurredAt || item.occurredAt > group.lastOccurredAt))
62
+ group.lastOccurredAt = item.occurredAt;
63
+ }
64
+ for (const group of groups.values()) {
65
+ group.eventIds.sort();
66
+ group.viewCount = new Set(group.evidence.map((item) => item.viewId).filter((id) => !!id)).size;
67
+ group.context = sharedContext(group.evidence);
68
+ group.evidence.sort((a, b) => (b.occurredAt ?? '').localeCompare(a.occurredAt ?? '') || a.id.localeCompare(b.id));
69
+ group.evidence = group.evidence.slice(0, 5);
70
+ }
71
+ return [...groups.values()].sort((a, b) => b.viewCount - a.viewCount || b.count - a.count ||
72
+ (b.lastOccurredAt ?? '').localeCompare(a.lastOccurredAt ?? '') || a.id.localeCompare(b.id));
73
+ }
@@ -0,0 +1,8 @@
1
+ export { analyzeErrors, type AnalyzeOptions } from './analysis.ts';
2
+ export { parseInput, type ParseInputOptions } from './input.ts';
3
+ export { groupObservations } from './grouping.ts';
4
+ export { createCandidates, parseProfile } from './candidates.ts';
5
+ export { exportFlowQa } from './exports/flow-qa.ts';
6
+ export { writeBundle, verifyBundle, renderReport } from './artifacts.ts';
7
+ export { linkFlowQaReport } from './results.ts';
8
+ export type * from './types.ts';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { analyzeErrors } from "./analysis.js";
2
+ export { parseInput } from "./input.js";
3
+ export { groupObservations } from "./grouping.js";
4
+ export { createCandidates, parseProfile } from "./candidates.js";
5
+ export { exportFlowQa } from "./exports/flow-qa.js";
6
+ export { writeBundle, verifyBundle, renderReport } from "./artifacts.js";
7
+ export { linkFlowQaReport } from "./results.js";
@@ -0,0 +1,13 @@
1
+ import type { EventType, ParsedInput, Runtime } from './types.ts';
2
+ export interface ParseInputOptions {
3
+ format?: 'auto' | 'json' | 'text';
4
+ project?: string;
5
+ environment?: string;
6
+ release?: string;
7
+ page?: string;
8
+ type?: EventType;
9
+ runtime?: Runtime;
10
+ from?: string;
11
+ to?: string;
12
+ }
13
+ export declare function parseInput(content: string, options?: ParseInputOptions): ParsedInput;
package/dist/input.js ADDED
@@ -0,0 +1,270 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { record, text, optionalText, strings, timestamp, parseWebSteps, hash } from "./validation.js";
3
+ import { redactText, safeUrl } from "./redact.js";
4
+ const TYPES = new Set(['javascript', 'promise', 'react', 'console', 'http', 'network', 'manual']);
5
+ const RUNTIMES = new Set(['browser', 'webview-ios', 'webview-android', 'unknown']);
6
+ const MAX_BYTES = 10 * 1024 * 1024;
7
+ const MAX_RECORDS = 10_000;
8
+ const LOGGER_PREFIX = /^\[(?:ERROR|WARN|WARNING|INFO|DEBUG|TRACE|FATAL|vite|timestamp|\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})?)?|\d{2}:\d{2}:\d{2})\][ \t]+\S/i;
9
+ function eventType(value, label) {
10
+ if (typeof value !== 'string' || !TYPES.has(value))
11
+ throw new Error(`${label} must be a valid event type`);
12
+ return value;
13
+ }
14
+ function runtime(value, label) {
15
+ if (typeof value !== 'string' || !RUNTIMES.has(value))
16
+ throw new Error(`${label} must be a valid runtime`);
17
+ return value;
18
+ }
19
+ function number(value, label, integer = false) {
20
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || (integer && !Number.isInteger(value))) {
21
+ throw new Error(`${label} must be a nonnegative ${integer ? 'integer' : 'number'}`);
22
+ }
23
+ return value;
24
+ }
25
+ function optionalStringArray(value, label) {
26
+ return value === undefined ? [] : strings(value, label).map(redactText);
27
+ }
28
+ function safeSteps(value, label) {
29
+ const steps = value === undefined ? [] : parseWebSteps(value, label);
30
+ // The step parser establishes the shape before any user text is sanitized.
31
+ const sanitized = steps.map((step) => {
32
+ const clean = (input) => redactText(input);
33
+ switch (step.type) {
34
+ case 'open': return { ...step, path: safeUrl(step.path) };
35
+ case 'act':
36
+ case 'assertAgent': return { ...step, instruction: clean(step.instruction) };
37
+ case 'click':
38
+ case 'assertVisible': return { ...step, locator: { ...step.locator, value: clean(step.locator.value), ...('name' in step.locator && step.locator.name ? { name: clean(step.locator.name) } : {}) } };
39
+ case 'fill': return { ...step, locator: { ...step.locator, value: clean(step.locator.value), ...('name' in step.locator && step.locator.name ? { name: clean(step.locator.name) } : {}) }, value: clean(step.value) };
40
+ case 'assertText': return { ...step, locator: { ...step.locator, value: clean(step.locator.value), ...('name' in step.locator && step.locator.name ? { name: clean(step.locator.name) } : {}) }, expected: clean(step.expected) };
41
+ case 'assertUrl': return { ...step, expected: safeUrl(step.expected) };
42
+ }
43
+ });
44
+ const credentialFill = steps.some((step) => step.type === 'fill' &&
45
+ /password|passwd|secret|token|api[_-]?key|authorization|cookie|session/i.test(`${step.locator.value} ${'name' in step.locator ? step.locator.name ?? '' : ''}`));
46
+ // A changed action or assertion would no longer express the author's intent.
47
+ // Keep the report, but require the missing safe step to be supplied explicitly.
48
+ return !credentialFill && JSON.stringify(steps) === JSON.stringify(sanitized)
49
+ ? { steps, redacted: false }
50
+ : { steps: [], redacted: true };
51
+ }
52
+ function canonical(value) {
53
+ if (Array.isArray(value))
54
+ return `[${value.map(canonical).join(',')}]`;
55
+ if (value && typeof value === 'object')
56
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`).join(',')}}`;
57
+ return JSON.stringify(value);
58
+ }
59
+ function browserEvent(value, index) {
60
+ const label = `events[${index}]`;
61
+ const item = record(value, label);
62
+ if (item.schemaVersion !== 1)
63
+ throw new Error(`${label}.schemaVersion must be 1`);
64
+ const id = text(item.eventId, `${label}.eventId`);
65
+ const project = text(item.project, `${label}.project`);
66
+ const environment = text(item.environment, `${label}.environment`);
67
+ const release = text(item.release, `${label}.release`);
68
+ text(item.sdkVersion, `${label}.sdkVersion`);
69
+ const occurredAt = timestamp(item.occurredAt, `${label}.occurredAt`);
70
+ if (item.receivedAt !== undefined)
71
+ timestamp(item.receivedAt, `${label}.receivedAt`);
72
+ const viewId = text(item.viewId, `${label}.viewId`);
73
+ number(item.sequence, `${label}.sequence`, true);
74
+ number(item.elapsedMs, `${label}.elapsedMs`);
75
+ const type = eventType(item.type, `${label}.type`);
76
+ const message = text(item.message, `${label}.message`);
77
+ const name = optionalText(item.name, `${label}.name`);
78
+ const stack = optionalText(item.stack, `${label}.stack`);
79
+ const componentStack = optionalText(item.componentStack, `${label}.componentStack`);
80
+ const page = text(item.page, `${label}.page`);
81
+ const eventRuntime = runtime(item.runtime, `${label}.runtime`);
82
+ optionalText(item.browser, `${label}.browser`);
83
+ if (item.context !== undefined) {
84
+ const context = record(item.context, `${label}.context`);
85
+ for (const [key, val] of Object.entries(context)) {
86
+ if (val !== null && typeof val !== 'string' && typeof val !== 'boolean' && (typeof val !== 'number' || !Number.isFinite(val))) {
87
+ throw new Error(`${label}.context.${key} must be scalar`);
88
+ }
89
+ }
90
+ }
91
+ let network;
92
+ if (item.network !== undefined) {
93
+ const net = record(item.network, `${label}.network`);
94
+ const method = text(net.method, `${label}.network.method`);
95
+ const url = text(net.url, `${label}.network.url`);
96
+ const durationMs = number(net.durationMs, `${label}.network.durationMs`);
97
+ let status;
98
+ if (net.status !== undefined) {
99
+ status = number(net.status, `${label}.network.status`, true);
100
+ if (status < 100 || status > 599)
101
+ throw new Error(`${label}.network.status must be 100..599`);
102
+ }
103
+ network = { method: redactText(method).toUpperCase(), url: safeUrl(url), durationMs, ...(status === undefined ? {} : { status }) };
104
+ }
105
+ return {
106
+ id: redactText(id), source: 'browser-error', project: redactText(project), environment: redactText(environment),
107
+ release: redactText(release), type, message: redactText(message), runtime: eventRuntime,
108
+ ...(name === undefined ? {} : { name: redactText(name) }),
109
+ ...(stack === undefined ? {} : { stack: redactText(stack) }),
110
+ ...(componentStack === undefined ? {} : { componentStack: redactText(componentStack) }),
111
+ page: safeUrl(page), occurredAt, viewId: redactText(viewId),
112
+ ...(network === undefined ? {} : { network }),
113
+ reproduction: [], preconditions: [], questions: [], steps: [],
114
+ };
115
+ }
116
+ function manualError(value, index, defaults) {
117
+ const label = `errors[${index}]`;
118
+ const item = record(value, label);
119
+ const message = text(item.message, `${label}.message`);
120
+ const id = optionalText(item.id, `${label}.id`) ?? `manual-${hash(canonical(item)).slice(0, 24)}`;
121
+ const type = item.type === undefined ? defaults.type ?? 'manual' : eventType(item.type, `${label}.type`);
122
+ const project = optionalText(item.project, `${label}.project`) ?? defaults.project ?? 'unknown';
123
+ const environment = optionalText(item.environment, `${label}.environment`) ?? defaults.environment ?? 'unknown';
124
+ const release = optionalText(item.release, `${label}.release`) ?? defaults.release ?? 'unknown';
125
+ const page = optionalText(item.page, `${label}.page`) ?? defaults.page;
126
+ const name = optionalText(item.name, `${label}.name`);
127
+ const stack = optionalText(item.stack, `${label}.stack`);
128
+ const componentStack = optionalText(item.componentStack, `${label}.componentStack`);
129
+ const eventRuntime = item.runtime === undefined ? (defaults.runtime === undefined ? 'unknown' : runtime(defaults.runtime, 'runtime')) : runtime(item.runtime, `${label}.runtime`);
130
+ const occurredAt = item.occurredAt === undefined ? undefined : timestamp(item.occurredAt, `${label}.occurredAt`);
131
+ const reproduction = optionalStringArray(item.reproduction, `${label}.reproduction`);
132
+ const preconditions = optionalStringArray(item.preconditions, `${label}.preconditions`);
133
+ const questions = optionalStringArray(item.questions, `${label}.questions`);
134
+ const expected = optionalText(item.expected, `${label}.expected`);
135
+ const expectedSource = optionalText(item.expectedSource, `${label}.expectedSource`);
136
+ const alteredExpected = (expected !== undefined && redactText(expected) !== expected) ||
137
+ (expectedSource !== undefined && redactText(expectedSource) !== expectedSource);
138
+ const stepResult = safeSteps(item.steps, `${label}.steps`);
139
+ if (stepResult.redacted)
140
+ questions.push('Provide safe reproduction steps without credentials or personal data.');
141
+ if (alteredExpected)
142
+ questions.push('Provide safe expected behavior and its source without credentials or personal data.');
143
+ return {
144
+ id: redactText(id), source: 'manual', project: redactText(project), environment: redactText(environment),
145
+ release: redactText(release), type, message: redactText(message), runtime: eventRuntime,
146
+ ...(page === undefined ? {} : { page: safeUrl(page) }),
147
+ ...(name === undefined ? {} : { name: redactText(name) }),
148
+ ...(stack === undefined ? {} : { stack: redactText(stack) }),
149
+ ...(componentStack === undefined ? {} : { componentStack: redactText(componentStack) }),
150
+ ...(occurredAt === undefined ? {} : { occurredAt }), reproduction, preconditions, questions,
151
+ ...(!alteredExpected && expected !== undefined ? { expected } : {}),
152
+ ...(!alteredExpected && expectedSource !== undefined ? { expectedSource } : {}), steps: stepResult.steps,
153
+ };
154
+ }
155
+ export function parseInput(content, options = {}) {
156
+ if (Buffer.byteLength(content, 'utf8') > MAX_BYTES)
157
+ throw new Error('Input exceeds 10 MiB');
158
+ if (!content.trim())
159
+ throw new Error('Input is empty');
160
+ const from = options.from === undefined ? undefined : timestamp(options.from, 'from');
161
+ const to = options.to === undefined ? undefined : timestamp(options.to, 'to');
162
+ if (from && to && from > to)
163
+ throw new Error('from must not exceed to');
164
+ const format = options.format ?? 'auto';
165
+ if (!['auto', 'json', 'text'].includes(format))
166
+ throw new Error('Invalid input format');
167
+ const trimmed = content.trimStart();
168
+ const isJson = format === 'json' || (format === 'auto' && /^[\[{]/.test(trimmed) && !LOGGER_PREFIX.test(trimmed));
169
+ let observations;
170
+ let kind;
171
+ let partial = false;
172
+ let raw;
173
+ if (isJson) {
174
+ let parsed;
175
+ try {
176
+ parsed = JSON.parse(content);
177
+ }
178
+ catch {
179
+ throw new Error('Malformed JSON input');
180
+ }
181
+ if (Array.isArray(parsed)) {
182
+ kind = 'browser-error-json';
183
+ raw = parsed;
184
+ }
185
+ else {
186
+ const top = record(parsed, 'input');
187
+ if (top.schemaVersion === 1) {
188
+ kind = 'browser-error-json';
189
+ if (top.partial !== undefined && typeof top.partial !== 'boolean')
190
+ throw new Error('partial must be boolean');
191
+ partial = top.partial === true;
192
+ if (!Array.isArray(top.events))
193
+ throw new Error('events must be an array');
194
+ raw = top.events;
195
+ }
196
+ else if (top.schemaVersion === 'error-to-test/manual-1') {
197
+ kind = 'manual-json';
198
+ if (!Array.isArray(top.errors))
199
+ throw new Error('errors must be an array');
200
+ raw = top.errors;
201
+ }
202
+ else
203
+ throw new Error('Unsupported input schemaVersion');
204
+ }
205
+ if (raw.length === 0)
206
+ throw new Error('Input has no records');
207
+ if (raw.length > MAX_RECORDS)
208
+ throw new Error('Input exceeds 10000 records');
209
+ observations = raw.map((item, index) => kind === 'browser-error-json' ? browserEvent(item, index) : manualError(item, index, options));
210
+ }
211
+ else {
212
+ kind = 'manual-text';
213
+ const lines = content.trim().split(/\r?\n/);
214
+ const message = lines.shift().trim();
215
+ if (!message)
216
+ throw new Error('Error message is empty');
217
+ observations = [manualError({ message, ...(lines.length ? { stack: lines.join('\n') } : {}) }, 0, options)];
218
+ raw = [content];
219
+ }
220
+ const inputCount = raw.length;
221
+ const seen = new Map();
222
+ const unique = [];
223
+ let duplicates = 0;
224
+ for (let index = 0; index < observations.length; index++) {
225
+ const item = observations[index];
226
+ const key = `${item.project}\u0000${item.id}`;
227
+ const source = canonical(raw[index]);
228
+ const previous = seen.get(key);
229
+ if (previous !== undefined) {
230
+ if (previous !== source)
231
+ throw new Error(`Conflicting duplicate ID: ${item.id}`);
232
+ duplicates++;
233
+ }
234
+ else {
235
+ seen.set(key, source);
236
+ unique.push(item);
237
+ }
238
+ }
239
+ const warnings = [];
240
+ if (partial)
241
+ warnings.push('Source export is partial; observed counts may be incomplete.');
242
+ if (duplicates)
243
+ warnings.push(`${duplicates} duplicate record(s) removed.`);
244
+ if (from || to)
245
+ warnings.push('Date filtering applies only to reports with observed timestamps.');
246
+ let filtered = 0;
247
+ const selected = unique.filter((item) => {
248
+ const matches = (!options.project || item.project === options.project) &&
249
+ (!options.environment || item.environment === options.environment) &&
250
+ (!options.release || item.release === options.release) &&
251
+ (!options.page || item.page === safeUrl(options.page)) &&
252
+ (!options.type || item.type === options.type) &&
253
+ (!from || !!item.occurredAt && item.occurredAt >= from) &&
254
+ (!to || !!item.occurredAt && item.occurredAt <= to);
255
+ if (!matches)
256
+ filtered++;
257
+ return matches;
258
+ }).sort((a, b) => a.project.localeCompare(b.project) || a.id.localeCompare(b.id));
259
+ if (filtered)
260
+ warnings.push(`${filtered} record(s) excluded by filters.`);
261
+ if ((from || to) && unique.some((item) => !item.occurredAt))
262
+ warnings.push('Undated manual reports were excluded by date filters.');
263
+ return {
264
+ observations: selected,
265
+ coverage: { kind, frequency: kind === 'browser-error-json' ? 'captured-events' : 'submitted-reports',
266
+ partial, inputCount, duplicates, filtered, retention: 'unknown',
267
+ ...(from || to ? { period: { ...(from ? { from } : {}), ...(to ? { to } : {}) } } : {}) },
268
+ sha256: createHash('sha256').update(content).digest('hex'), warnings,
269
+ };
270
+ }
@@ -0,0 +1,3 @@
1
+ export declare function safeUrl(value: string): string;
2
+ export declare function redactText(value: string): string;
3
+ export declare function pagePath(value?: string): string;