@ihyeon/error-to-test 0.2.0 → 0.2.2

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/README.ko.md CHANGED
@@ -102,6 +102,25 @@ TC 생성 대상에서 제외된 묶음도 모두 비교합니다. 한쪽에 여
102
102
 
103
103
  양쪽 번들을 검증한 뒤 읽으며 원래 산출물·TC 상태·검토 조건·연결 결과는 수정하지 않습니다. 기본 출력은 Markdown이고, `--format json`은 `error-to-test/comparison-1`을 반환합니다. `--out`은 양쪽 번들의 `results` 폴더 밖에 있는 새 파일만 허용합니다. API는 `compareBundles()`와 `renderComparison()`입니다.
104
104
 
105
+ CI에서는 `--max-new N`으로 **현재에만 있는 오류 서명의 허용 개수**를 정할 수 있습니다.
106
+
107
+ ```sh
108
+ error-to-test compare ./before ./current --max-new 0
109
+ error-to-test compare ./before ./current --max-new 2 --format json --out ./comparison.json
110
+ ```
111
+
112
+ 0~10,000의 십진 정수를 받습니다. TC 생성에서 제외된 묶음을 포함한 전체 비교 결과의 `only-current` 서명 수를 기준으로 합니다. 릴리스만 다른 동일 비교 키는 한 번 세며, 로그 건수나 건수 증가는 한도에 포함하지 않습니다.
113
+
114
+ | 종료 코드 | 의미 |
115
+ | --- | --- |
116
+ | `0` | 비교 성공, 한도 이내 또는 한도 옵션 미사용 |
117
+ | `1` | 잘못된 옵션·입력 형식 불일치·번들 변조·출력 오류 |
118
+ | `2` | 비교 성공, 현재에만 있는 서명 수가 한도 초과 |
119
+
120
+ 한도를 넘겨도 전체 비교 보고서를 출력하거나 저장하므로 CI에서 검토 자료로 남길 수 있습니다. 숫자로 된 통과·실패 요약은 stderr에 쓰고, JSON stdout은 기존 `error-to-test/comparison-1` 형식을 유지합니다. 출력 오류는 코드 1로 처리하고 기존 파일을 보존합니다. 옵션을 생략하면 기존 비교 동작을 유지하며, `--max-new`는 `compare`에서만 사용할 수 있습니다.
121
+
122
+ 프로젝트·환경·기간·수집 범위를 맞춘 분석을 기준으로 사용하세요. 부분 내보내기와 수집 범위 경고는 보고서에 남습니다. 이 값은 제공한 이전 분석에 없던 서명 수이며 실제 유입 시점이나 회귀 원인을 확정하지 않습니다. TC 실행·검토 상태는 변경하지 않습니다. API에서는 `comparison.counts['only-current']`로 같은 기준을 적용할 수 있습니다.
123
+
105
124
  `analyze --baseline`을 쓰면 **이전 분석에서 관측되지 않은 서명만 골라 TC를 생성**할 수 있습니다.
106
125
 
107
126
  ```sh
@@ -137,6 +156,23 @@ error-to-test analyze --input errors.json --min-count 3 --profile ./review-profi
137
156
 
138
157
  `init-profile`은 검증에 통과한 번들만 읽고 새 파일에 저장합니다. 수정된 번들, 선택된 TC가 없는 결과, 기존 출력 파일은 거부합니다. 원래 분석 산출물을 덮어쓰지 않습니다. API의 `createProfileTemplate(analysis)`도 편집용 `error-to-test/profile-1` 객체를 만들며, 완성된 실행 프로필을 의미하지 않습니다.
139
158
 
159
+ 이미 작성한 프로필은 `--profile`로 이어서 보완할 수 있습니다.
160
+
161
+ ```sh
162
+ error-to-test analyze --input current-errors.jsonl --format jsonl --out ./current-analysis
163
+ error-to-test init-profile ./current-analysis --profile ./existing-profile.json --out ./expanded-profile.json
164
+ # 새로 추가된 빈 요구사항·출처·준비 조건·동작·assertion 작성
165
+ error-to-test analyze --input current-errors.jsonl --format jsonl --profile ./expanded-profile.json --out ./expanded-analysis
166
+ ```
167
+
168
+ 기존 프로필은 요구사항·기대 결과 출처 등 일반 프로필 검증을 통과해야 합니다. 이름과 규칙 순서·ID·조건·단계·기대 결과·준비 확인·질문을 검증된 값 그대로 보존합니다. 알 수 없는 필드와 파일 서식은 보존하지 않습니다. 기존 질문과 준비 미확인 상태도 남아 실행을 차단합니다.
169
+
170
+ TC 생성과 동일하게 모든 조건을 함께 검사해 기존 규칙이 적용되는 선택 묶음을 찾습니다. 넓은 조건의 규칙은 원래 조건 안에서 여러 묶음에 적용될 수 있습니다. 다른 릴리스의 정확한 `match.groupId`는 그대로 두며, 새 묶음에 단계·기대 결과를 복사하지 않습니다. 기존 규칙이 없는 선택 묶음에만 순위대로 빈 검토 항목을 붙입니다. 새 항목의 ID가 충돌하면 숫자 접미사를 붙이고 기존 ID는 유지합니다. 모두 기존 규칙으로 다뤄지면 항목을 추가하지 않습니다.
171
+
172
+ 새 항목은 기대 결과·출처가 비어 있고, 준비 미확인과 검토 질문을 유지합니다. 직접 채운 뒤 원래 입력·메타데이터·필터·이전 분석 기준으로 다시 분석하세요. 기존 검토 조건도 적용합니다. 과거 규칙을 자동 삭제하지 않으므로 합산 100개 규칙·1 MiB 한도를 지켜야 합니다. 민감한 정보가 있는 기존 메타데이터·실행 단계는 파일 생성 전에 거부합니다. 기본·확장 템플릿 모두 번들의 `results` 폴더 밖에 있는 새 파일에 저장합니다.
173
+
174
+ API는 `createProfileTemplate(analysis, { profile: existingProfile })`입니다. JSON 값만으로 구성한 객체 또는 BOM 하나를 지원하는 JSON 문자열을 1 MiB까지 받으며 입력 객체를 변경하지 않습니다. 객체의 선택 필드가 `undefined`이면 해당 속성을 생략하세요. `profile`을 생략하면 기존 빈 템플릿을 만듭니다.
175
+
140
176
  ```sh
141
177
  node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
142
178
  node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --reviewed --out .error-to-test/reviewed
package/README.md CHANGED
@@ -131,6 +131,27 @@ All source groups participate, including groups excluded from TC generation by `
131
131
 
132
132
  Both bundles must pass consistency verification. The command reads their verified snapshots without editing artifacts, TC states, review gates, or linked results. Markdown is the default; `--format json` returns `error-to-test/comparison-1`. `--out` requires a new file outside either bundle's `results` directory. The API equivalents are `await compareBundles(baselineDirectory, currentDirectory)` and `renderComparison(comparison)`.
133
133
 
134
+ ### Limit newly observed signatures in CI
135
+
136
+ Set `--max-new N` to fail a CI step when the supplied current analysis has more than N `only-current` signatures:
137
+
138
+ ```sh
139
+ error-to-test compare ./before ./current --max-new 0
140
+ error-to-test compare ./before ./current --max-new 2 --format json --out ./comparison.json
141
+ ```
142
+
143
+ The limit accepts decimal integers from 0 to 10,000. It counts distinct comparison signatures across all retained groups, including groups excluded from TC generation. Release groups sharing the same comparison key count once. Record counts and count increases do not affect this limit.
144
+
145
+ | Exit code | Result |
146
+ | --- | --- |
147
+ | `0` | Comparison succeeded and the limit was met, or no limit was requested |
148
+ | `1` | Invalid options, incompatible/stale inputs, or an output error |
149
+ | `2` | Comparison succeeded and the `only-current` count exceeded the limit |
150
+
151
+ On limit failure the full report is still printed or saved, so CI can retain it for review. A numeric pass/fail summary goes to stderr; JSON stdout remains the unchanged `error-to-test/comparison-1` object. Output errors take precedence and preserve existing files. Without `--max-new`, existing comparison behavior is unchanged. The option is available only on `compare`.
152
+
153
+ Choose snapshots with the intended project, environment, period, and collection scope. Partial-export and coverage warnings remain in the report. This limit describes signatures absent from the supplied baseline; it does not establish when an error was introduced, execute TCs, or change their review state. API callers can apply their own threshold to `comparison.counts['only-current']`.
154
+
134
155
  ### Generate TCs for signatures absent from a baseline
135
156
 
136
157
  Pass a verified analysis bundle to `analyze --baseline` to focus TC generation on current signatures that were not observed in that baseline:
@@ -174,6 +195,25 @@ For each scenario, fill `requirement` and `expectedSource`, establish `precondit
174
195
 
175
196
  `init-profile` requires a new output file, refuses stale bundles and empty candidate selections, and never overwrites an existing file. The original analysis artifacts remain unchanged. The API equivalent is `createProfileTemplate(analysis)`; its result is an incomplete `error-to-test/profile-1` object for editing, not an execution-ready profile.
176
197
 
198
+ ### Extend an existing profile
199
+
200
+ Keep existing scenario rules and add review templates for selected groups that they do not cover:
201
+
202
+ ```sh
203
+ error-to-test analyze --input current-errors.jsonl --format jsonl --out ./current-analysis
204
+ error-to-test init-profile ./current-analysis --profile ./existing-profile.json --out ./expanded-profile.json
205
+ # Fill only the new blank requirements, sources, setup, actions, and assertions.
206
+ error-to-test analyze --input current-errors.jsonl --format jsonl --profile ./expanded-profile.json --out ./expanded-analysis
207
+ ```
208
+
209
+ The existing profile must pass normal profile validation: its requirements and expectation sources must already be filled. Profile name, scenario order, IDs, match conditions, steps, expectations, setup flags, and questions are retained as validated profile values. Unknown fields and file formatting are not preserved. Existing questions and unconfirmed setup still block cases.
210
+
211
+ Coverage uses exactly the same matching rules as TC generation, with all supplied predicates combined. An existing broad rule can cover several selected groups within its original conditions. An exact `match.groupId` from another release remains exact; its steps and expectation are not copied to a new group. Only uncovered selected groups receive new blank templates in ranked order. New scenario IDs gain deterministic numeric suffixes on collision; existing IDs stay unchanged. If all selected groups are covered, the result contains only the existing rules.
212
+
213
+ New templates retain blank expectation fields, `setupConfirmed: false`, and the review question. Fill them explicitly before reanalysis, using the original inputs, metadata, filters, and optional baseline. The usual review gate applies. Existing scenarios are never automatically deleted; the combined profile must stay within 100 scenarios and 1 MiB. Sensitive existing metadata or execution steps are rejected before writing. Output must be a new file outside the bundle's `results` directory, for both basic and extended templates.
214
+
215
+ The API is `createProfileTemplate(analysis, { profile: existingProfile })`; `profile` accepts an object containing only JSON values or a JSON string, including one leading BOM, within 1 MiB. Omit undefined optional properties from object inputs. The function does not mutate either input. Without `profile`, it produces the original blank template.
216
+
177
217
  ## Review and use Flow QA
178
218
 
179
219
  Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
@@ -1,3 +1,5 @@
1
- import type { AppProfile, IssueGroup, TestCandidate } from './types.ts';
1
+ import type { AppProfile, IssueGroup, ScenarioRule, TestCandidate, WebStep } from './types.ts';
2
+ export declare function stepsContainSensitiveData(steps: WebStep[]): boolean;
2
3
  export declare function parseProfile(raw: unknown): AppProfile;
4
+ export declare function matchesScenarioRule(rule: ScenarioRule, group: IssueGroup): boolean;
3
5
  export declare function createCandidates(groups: IssueGroup[], profile?: AppProfile): TestCandidate[];
@@ -23,7 +23,7 @@ function profileText(value, label) {
23
23
  function profileStrings(value, label) {
24
24
  return strings(value, label).map((item, index) => profileText(item, `${label}[${index}]`));
25
25
  }
26
- function stepsContainSensitiveData(steps) {
26
+ export function stepsContainSensitiveData(steps) {
27
27
  const credentialFill = steps.some((step) => step.type === 'fill' &&
28
28
  /password|passwd|secret|token|api[_-]?key|authorization|cookie|session/i.test(`${step.locator.value} ${'name' in step.locator ? step.locator.name ?? '' : ''}`));
29
29
  if (credentialFill)
@@ -92,7 +92,7 @@ function confirmed(value, label) {
92
92
  throw new Error(`${label} must be a boolean.`);
93
93
  return value;
94
94
  }
95
- function matches(rule, group) {
95
+ export function matchesScenarioRule(rule, group) {
96
96
  const match = rule.match;
97
97
  return (match.groupId === undefined || match.groupId === group.id)
98
98
  && (!match.type || match.type === group.type)
@@ -184,7 +184,7 @@ function createOne(group, rule) {
184
184
  }
185
185
  export function createCandidates(groups, profile) {
186
186
  return groups.flatMap((group) => {
187
- const rules = (profile?.scenarios ?? []).filter((rule) => matches(rule, group)).sort((a, b) => a.id.localeCompare(b.id));
187
+ const rules = (profile?.scenarios ?? []).filter((rule) => matchesScenarioRule(rule, group)).sort((a, b) => a.id.localeCompare(b.id));
188
188
  return rules.length ? rules.map((rule) => createOne(group, rule)) : [createOne(group)];
189
189
  });
190
190
  }
package/dist/cli.js CHANGED
@@ -20,9 +20,10 @@ const help = `Error to Test — local error analysis and regression TC drafts
20
20
  cat error.txt | error-to-test analyze --input - --format text --out new-directory
21
21
  error-to-test verify new-directory [--input errors-1.json --input errors-2.json] [--profile profile.json]
22
22
  error-to-test init-profile new-directory --out profile.json
23
+ error-to-test init-profile new-directory --profile existing.json --out extended.json
23
24
  error-to-test link-run new-directory --report path/to/qa-report.json
24
25
  error-to-test results new-directory [--format text|json] [--out summary.md]
25
- error-to-test compare BASELINE CURRENT [--format text|json] [--out comparison.md]
26
+ error-to-test compare BASELINE CURRENT [--format text|json] [--out comparison.md] [--max-new N]
26
27
 
27
28
  Options:
28
29
  --input FILE SDK export, manual JSON, JSONL, or plain error text; repeat for same-format files in order (analyze: sole - for stdin)
@@ -30,7 +31,7 @@ Options:
30
31
  --format auto|json|jsonl|text Analyze input format; JSONL requires explicit selection and one record per line; auto rejects malformed JSON-looking input
31
32
  --format text|json Results summary format (default: text Markdown)
32
33
  --format text|json Compare format (default: text Markdown)
33
- --profile FILE Confirmed app scenarios and explicit assertions (optional)
34
+ --profile FILE Confirmed app scenarios and explicit assertions (analyze/verify); existing profile to extend (init-profile)
34
35
  --baseline DIRECTORY Select only signatures absent from this verified bundle, before --min-count and --top; retain all groups in analysis.json (analyze only)
35
36
  --project NAME Metadata for a manual report
36
37
  --environment NAME Metadata for a manual report
@@ -49,6 +50,7 @@ Options:
49
50
  --out FILE New init-profile JSON file; existing files are never overwritten
50
51
  --out FILE New results summary file; existing files are never overwritten
51
52
  --out FILE New comparison file; existing files are never overwritten
53
+ --max-new N Compare only: allow 0..10000 only-current signatures; exit 0 within limit, 2 over limit, 1 on error
52
54
  --reviewed Acknowledge review; unresolved questions still block cases
53
55
  --report FILE Normalized Flow QA report (link-run only)
54
56
  --version, -v Print the package version
@@ -73,6 +75,23 @@ async function stdinText() {
73
75
  throw new Error('Input must be valid UTF-8.');
74
76
  return input.toString('utf8');
75
77
  }
78
+ async function writeGateOutput(content) {
79
+ await new Promise((resolveWrite, rejectWrite) => {
80
+ const onError = (error) => { process.stdout.off('error', onError); rejectWrite(error); };
81
+ process.stdout.on('error', onError);
82
+ process.stdout.write(content, (error) => {
83
+ if (error) {
84
+ rejectWrite(error);
85
+ // Writable can emit 'error' after invoking the failed write callback.
86
+ setImmediate(() => process.stdout.off('error', onError));
87
+ }
88
+ else {
89
+ process.stdout.off('error', onError);
90
+ resolveWrite();
91
+ }
92
+ });
93
+ });
94
+ }
76
95
  async function inputContents(paths, allowStdin) {
77
96
  if (paths.length < 1 || paths.length > 50)
78
97
  throw new Error('Provide between 1 and 50 --input files.');
@@ -123,7 +142,7 @@ export async function main(args = process.argv.slice(2)) {
123
142
  help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string', multiple: true }, error: { type: 'string' }, report: { type: 'string' },
124
143
  format: { type: 'string' }, profile: { type: 'string' }, baseline: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
125
144
  release: { type: 'string' }, page: { type: 'string' }, type: { type: 'string' }, runtime: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' },
126
- top: { type: 'string' }, 'min-count': { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
145
+ top: { type: 'string' }, 'min-count': { type: 'string' }, 'max-new': { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
127
146
  reproduce: { type: 'string', multiple: true }, precondition: { type: 'string', multiple: true },
128
147
  expected: { type: 'string' }, 'expected-source': { type: 'string' },
129
148
  } });
@@ -146,16 +165,24 @@ export async function main(args = process.argv.slice(2)) {
146
165
  if (command === 'init-profile') {
147
166
  if (positionals.length !== 2 || !positionals[1] || !values.out)
148
167
  throw new Error('init-profile requires one bundle directory and --out FILE.');
149
- if (Object.keys(values).some(key => !['out', 'help'].includes(key)))
150
- throw new Error('Unsupported option for init-profile. Use only --out FILE.');
151
- const { analysis } = await readVerifiedBundle(resolve(positionals[1]));
168
+ if (Object.keys(values).some(key => !['out', 'profile', 'help'].includes(key)))
169
+ throw new Error('Unsupported option for init-profile. Use only --profile FILE and --out FILE.');
170
+ if (values.profile !== undefined && !values.profile.trim())
171
+ throw new Error('--profile requires a nonempty file path.');
172
+ const bundle = resolve(positionals[1]);
173
+ const { analysis } = await readVerifiedBundle(bundle);
152
174
  if (analysis.schemaVersion !== 'error-to-test/analysis-1' || !Array.isArray(analysis.groups) || !Array.isArray(analysis.candidates))
153
175
  throw new Error('Unsupported analysis contract.');
154
- const profile = createProfileTemplate(analysis);
176
+ const profile = values.profile === undefined
177
+ ? createProfileTemplate(analysis)
178
+ : createProfileTemplate(analysis, { profile: await readBoundedFile(resolve(values.profile), 1024 * 1024) });
155
179
  const content = jsonText(profile);
156
180
  if (Buffer.byteLength(content) > 1024 * 1024)
157
181
  throw new Error('The generated profile exceeds 1 MiB. Narrow the selected groups.');
158
182
  const out = resolve(values.out);
183
+ if (insideBundleResults(await realpath(bundle), await canonicalOutput(out))) {
184
+ throw new Error('The profile cannot be written inside the bundle results directory. Choose an outside --out FILE path.');
185
+ }
159
186
  await mkdir(dirname(out), { recursive: true });
160
187
  try {
161
188
  await writeFile(out, content, { flag: 'wx', mode: 0o600 });
@@ -165,7 +192,7 @@ export async function main(args = process.argv.slice(2)) {
165
192
  throw new Error('The output file already exists. Choose a new --out FILE path.');
166
193
  throw error;
167
194
  }
168
- process.stdout.write(`Profile template written: ${out}\nFill requirement, expectedSource, preconditions, and steps; confirm setupConfirmed and clear answered questions. Then rerun analyze with the original input and --profile ${out}.\n`);
195
+ process.stdout.write(`Profile template written: ${out}\n${values.profile === undefined ? '' : 'Existing rules were retained; fill and review any new blank scenarios manually. This does not approve the profile.\n'}Fill requirement, expectedSource, preconditions, and steps; confirm setupConfirmed and clear answered questions. Then rerun analyze with the original input and --profile ${out}.\n`);
169
196
  return;
170
197
  }
171
198
  if (command === 'link-run') {
@@ -220,19 +247,37 @@ export async function main(args = process.argv.slice(2)) {
220
247
  if (command === 'compare') {
221
248
  if (positionals.length !== 3 || !positionals[1] || !positionals[2])
222
249
  throw new Error('compare requires BASELINE and CURRENT bundle directories.');
223
- if (Object.keys(values).some(key => !['format', 'out', 'help'].includes(key)))
224
- throw new Error('Unsupported option for compare. Use only --format text|json and --out FILE.');
250
+ if (Object.keys(values).some(key => !['format', 'out', 'max-new', 'help'].includes(key)))
251
+ throw new Error('Unsupported option for compare. Use only --format text|json, --out FILE, and --max-new N.');
225
252
  const format = values.format ?? 'text';
226
253
  if (format !== 'text' && format !== 'json')
227
254
  throw new Error('compare --format must be text or json.');
255
+ const maxNewRaw = values['max-new'];
256
+ if (maxNewRaw !== undefined && (!/^[0-9]+$/.test(maxNewRaw) || Number(maxNewRaw) > 10000)) {
257
+ throw new Error('compare --max-new must be a decimal integer between 0 and 10000.');
258
+ }
259
+ const maxNew = maxNewRaw === undefined ? undefined : Number(maxNewRaw);
228
260
  const baseline = resolve(positionals[1]);
229
261
  const current = resolve(positionals[2]);
230
262
  const comparison = await compareBundles(baseline, current);
231
263
  const content = format === 'json' ? jsonText(comparison) : renderComparison(comparison);
232
264
  if (Buffer.byteLength(content) > 64 * 1024 * 1024)
233
265
  throw new Error('The comparison exceeds 64 MiB. Narrow the bundles before requesting output.');
266
+ const finishGate = () => {
267
+ if (maxNew === undefined)
268
+ return;
269
+ const count = comparison.counts['only-current'];
270
+ const passed = count <= maxNew;
271
+ process.stderr.write(`Comparison gate ${passed ? 'passed' : 'failed'}: ${count} only-current signatures ${passed ? `(maximum ${maxNew}).` : `exceed maximum ${maxNew}.`}\n`);
272
+ if (!passed)
273
+ process.exitCode = 2;
274
+ };
234
275
  if (values.out === undefined) {
235
- process.stdout.write(content);
276
+ if (maxNew === undefined)
277
+ process.stdout.write(content);
278
+ else
279
+ await writeGateOutput(content);
280
+ finishGate();
236
281
  return;
237
282
  }
238
283
  const out = resolve(values.out);
@@ -251,7 +296,12 @@ export async function main(args = process.argv.slice(2)) {
251
296
  throw new Error('The output file already exists. Choose a new --out FILE path.');
252
297
  throw error;
253
298
  }
254
- process.stdout.write(`Comparison written: ${out}\n`);
299
+ const written = `Comparison written: ${out}\n`;
300
+ if (maxNew === undefined)
301
+ process.stdout.write(written);
302
+ else
303
+ await writeGateOutput(written);
304
+ finishGate();
255
305
  return;
256
306
  }
257
307
  if (command === 'verify') {
@@ -270,6 +320,8 @@ export async function main(args = process.argv.slice(2)) {
270
320
  throw new Error('Use analyze, init-profile, verify, link-run, results, or compare. See --help.');
271
321
  if (values.report)
272
322
  throw new Error('--report applies to link-run only.');
323
+ if (values['max-new'] !== undefined)
324
+ throw new Error('--max-new applies to compare only.');
273
325
  if (values.baseline !== undefined && values.baseline.trim() === '')
274
326
  throw new Error('--baseline requires a bundle directory.');
275
327
  if ((values.input === undefined) === (values.error === undefined))
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { createCandidates, parseProfile } from './candidates.ts';
5
5
  export { exportFlowQa } from './exports/flow-qa.ts';
6
6
  export { writeBundle, verifyBundle, renderReport } from './artifacts.ts';
7
7
  export { linkFlowQaReport } from './results.ts';
8
- export { createProfileTemplate } from './profile-template.ts';
8
+ export { createProfileTemplate, type ProfileTemplateOptions } from './profile-template.ts';
9
9
  export { readRunSummary, renderRunSummary, type RunSummary, type LinkedRunStatus, type LinkedCaseStatus } from './run-summary.ts';
10
10
  export { compareBundles, renderComparison, type AnalysisComparison, type ComparisonStatus, type ComparisonSide, type ComparisonOccurrence, type ComparisonIssue } from './comparison.ts';
11
11
  export type * from './types.ts';
@@ -1,2 +1,5 @@
1
1
  import type { Analysis, AppProfile } from './types.ts';
2
- export declare function createProfileTemplate(analysis: Analysis): AppProfile;
2
+ export interface ProfileTemplateOptions {
3
+ profile?: unknown;
4
+ }
5
+ export declare function createProfileTemplate(analysis: Analysis, options?: ProfileTemplateOptions): AppProfile;
@@ -1,7 +1,85 @@
1
+ import { matchesScenarioRule, parseProfile, stepsContainSensitiveData } from "./candidates.js";
1
2
  import { pagePath, redactText, safeUrl } from "./redact.js";
2
3
  import { parseWebSteps, record } from "./validation.js";
3
4
  const idPattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/;
4
5
  const question = 'Confirm the expected behavior, setup, reproduction steps, and assertion, then remove this question.';
6
+ const maxProfileBytes = 1024 * 1024;
7
+ function assertJsonValue(value, active) {
8
+ if (value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))
9
+ return;
10
+ if (typeof value !== 'object')
11
+ throw new Error('The profile object must contain only JSON values.');
12
+ if (active.has(value))
13
+ throw new Error('The profile object must contain only JSON values.');
14
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
15
+ throw new Error('The profile object must contain only JSON values.');
16
+ }
17
+ active.add(value);
18
+ try {
19
+ const keys = Reflect.ownKeys(value);
20
+ if (Array.isArray(value) && keys.length !== value.length + 1)
21
+ throw new Error('The profile object must contain only JSON values.');
22
+ for (const key of keys) {
23
+ if (Array.isArray(value) && key === 'length')
24
+ continue;
25
+ if (typeof key !== 'string' || (Array.isArray(value) && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length))) {
26
+ throw new Error('The profile object must contain only JSON values.');
27
+ }
28
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
29
+ if (!descriptor?.enumerable || !('value' in descriptor))
30
+ throw new Error('The profile object must contain only JSON values.');
31
+ assertJsonValue(descriptor.value, active);
32
+ }
33
+ }
34
+ finally {
35
+ active.delete(value);
36
+ }
37
+ }
38
+ function existingProfile(raw) {
39
+ let input;
40
+ if (typeof raw === 'string') {
41
+ if (Buffer.byteLength(raw, 'utf8') > maxProfileBytes)
42
+ throw new Error('The profile must be 1 MiB or smaller.');
43
+ try {
44
+ input = JSON.parse(raw.replace(/^\uFEFF/, ''));
45
+ }
46
+ catch {
47
+ throw new Error('The profile is not valid JSON.');
48
+ }
49
+ }
50
+ else {
51
+ let serialized;
52
+ try {
53
+ assertJsonValue(raw, new WeakSet());
54
+ serialized = JSON.stringify(raw);
55
+ }
56
+ catch {
57
+ throw new Error('The profile object must contain only JSON values.');
58
+ }
59
+ if (Buffer.byteLength(serialized, 'utf8') > maxProfileBytes)
60
+ throw new Error('The profile must be 1 MiB or smaller.');
61
+ input = JSON.parse(serialized);
62
+ }
63
+ const parsed = parseProfile(input);
64
+ if (parsed.scenarios.some((scenario) => redactText(scenario.id) !== scenario.id ||
65
+ (scenario.match.groupId !== undefined && redactText(scenario.match.groupId) !== scenario.match.groupId))) {
66
+ throw new Error('The existing profile contains sensitive scenario IDs; remove them before extending it.');
67
+ }
68
+ if (parsed.scenarios.some((scenario) => stepsContainSensitiveData(scenario.steps))) {
69
+ throw new Error('The existing profile contains sensitive execution steps; remove them before extending it.');
70
+ }
71
+ return parsed;
72
+ }
73
+ function newScenarioId(base, used) {
74
+ if (!used.has(base))
75
+ return base;
76
+ for (let number = 2;; number++) {
77
+ const suffix = `-${number}`;
78
+ const candidate = `${base.slice(0, 80 - suffix.length)}${suffix}`;
79
+ if (!used.has(candidate))
80
+ return candidate;
81
+ }
82
+ }
5
83
  function selectedId(value, label) {
6
84
  if (typeof value !== 'string' || !idPattern.test(value))
7
85
  throw new Error(`${label} must be a Flow QA-compatible ID.`);
@@ -33,7 +111,7 @@ function reviewTitle(message) {
33
111
  const short = [...safe].slice(0, 190).join('').trim();
34
112
  return `Review ${short || 'observed error'}`;
35
113
  }
36
- export function createProfileTemplate(analysis) {
114
+ export function createProfileTemplate(analysis, options = {}) {
37
115
  const input = record(analysis, 'analysis');
38
116
  if (!Array.isArray(input.groups) || input.groups.length > 10000)
39
117
  throw new Error('analysis.groups must be an array of at most 10000 groups.');
@@ -45,8 +123,10 @@ export function createProfileTemplate(analysis) {
45
123
  }
46
124
  if (selected.size > 100)
47
125
  throw new Error('Template supports at most 100 selected groups and scenarios.');
126
+ const existing = options.profile === undefined ? undefined : existingProfile(options.profile);
48
127
  const seen = new Set();
49
- const scenarios = [];
128
+ const scenarios = existing ? [...existing.scenarios] : [];
129
+ const usedIds = new Set(scenarios.map((scenario) => scenario.id));
50
130
  for (const [index, raw] of input.groups.entries()) {
51
131
  const group = record(raw, `analysis.groups[${index}]`);
52
132
  const id = selectedId(group.id, `analysis.groups[${index}].id`);
@@ -55,10 +135,16 @@ export function createProfileTemplate(analysis) {
55
135
  if (seen.has(id))
56
136
  throw new Error(`Selected group ID is duplicated: ${id}.`);
57
137
  seen.add(id);
138
+ if (existing && existing.scenarios.some((scenario) => matchesScenarioRule(scenario, group)))
139
+ continue;
58
140
  if (`review-${id}`.length > 80)
59
141
  throw new Error(`Selected group ID is too long for a profile scenario: ${id}.`);
142
+ if (scenarios.length >= 100)
143
+ throw new Error('The extended profile supports at most 100 scenarios.');
144
+ const scenarioId = existing ? newScenarioId(`review-${id}`, usedIds) : `review-${id}`;
145
+ usedIds.add(scenarioId);
60
146
  scenarios.push({
61
- id: `review-${id}`,
147
+ id: scenarioId,
62
148
  title: reviewTitle(group.message),
63
149
  match: { groupId: id },
64
150
  requirement: '',
@@ -71,5 +157,9 @@ export function createProfileTemplate(analysis) {
71
157
  }
72
158
  if (seen.size !== selected.size)
73
159
  throw new Error('Selected candidate references a missing group ID.');
74
- return { schemaVersion: 'error-to-test/profile-1', name: 'Error to Test review', scenarios };
160
+ const profile = { schemaVersion: 'error-to-test/profile-1', name: existing?.name ?? 'Error to Test review', scenarios };
161
+ if (existing && Buffer.byteLength(`${JSON.stringify(profile, null, 2)}\n`, 'utf8') > maxProfileBytes) {
162
+ throw new Error('The generated profile exceeds 1 MiB. Narrow the selected groups or scenario details.');
163
+ }
164
+ return profile;
75
165
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ihyeon/error-to-test",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Turn captured browser errors and pasted error reports into traceable regression test candidates.",
5
5
  "license": "MIT",
6
6
  "author": "Hyeonse Im",