@sdods/core 0.3.2 → 0.5.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.
Files changed (56) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/api/client.d.ts +62 -1
  3. package/dist/api/client.js +189 -27
  4. package/dist/api/template.d.ts +15 -2
  5. package/dist/api/template.js +31 -13
  6. package/dist/auth/capture.js +4 -3
  7. package/dist/auth/index.js +3 -18
  8. package/dist/config/defaults.js +2 -0
  9. package/dist/config/resolve.d.ts +5 -1
  10. package/dist/config/resolve.js +16 -3
  11. package/dist/config/runner.d.ts +26 -1
  12. package/dist/config/runner.js +155 -24
  13. package/dist/config/tags.d.ts +14 -2
  14. package/dist/config/tags.js +27 -7
  15. package/dist/evidence/index.d.ts +3 -0
  16. package/dist/evidence/index.js +3 -0
  17. package/dist/evidence/trace-redact.d.ts +74 -0
  18. package/dist/evidence/trace-redact.js +297 -0
  19. package/dist/evidence/zip.d.ts +36 -0
  20. package/dist/evidence/zip.js +148 -0
  21. package/dist/fixtures/api-context.d.ts +7 -0
  22. package/dist/fixtures/api-context.js +7 -0
  23. package/dist/fixtures/auth.js +72 -5
  24. package/dist/fixtures/test.js +9 -2
  25. package/dist/heal/healer.d.ts +12 -1
  26. package/dist/heal/healer.js +80 -34
  27. package/dist/heal/strategies.d.ts +12 -2
  28. package/dist/heal/strategies.js +42 -0
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.js +1 -0
  31. package/dist/lint/index.d.ts +1 -0
  32. package/dist/lint/index.js +44 -3
  33. package/dist/lint/steps.d.ts +13 -0
  34. package/dist/lint/steps.js +333 -0
  35. package/dist/load-module.d.ts +7 -0
  36. package/dist/load-module.js +70 -0
  37. package/dist/logger.d.ts +1 -0
  38. package/dist/logger.js +9 -3
  39. package/dist/steps/a11y.steps.js +10 -10
  40. package/dist/steps/api.steps.js +64 -27
  41. package/dist/steps/browser.steps.js +34 -33
  42. package/dist/steps/clock.steps.js +5 -5
  43. package/dist/steps/data.steps.js +61 -8
  44. package/dist/steps/db.steps.js +8 -8
  45. package/dist/steps/dom.steps.js +49 -49
  46. package/dist/steps/hybrid.steps.js +9 -5
  47. package/dist/steps/iframe.steps.js +9 -9
  48. package/dist/steps/net.steps.d.ts +12 -7
  49. package/dist/steps/net.steps.js +78 -83
  50. package/dist/steps/perf.steps.js +6 -6
  51. package/dist/steps/tabs.steps.js +6 -6
  52. package/dist/steps/ui.steps.js +94 -45
  53. package/dist/steps/webhook.steps.js +3 -3
  54. package/dist/version.d.ts +1 -1
  55. package/dist/version.js +15 -1
  56. package/package.json +6 -4
@@ -3,7 +3,7 @@ import { expect } from '@playwright/test';
3
3
  import { attachmentNames, scenarioFiles } from '@sdods/contracts';
4
4
  import { Logger } from '../logger.js';
5
5
  import { SdodsError } from '../errors.js';
6
- import { buildCandidates } from './strategies.js';
6
+ import { buildCandidates, disambiguationCandidates, rolesFor } from './strategies.js';
7
7
  /** Locator wrapper: every action goes through the healer. */
8
8
  export class HealedLocator {
9
9
  healer;
@@ -83,54 +83,100 @@ export class Healer {
83
83
  async expectText(primary, ctx, text) {
84
84
  await expect(await this.resolve(primary, ctx, 'assert')).toContainText(text);
85
85
  }
86
+ /**
87
+ * The first of `locators`, in preference order, that matches anything. Waits up to
88
+ * primaryTimeoutMs for the LAST one to attach — callers list the loosest locator last, a
89
+ * superset of the others — so an element that renders a moment late is still judged by the
90
+ * most precise locator. When nothing matches, the most precise one is returned for resolve()
91
+ * to wait on and heal from.
92
+ */
93
+ async prefer(...locators) {
94
+ const loosest = locators[locators.length - 1];
95
+ await loosest
96
+ .first()
97
+ .waitFor({ state: 'attached', timeout: this.deps.config.primaryTimeoutMs })
98
+ .catch(() => undefined);
99
+ for (const locator of locators)
100
+ if ((await locator.count()) > 0)
101
+ return locator;
102
+ return locators[0];
103
+ }
86
104
  /**
87
105
  * Wait briefly for the primary locator; on failure probe all candidates in parallel,
88
- * score them and pick the best above minScore. Records a HealEvent either way.
106
+ * score them and pick the best above minScore. A primary that is visible but matches several
107
+ * elements is healed too, for actions that have a role to prefer. Records a HealEvent whenever
108
+ * it heals.
89
109
  */
90
110
  async resolve(primary, ctx, action) {
91
111
  const cfg = this.deps.config;
112
+ const healable = cfg.enabled && cfg.actions.includes(action);
92
113
  try {
93
114
  await primary.first().waitFor({ state: 'visible', timeout: cfg.primaryTimeoutMs });
94
- return primary;
95
115
  }
96
116
  catch (primaryError) {
97
- if (!cfg.enabled || !cfg.actions.includes(action))
117
+ if (!healable)
98
118
  throw primaryError;
99
119
  const page = primary.page();
100
- const t0 = Date.now();
101
120
  const candidates = buildCandidates(page, ctx);
102
121
  if (candidates.length === 0)
103
122
  throw primaryError;
104
- const probes = await Promise.all(candidates.map((c) => this.probe(c, cfg.probeTimeoutMs, action)));
105
- const ranked = probes.sort((a, b) => b.score - a.score);
106
- const best = ranked[0];
107
- const event = {
108
- fingerprint: this.deps.scenario?.fingerprint ?? '',
109
- runId: this.deps.runId ?? '',
110
- stepIndex: this.deps.stepIndex?.() ?? 0,
111
- action,
112
- description: ctx.description,
113
- pageUrl: page.url(),
114
- originalSelector: String(primary),
115
- context: { ...ctx, name: ctx.name instanceof RegExp ? ctx.name.toString() : ctx.name },
116
- strategyUsed: best && best.score >= cfg.minScore ? best.strategy : null,
117
- healedSelector: best && best.score >= cfg.minScore ? best.selector : null,
118
- candidates: ranked.map(({ locator: _l, baseScore: _b, ...rest }) => rest),
119
- succeeded: Boolean(best && best.score >= cfg.minScore),
120
- durationMs: Date.now() - t0,
121
- at: new Date().toISOString(),
122
- };
123
- this.record(event);
124
- if (!event.succeeded || !best) {
125
- throw new SdodsError('HEAL_FAILED', `Could not locate "${ctx.description}" (${String(primary)}) and no healing candidate scored ≥ ${cfg.minScore}.`, {
126
- hint: `Probed: ${ranked.map((p) => `${p.strategy}=${p.score.toFixed(2)}`).join(', ') || 'none'}. Add role/name/testId/label to the heal context or fix the locator.`,
127
- details: { candidates: event.candidates },
128
- cause: primaryError,
129
- });
130
- }
131
- this.log.warn(`healed "${ctx.description}": ${String(primary)} → ${best.selector} via ${best.strategy} (score ${best.score.toFixed(2)}, ${event.durationMs} ms). Update the page object.`);
132
- return best.locator.first();
123
+ // The role filter goes first: a primary whose FIRST match is hidden (a collapsed toggle
124
+ // ahead of the field) never becomes visible, yet narrows to the visible element that fits.
125
+ return this.heal(primary, ctx, action, [...disambiguationCandidates(page, primary, ctx, action), ...candidates], { cause: primaryError });
126
+ }
127
+ // Visible is not enough. A primary matching several elements makes the action throw a
128
+ // strict-mode violation after resolve() has returned, where healing never sees it. Assertions
129
+ // and hovers have no role to prefer, and their callers take .first() when they mean "any of
130
+ // them", so only role-bound actions are disambiguated.
131
+ if (!healable || rolesFor(action).length === 0)
132
+ return primary;
133
+ const matched = await primary.count();
134
+ if (matched <= 1)
135
+ return primary;
136
+ const page = primary.page();
137
+ return this.heal(primary, ctx, action, [...disambiguationCandidates(page, primary, ctx, action), ...buildCandidates(page, ctx)], { matched });
138
+ }
139
+ async heal(primary, ctx, action, candidates, why) {
140
+ const cfg = this.deps.config;
141
+ const page = primary.page();
142
+ const t0 = Date.now();
143
+ const probes = await Promise.all(candidates.map((c) => this.probe(c, cfg.probeTimeoutMs, action)));
144
+ const ranked = probes.sort((a, b) => b.score - a.score);
145
+ // Healing an ambiguity onto another ambiguous locator would only move the strict-mode
146
+ // violation, so that heal accepts a unique candidate only.
147
+ const ambiguous = why.matched !== undefined;
148
+ const best = ranked.find((p) => p.score >= cfg.minScore && (!ambiguous || p.count === 1));
149
+ const event = {
150
+ fingerprint: this.deps.scenario?.fingerprint ?? '',
151
+ runId: this.deps.runId ?? '',
152
+ stepIndex: this.deps.stepIndex?.() ?? 0,
153
+ action,
154
+ description: ctx.description,
155
+ pageUrl: page.url(),
156
+ originalSelector: String(primary),
157
+ context: { ...ctx, name: ctx.name instanceof RegExp ? ctx.name.toString() : ctx.name },
158
+ strategyUsed: best ? best.strategy : null,
159
+ healedSelector: best ? best.selector : null,
160
+ candidates: ranked.map(({ locator: _l, baseScore: _b, ...rest }) => rest),
161
+ succeeded: Boolean(best),
162
+ durationMs: Date.now() - t0,
163
+ at: new Date().toISOString(),
164
+ };
165
+ this.record(event);
166
+ const probed = ranked.map((p) => `${p.strategy}=${p.score.toFixed(2)}`).join(', ') || 'none';
167
+ if (!best) {
168
+ throw new SdodsError('HEAL_FAILED', ambiguous
169
+ ? `"${ctx.description}" (${String(primary)}) matched ${why.matched} elements and no healing candidate narrowed it to one that fits "${action}" with a score ≥ ${cfg.minScore}.`
170
+ : `Could not locate "${ctx.description}" (${String(primary)}) and no healing candidate scored ≥ ${cfg.minScore}.`, {
171
+ hint: ambiguous
172
+ ? `Probed: ${probed}. Make the locator specific to one element: an exact name or label, a role, or a test id.`
173
+ : `Probed: ${probed}. Add role/name/testId/label to the heal context or fix the locator.`,
174
+ details: { candidates: event.candidates },
175
+ cause: why.cause,
176
+ });
133
177
  }
178
+ this.log.warn(`healed "${ctx.description}": ${String(primary)}${ambiguous ? ` (matched ${why.matched})` : ''} → ${best.selector} via ${best.strategy} (score ${best.score.toFixed(2)}, ${event.durationMs} ms). Update the page object.`);
179
+ return best.locator.first();
134
180
  }
135
181
  async probe(c, timeoutMs, action) {
136
182
  const t0 = Date.now();
@@ -1,5 +1,15 @@
1
- import type { Page } from '@playwright/test';
2
- import type { HealContext, HealProbe } from './types.js';
1
+ import type { Locator, Page } from '@playwright/test';
2
+ import type { AriaRole, HealAction, HealContext, HealProbe } from './types.js';
3
+ export declare function rolesFor(action: HealAction): AriaRole[];
4
+ /** `locator` narrowed to elements whose role fits `action`; `locator` itself when none is defined. */
5
+ export declare function withActionRole(page: Page, locator: Locator, action: HealAction): Locator;
6
+ /**
7
+ * Candidates for a primary locator that matched several elements: the primary narrowed to the
8
+ * roles that fit the action (and the context's own role, when it names one), as a single union.
9
+ * A union keeps a genuine tie ambiguous — an input and a select both labelled "Country" still
10
+ * count 2 for a fill — rather than letting role order break it silently.
11
+ */
12
+ export declare function disambiguationCandidates(page: Page, primary: Locator, ctx: HealContext, action: HealAction): Omit<HealProbe, 'score' | 'count' | 'visible' | 'enabled' | 'ms'>[];
3
13
  /** Build candidate locators from the context, ordered by base score (higher = more semantic). */
4
14
  export declare function buildCandidates(page: Page, ctx: HealContext): Omit<HealProbe, 'score' | 'count' | 'visible' | 'enabled' | 'ms'>[];
5
15
  //# sourceMappingURL=strategies.d.ts.map
@@ -1,3 +1,45 @@
1
+ /**
2
+ * The roles an element must have for an action to make sense on it. `assert` and `hover` apply to
3
+ * anything, so they have none. A contenteditable editor has no role at all, which is why callers
4
+ * treat a role filter as a preference, never as the only way to reach an element.
5
+ */
6
+ const ACTION_ROLES = {
7
+ fill: ['textbox', 'searchbox', 'combobox', 'spinbutton'],
8
+ select: ['combobox', 'listbox'],
9
+ check: ['checkbox', 'radio', 'switch'],
10
+ click: ['button', 'link', 'menuitem', 'tab', 'option', 'checkbox', 'radio', 'switch'],
11
+ assert: [],
12
+ hover: [],
13
+ };
14
+ export function rolesFor(action) {
15
+ return ACTION_ROLES[action];
16
+ }
17
+ /** `locator` narrowed to elements whose role fits `action`; `locator` itself when none is defined. */
18
+ export function withActionRole(page, locator, action) {
19
+ const roles = rolesFor(action);
20
+ if (roles.length === 0)
21
+ return locator;
22
+ return locator.and(roles.map((r) => page.getByRole(r)).reduce((union, next) => union.or(next)));
23
+ }
24
+ /**
25
+ * Candidates for a primary locator that matched several elements: the primary narrowed to the
26
+ * roles that fit the action (and the context's own role, when it names one), as a single union.
27
+ * A union keeps a genuine tie ambiguous — an input and a select both labelled "Country" still
28
+ * count 2 for a fill — rather than letting role order break it silently.
29
+ */
30
+ export function disambiguationCandidates(page, primary, ctx, action) {
31
+ const roles = [...new Set([...(ctx.role ? [ctx.role] : []), ...rolesFor(action)])];
32
+ if (roles.length === 0)
33
+ return [];
34
+ return [
35
+ {
36
+ strategy: 'role-filter',
37
+ selector: `${String(primary)}.and(${roles.map((r) => `getByRole('${r}')`).join('.or(')}${')'.repeat(roles.length - 1)})`,
38
+ locator: primary.and(roles.map((r) => page.getByRole(r)).reduce((union, next) => union.or(next))),
39
+ baseScore: 1.0,
40
+ },
41
+ ];
42
+ }
1
43
  /** Build candidate locators from the context, ordered by base score (higher = more semantic). */
2
44
  export function buildCandidates(page, ctx) {
3
45
  const out = [];
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export * from './data/index.js';
7
7
  export * from './heal/index.js';
8
8
  export * from './shots/index.js';
9
9
  export * from './lint/index.js';
10
+ export * from './evidence/index.js';
10
11
  export { BasePage } from './pages/base-page.js';
11
12
  export { PageRegistry } from './fixtures/pages.js';
12
13
  export { AuthStateCache } from './fixtures/auth.js';
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ export * from './data/index.js';
7
7
  export * from './heal/index.js';
8
8
  export * from './shots/index.js';
9
9
  export * from './lint/index.js';
10
+ export * from './evidence/index.js';
10
11
  export { BasePage } from './pages/base-page.js';
11
12
  export { PageRegistry } from './fixtures/pages.js';
12
13
  export { AuthStateCache } from './fixtures/auth.js';
@@ -20,6 +20,7 @@ export declare function detectUndefinedSteps(project: ProjectConfig & {
20
20
  message: string;
21
21
  file?: string;
22
22
  line?: number;
23
+ rule?: string;
23
24
  }>>;
24
25
  export declare function formatFindings(result: LintResult): string;
25
26
  //# sourceMappingURL=index.d.ts.map
@@ -1,9 +1,10 @@
1
1
  import { readdirSync, statSync, existsSync } from 'node:fs';
2
- import { join, relative } from 'node:path';
2
+ import { join, relative, resolve } from 'node:path';
3
3
  import { execa } from 'execa';
4
4
  import { BROWSERS_FOR_SKIP, KNOWN_VALUE_TAGS, LAYER_TAGS, RUNNER_SPECIAL_TAGS, VALUE_TAG, taxonomyFromProject, } from '../config/tags.js';
5
5
  import { moduleForFeature } from '../config/workspace.js';
6
6
  import { parseFeatureFile, scenariosOf } from './gherkin.js';
7
+ import { checkStepAmbiguity } from './steps.js';
7
8
  export * from './gherkin.js';
8
9
  export function listFeatureFiles(root) {
9
10
  const out = [];
@@ -30,8 +31,10 @@ export async function lintProject(opts) {
30
31
  const errors = [];
31
32
  const warnings = [];
32
33
  const rel = (f) => relative(project.root, f).replace(/\\/g, '/');
34
+ const parsedFeatures = [];
33
35
  for (const file of files) {
34
36
  const parsed = parseFeatureFile(file);
37
+ parsedFeatures.push(parsed);
35
38
  for (const e of parsed.errors)
36
39
  errors.push({
37
40
  severity: 'error',
@@ -213,16 +216,25 @@ export async function lintProject(opts) {
213
216
  seen.set(key, sc.line);
214
217
  }
215
218
  }
219
+ // A phrasing matched by two definitions stops bddgen generating anything (#60).
220
+ const ambiguity = await checkStepAmbiguity({ project, features: parsedFeatures });
221
+ errors.push(...ambiguity.errors);
222
+ warnings.push(...ambiguity.warnings);
216
223
  if (opts.undefinedSteps && opts.repoRoot) {
217
224
  const found = await detectUndefinedSteps(project, opts.repoRoot);
218
- for (const f of found)
225
+ for (const f of found) {
226
+ const rule = f.rule ?? 'steps/undefined';
227
+ // The static check above usually saw this ambiguity already; do not report it twice.
228
+ if (errors.some((e) => e.rule === rule && e.file === f.file && e.line === f.line))
229
+ continue;
219
230
  errors.push({
220
231
  severity: 'error',
221
- rule: 'steps/undefined',
232
+ rule,
222
233
  message: f.message,
223
234
  file: f.file ?? '',
224
235
  line: f.line,
225
236
  });
237
+ }
226
238
  }
227
239
  return { errors, warnings, filesChecked: files.length };
228
240
  }
@@ -266,6 +278,35 @@ export async function detectUndefinedSteps(project, repoRoot) {
266
278
  .slice(0, 10)
267
279
  .join(' | '),
268
280
  });
281
+ // bddgen stops at the first ambiguous step. This parser only knew the missing-step block, so an
282
+ // ambiguity (#60) — or any other generation failure — came back as "no findings".
283
+ const ambiguous = /^Step: (.+?) # (.+\.feature):(\d+)(?::\d+)?$/;
284
+ for (let i = 0; i < lines.length; i++) {
285
+ const s = ambiguous.exec(lines[i].trim());
286
+ if (!s || !/Multiple definitions matched/.test(lines[i - 1] ?? ''))
287
+ continue;
288
+ const variants = [];
289
+ for (let j = i + 1; j < lines.length && lines[j].trim().startsWith('- '); j++)
290
+ variants.push(lines[j].trim().slice(2));
291
+ out.push({
292
+ rule: 'steps/ambiguous',
293
+ message: `Multiple definitions matched "${s[1]}": ${variants.join('; ')}`,
294
+ file: relative(project.root, resolve(repoRoot, s[2])).replace(/\\/g, '/'),
295
+ line: Number(s[3]),
296
+ });
297
+ }
298
+ if (!out.length) {
299
+ const tail = text
300
+ .split('\n')
301
+ .map((l) => l.trim())
302
+ .filter(Boolean)
303
+ .slice(-5)
304
+ .join(' | ');
305
+ out.push({
306
+ rule: 'steps/bddgen',
307
+ message: `bddgen failed to generate specs (exit ${result.exitCode}): ${tail || '(no output)'}`,
308
+ });
309
+ }
269
310
  return out;
270
311
  }
271
312
  export function formatFindings(result) {
@@ -0,0 +1,13 @@
1
+ import type { LintFinding, ProjectConfig } from '@sdods/contracts';
2
+ import type { ParsedFeature } from './gherkin.js';
3
+ export interface AmbiguityCheckOptions {
4
+ project: ProjectConfig & {
5
+ root: string;
6
+ };
7
+ features: ParsedFeature[];
8
+ }
9
+ export declare function checkStepAmbiguity(opts: AmbiguityCheckOptions): Promise<{
10
+ errors: LintFinding[];
11
+ warnings: LintFinding[];
12
+ }>;
13
+ //# sourceMappingURL=steps.d.ts.map