cypress-annotate 0.4.0 → 1.0.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.
Files changed (63) hide show
  1. package/AGENTS.md +40 -28
  2. package/CHANGELOG.md +142 -0
  3. package/DOCS/images/crop.png +0 -0
  4. package/DOCS/images/failure-hook.png +0 -0
  5. package/DOCS/internals.md +151 -0
  6. package/README.md +104 -352
  7. package/dist/annotate-image.d.ts +5 -0
  8. package/dist/annotate-image.d.ts.map +1 -1
  9. package/dist/annotate-image.js +16 -2
  10. package/dist/cypress/commands.d.ts +6 -1
  11. package/dist/cypress/commands.d.ts.map +1 -1
  12. package/dist/cypress/commands.js +13 -6
  13. package/dist/cypress/config.d.ts +42 -0
  14. package/dist/cypress/config.d.ts.map +1 -0
  15. package/dist/cypress/config.js +102 -0
  16. package/dist/cypress/failure-hook.d.ts.map +1 -1
  17. package/dist/cypress/failure-hook.js +10 -3
  18. package/dist/cypress/failure-report.d.ts +6 -0
  19. package/dist/cypress/failure-report.d.ts.map +1 -1
  20. package/dist/cypress/failure-report.js +14 -4
  21. package/dist/cypress/task.d.ts +36 -2
  22. package/dist/cypress/task.d.ts.map +1 -1
  23. package/dist/cypress/task.js +60 -5
  24. package/dist/draw.d.ts +4 -0
  25. package/dist/draw.d.ts.map +1 -1
  26. package/dist/draw.js +7 -4
  27. package/dist/index.d.ts +9 -20
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +7 -57
  30. package/dist/types.d.ts +6 -72
  31. package/dist/types.d.ts.map +1 -1
  32. package/package.json +10 -42
  33. package/skills/cypress-annotate/SKILL.md +51 -9
  34. package/DOCS/pipeline.md +0 -308
  35. package/dist/annotate.d.ts +0 -9
  36. package/dist/annotate.d.ts.map +0 -1
  37. package/dist/annotate.js +0 -82
  38. package/dist/browser/collect-elements.js +0 -158
  39. package/dist/browser/measure-target.js +0 -69
  40. package/dist/claude-reasoner.d.ts +0 -17
  41. package/dist/claude-reasoner.d.ts.map +0 -1
  42. package/dist/claude-reasoner.js +0 -192
  43. package/dist/cli.d.ts +0 -3
  44. package/dist/cli.d.ts.map +0 -1
  45. package/dist/cli.js +0 -84
  46. package/dist/cypress/failure-explainer.d.ts +0 -45
  47. package/dist/cypress/failure-explainer.d.ts.map +0 -1
  48. package/dist/cypress/failure-explainer.js +0 -123
  49. package/dist/finder.d.ts +0 -68
  50. package/dist/finder.d.ts.map +0 -1
  51. package/dist/finder.js +0 -64
  52. package/dist/inventory.d.ts +0 -33
  53. package/dist/inventory.d.ts.map +0 -1
  54. package/dist/inventory.js +0 -88
  55. package/dist/measure.d.ts +0 -11
  56. package/dist/measure.d.ts.map +0 -1
  57. package/dist/measure.js +0 -145
  58. package/dist/pipeline.d.ts +0 -60
  59. package/dist/pipeline.d.ts.map +0 -1
  60. package/dist/pipeline.js +0 -115
  61. package/skills/annotate-bug/SKILL.md +0 -121
  62. package/src/browser/collect-elements.js +0 -158
  63. package/src/browser/measure-target.js +0 -69
package/dist/annotate.js DELETED
@@ -1,82 +0,0 @@
1
- import { annotateImage } from './annotate-image.js';
2
- import { measureElement, measureRegion, readPageMetrics, scrollElementIntoView } from './measure.js';
3
- /**
4
- * Playwright-driven annotation: position the page, measure, capture, and hand
5
- * the pixels to `annotateImage`, which owns all the coordinate maths and is
6
- * shared with the driver-agnostic path.
7
- */
8
- export async function annotate(page, annotations, options = {}) {
9
- if (annotations.length === 0)
10
- throw new Error('No annotations supplied.');
11
- const mode = options.mode ?? 'viewport';
12
- const fullPageCapture = mode !== 'viewport';
13
- const warnings = [];
14
- // Positioning happens before measurement: any scroll invalidates every rect.
15
- if (fullPageCapture && (options.scrollToTop ?? true)) {
16
- await page.evaluate(() => window.scrollTo(0, 0));
17
- }
18
- else if (mode === 'viewport' && (options.scrollIntoView ?? true)) {
19
- // A region is defined relative to wherever the page already is, so
20
- // scrolling to reveal it would invalidate the very percentages given.
21
- const first = annotations[0];
22
- if (first?.selector)
23
- await scrollElementIntoView(page, first.selector);
24
- }
25
- await page.waitForTimeout(60);
26
- const metrics = await readPageMetrics(page);
27
- const elements = [];
28
- for (const annotation of annotations) {
29
- if (annotation.selector && annotation.region) {
30
- throw new Error('An annotation takes either a selector or a region, not both.');
31
- }
32
- if (annotation.selector) {
33
- elements.push(await measureElement(page, annotation.selector, metrics));
34
- }
35
- else if (annotation.region) {
36
- elements.push(measureRegion(annotation.region, metrics));
37
- }
38
- else {
39
- throw new Error('An annotation needs either a selector or a region.');
40
- }
41
- }
42
- for (const element of elements) {
43
- if (element.matchCount > 1) {
44
- warnings.push(`Selector "${element.selector}" matched ${element.matchCount} elements; annotated the first.`);
45
- }
46
- if (mode === 'viewport' && !element.inViewport) {
47
- warnings.push(`Element "${element.selector}" is outside the viewport; its box will be clipped.`);
48
- }
49
- }
50
- const screenshot = await page.screenshot({
51
- fullPage: fullPageCapture,
52
- animations: 'disabled',
53
- caret: 'hide',
54
- type: 'png',
55
- });
56
- const targets = elements.map((element, i) => ({
57
- viewportRect: element.viewportRect,
58
- documentRect: element.documentRect,
59
- isFixed: element.isFixed,
60
- label: annotations[i]?.label,
61
- shape: annotations[i]?.shape,
62
- style: annotations[i]?.style,
63
- describe: `Element "${element.selector}"`,
64
- }));
65
- const result = await annotateImage(screenshot, targets, {
66
- metrics,
67
- capture: fullPageCapture ? 'fullPage' : 'viewport',
68
- crop: mode === 'element',
69
- cropPadding: options.cropPadding,
70
- style: options.style,
71
- });
72
- return {
73
- image: result.image,
74
- rawImage: result.rawImage,
75
- width: result.width,
76
- height: result.height,
77
- metrics,
78
- elements,
79
- drawnRects: result.drawnRects,
80
- warnings: [...warnings, ...result.warnings],
81
- };
82
- }
@@ -1,158 +0,0 @@
1
- // This file is read as text and evaluated inside the page - it is never
2
- // imported or bundled. Keeping it out of the TypeScript build is deliberate:
3
- // esbuild's keepNames transform injects a `__name` helper into any function it
4
- // compiles, and that helper does not exist in the browser, so a serialized
5
- // TypeScript function throws `__name is not defined` on evaluation.
6
- //
7
- // The whole file is therefore a single arrow-function expression.
8
- //
9
- // Tags every candidate element with a ref attribute and returns a description
10
- // of it. Tagging rather than deriving a selector afterwards is deliberate: a
11
- // selector we injected always resolves, whereas a path built from classes can
12
- // be invalidated by anything that re-renders between measuring and annotating.
13
-
14
- (function (options) {
15
- var prefix = options.prefix;
16
- var refAttr = options.refAttr;
17
- var minSize = options.minSize;
18
- var viewportOnly = options.viewportOnly;
19
-
20
- var INTERACTIVE = ['a', 'button', 'input', 'select', 'textarea', 'label', 'summary', 'option'];
21
- var STRUCTURAL = ['header', 'nav', 'main', 'footer', 'aside', 'form', 'table', 'img', 'svg', 'video', 'dialog'];
22
- var HEADING = /^h[1-6]$/;
23
- var testAttrs = ['data-testid', 'data-test-id', 'data-test', 'data-cy', 'data-qa'];
24
-
25
- function readableSelector(el) {
26
- // Prefer whatever a developer would actually paste into devtools.
27
- var id = el.getAttribute('id');
28
- if (id && /^[A-Za-z][\w-]*$/.test(id) && el.ownerDocument.querySelectorAll('#' + id).length === 1) {
29
- return '#' + id;
30
- }
31
-
32
- for (var i = 0; i < testAttrs.length; i++) {
33
- var value = el.getAttribute(testAttrs[i]);
34
- if (value) {
35
- var candidate = '[' + testAttrs[i] + '="' + value + '"]';
36
- if (el.ownerDocument.querySelectorAll(candidate).length === 1) return candidate;
37
- }
38
- }
39
-
40
- var parts = [];
41
- var node = el;
42
- for (var depth = 0; node && depth < 4; depth++) {
43
- var tag = node.tagName.toLowerCase();
44
- if (tag === 'body' || tag === 'html') break;
45
-
46
- var nodeId = node.getAttribute('id');
47
- if (nodeId && /^[A-Za-z][\w-]*$/.test(nodeId)) {
48
- parts.unshift('#' + nodeId);
49
- break;
50
- }
51
-
52
- var parent = node.parentElement;
53
- var part = tag;
54
- if (parent) {
55
- var siblings = [];
56
- for (var c = 0; c < parent.children.length; c++) {
57
- if (parent.children[c].tagName === node.tagName) siblings.push(parent.children[c]);
58
- }
59
- if (siblings.length > 1) part += ':nth-of-type(' + (siblings.indexOf(node) + 1) + ')';
60
- }
61
- parts.unshift(part);
62
-
63
- var joined = parts.join(' > ');
64
- try {
65
- if (el.ownerDocument.querySelectorAll(joined).length === 1) return joined;
66
- } catch (e) {
67
- // An unusual tag name can produce an invalid selector; keep walking.
68
- }
69
- node = parent;
70
- }
71
- return parts.join(' > ') || el.tagName.toLowerCase();
72
- }
73
-
74
- function accessibleName(el) {
75
- var aria = el.getAttribute('aria-label');
76
- if (aria) return aria.trim();
77
- var alt = el.getAttribute('alt');
78
- if (alt) return alt.trim();
79
- var placeholder = el.getAttribute('placeholder');
80
- if (placeholder) return 'placeholder: ' + placeholder.trim();
81
- if (el.tagName === 'INPUT' && typeof el.value === 'string' && el.value) {
82
- return 'value: ' + el.value.trim();
83
- }
84
- return (el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 80);
85
- }
86
-
87
- // An element a developer deliberately named is worth listing even when it is
88
- // just a wrapper - a misaligned or overflowing container is exactly the kind
89
- // of target whose children, not itself, carry the text.
90
- function hasStableName(el) {
91
- if (el.hasAttribute('id')) return true;
92
- for (var i = 0; i < testAttrs.length; i++) {
93
- if (el.hasAttribute(testAttrs[i])) return true;
94
- }
95
- return false;
96
- }
97
-
98
- // Text-bearing leaf: has its own text but no child element that also has text.
99
- function isTextLeaf(el) {
100
- if (!(el.textContent || '').trim()) return false;
101
- for (var i = 0; i < el.children.length; i++) {
102
- if ((el.children[i].textContent || '').trim()) return false;
103
- }
104
- return true;
105
- }
106
-
107
- // Clear handles left by an earlier pass. Counters restart at 1 each time, so
108
- // without this a stale e5 from a previous scroll position still matches
109
- // [data-annot-ref="e5"] and the annotation can land on the wrong element.
110
- var stale = document.querySelectorAll('[' + refAttr + ']');
111
- for (var s = 0; s < stale.length; s++) stale[s].removeAttribute(refAttr);
112
-
113
- var results = [];
114
- var counter = 0;
115
- var all = document.querySelectorAll('*');
116
-
117
- for (var i = 0; i < all.length; i++) {
118
- var el = all[i];
119
- var tag = el.tagName.toLowerCase();
120
- if (tag === 'script' || tag === 'style' || tag === 'meta' || tag === 'link') continue;
121
-
122
- var style = getComputedStyle(el);
123
- if (style.visibility === 'hidden' || style.display === 'none') continue;
124
- if (parseFloat(style.opacity) < 0.05) continue;
125
-
126
- var rect = el.getBoundingClientRect();
127
- if (rect.width < minSize || rect.height < minSize) continue;
128
-
129
- var intersects =
130
- rect.bottom > 0 && rect.right > 0 &&
131
- rect.top < window.innerHeight && rect.left < window.innerWidth;
132
- if (viewportOnly && !intersects) continue;
133
-
134
- var interesting =
135
- INTERACTIVE.indexOf(tag) !== -1 ||
136
- STRUCTURAL.indexOf(tag) !== -1 ||
137
- HEADING.test(tag) ||
138
- el.hasAttribute('role') ||
139
- hasStableName(el) ||
140
- isTextLeaf(el);
141
- if (!interesting) continue;
142
-
143
- var ref = prefix + ++counter;
144
- el.setAttribute(refAttr, ref);
145
-
146
- results.push({
147
- ref: ref,
148
- reportSelector: readableSelector(el),
149
- tag: tag,
150
- role: el.getAttribute('role'),
151
- name: accessibleName(el),
152
- rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
153
- inViewport: intersects,
154
- });
155
- }
156
-
157
- return results;
158
- })
@@ -1,69 +0,0 @@
1
- // Paste this into whichever browser MCP is live, as the evaluate function:
2
- //
3
- // Playwright MCP browser_evaluate({ function: "<this>", filename: "measure.json" })
4
- // Chrome DevTools evaluate_script({ pageId, function: "<this>", filePath: "measure.json" })
5
- //
6
- // Edit the SELECTORS line, and nothing else. The result is the exact JSON that
7
- // `annotate-shot --measurement` expects.
8
- //
9
- // It deliberately does not scroll, click, or change anything: every rectangle it
10
- // returns is only valid for the scroll position the page is in right now, so
11
- // the screenshot must be taken immediately after this runs, with no navigation
12
- // in between.
13
-
14
- () => {
15
- const SELECTORS = ['#place-order'];
16
-
17
- const doc = document.documentElement;
18
- const body = document.body;
19
-
20
- const metrics = {
21
- devicePixelRatio: window.devicePixelRatio,
22
- scrollX: window.scrollX,
23
- scrollY: window.scrollY,
24
- // innerWidth/Height rather than documentElement.clientWidth/Height: on a
25
- // page with no doctype (quirks mode) the root element reports the content
26
- // size, not the viewport.
27
- viewportWidth: window.innerWidth,
28
- viewportHeight: window.innerHeight,
29
- documentWidth: Math.max(doc.scrollWidth, body ? body.scrollWidth : 0),
30
- documentHeight: Math.max(doc.scrollHeight, body ? body.scrollHeight : 0),
31
- };
32
-
33
- const targets = SELECTORS.map((selector) => {
34
- let matches;
35
- try {
36
- matches = document.querySelectorAll(selector);
37
- } catch (e) {
38
- return { selector, found: false, error: 'invalid selector: ' + e.message };
39
- }
40
- if (matches.length === 0) return { selector, found: false, error: 'no element matched' };
41
-
42
- const el = matches[0];
43
- const r = el.getBoundingClientRect();
44
-
45
- // An element inside a fixed subtree does not move with document scroll, so
46
- // it has no meaningful document-space position.
47
- let isFixed = false;
48
- for (let node = el; node; node = node.parentElement) {
49
- if (getComputedStyle(node).position === 'fixed') {
50
- isFixed = true;
51
- break;
52
- }
53
- }
54
-
55
- return {
56
- selector,
57
- found: true,
58
- matchCount: matches.length,
59
- tag: el.tagName.toLowerCase(),
60
- text: (el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 80),
61
- isFixed,
62
- rect: { x: r.x, y: r.y, width: r.width, height: r.height },
63
- inViewport:
64
- r.bottom > 0 && r.right > 0 && r.top < window.innerHeight && r.left < window.innerWidth,
65
- };
66
- });
67
-
68
- return { metrics, targets };
69
- }
@@ -1,17 +0,0 @@
1
- import Anthropic from '@anthropic-ai/sdk';
2
- import type { BugFinding, Reasoner, ReasonerInput } from './finder.js';
3
- export interface ClaudeReasonerOptions {
4
- model?: string;
5
- maxTokens?: number;
6
- effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
7
- client?: Anthropic;
8
- }
9
- export declare class ClaudeReasoner implements Reasoner {
10
- private readonly client;
11
- private readonly model;
12
- private readonly maxTokens;
13
- private readonly effort;
14
- constructor(options?: ClaudeReasonerOptions);
15
- propose(input: ReasonerInput): Promise<BugFinding[]>;
16
- }
17
- //# sourceMappingURL=claude-reasoner.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"claude-reasoner.d.ts","sourceRoot":"","sources":["../src/claude-reasoner.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,aAAa,EAAY,MAAM,aAAa,CAAC;AA2FjF,MAAM,WAAW,qBAAqB;IACpC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;IACrD,MAAM,CAAC,EAAE,SAAS,CAAC;CACpB;AAED,qBAAa,cAAe,YAAW,QAAQ;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA8C;gBAEzD,OAAO,GAAE,qBAA0B;IAOzC,OAAO,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;CAkE3D"}
@@ -1,192 +0,0 @@
1
- import Anthropic from '@anthropic-ai/sdk';
2
- import { renderInventory } from './inventory.js';
3
- /**
4
- * Split out from finder.ts on purpose: this is the only file in the package
5
- * with a real (non-type-only) import of `@anthropic-ai/sdk`. finder.ts's other
6
- * exports (findingsToAnnotations, gatherReasonerInput, ReplayReasoner, ...) do
7
- * not need the SDK at all, and index.ts re-exports them from its root barrel -
8
- * if ClaudeReasoner lived in the same file, importing anything from that
9
- * barrel would eagerly load the SDK too, since ES module imports evaluate the
10
- * whole file regardless of which export you asked for. Caught by actually
11
- * installing the built package into a scratch project and importing it with
12
- * no SDK present, not by inspection.
13
- */
14
- const SEVERITIES = ['blocker', 'major', 'minor', 'cosmetic'];
15
- const FINDING_SCHEMA = {
16
- type: 'object',
17
- properties: {
18
- findings: {
19
- type: 'array',
20
- description: 'Every visual or functional defect found. Empty if the page looks correct.',
21
- items: {
22
- type: 'object',
23
- properties: {
24
- description: {
25
- type: 'string',
26
- description: 'What is wrong, in one sentence a developer could act on.',
27
- },
28
- evidence: {
29
- type: 'string',
30
- description: 'What in the screenshot or element list shows this is a defect.',
31
- },
32
- severity: { type: 'string', enum: SEVERITIES },
33
- ref: {
34
- type: ['string', 'null'],
35
- description: 'The handle of the single element the annotation should point at, e.g. "e12". ' +
36
- 'Null only if no listed element corresponds to the problem.',
37
- },
38
- region: {
39
- type: ['object', 'null'],
40
- description: 'Fallback used only when ref is null: the area of the viewport to box, in percentages.',
41
- properties: {
42
- xPct: { type: 'number' },
43
- yPct: { type: 'number' },
44
- widthPct: { type: 'number' },
45
- heightPct: { type: 'number' },
46
- },
47
- required: ['xPct', 'yPct', 'widthPct', 'heightPct'],
48
- additionalProperties: false,
49
- },
50
- },
51
- required: ['description', 'evidence', 'severity', 'ref', 'region'],
52
- additionalProperties: false,
53
- },
54
- },
55
- },
56
- required: ['findings'],
57
- additionalProperties: false,
58
- };
59
- const SYSTEM_PROMPT = `You are doing exploratory visual testing of a web page.
60
-
61
- You get a screenshot and a list of the page's elements. Every element has a handle
62
- like [e12], its tag, its accessible name, and its bounding box in CSS pixels
63
- (x,y width x height) relative to the viewport.
64
-
65
- Report defects a developer would accept as real bugs: overlapping or clipped
66
- content, misalignment, text overflowing its container, invisible or unreadable
67
- text, controls positioned off-screen or outside their container, broken images,
68
- inconsistent spacing that breaks an otherwise regular rhythm, and anything that
69
- contradicts the ticket.
70
-
71
- Do not report subjective styling preferences, and do not invent defects. If the
72
- page looks correct, return an empty findings array.
73
-
74
- For each finding, set "ref" to the handle of the single element the annotation
75
- should point at - the element that is wrong, not its container, and not the
76
- element it collides with. The bounding boxes in the element list are the best
77
- evidence for geometric bugs: overlapping boxes, boxes extending past a parent,
78
- and boxes with a zero or negative gap are all visible in the numbers.
79
-
80
- Only set "ref" to null when no listed element corresponds to the problem - for
81
- example whitespace where something should be. In that case fill in "region"
82
- with the area to box, as percentages of the viewport.
83
-
84
- Always call the report_findings tool exactly once, even when you find nothing.`;
85
- export class ClaudeReasoner {
86
- client;
87
- model;
88
- maxTokens;
89
- effort;
90
- constructor(options = {}) {
91
- this.client = options.client ?? new Anthropic();
92
- this.model = options.model ?? 'claude-opus-5';
93
- this.maxTokens = options.maxTokens ?? 16000;
94
- this.effort = options.effort ?? 'high';
95
- }
96
- async propose(input) {
97
- const stream = this.client.messages.stream({
98
- model: this.model,
99
- max_tokens: this.maxTokens,
100
- system: SYSTEM_PROMPT,
101
- thinking: { type: 'adaptive' },
102
- output_config: { effort: this.effort },
103
- tools: [
104
- {
105
- name: 'report_findings',
106
- description: 'Report every defect found on the page.',
107
- input_schema: FINDING_SCHEMA,
108
- strict: true,
109
- },
110
- ],
111
- messages: [
112
- {
113
- role: 'user',
114
- content: [
115
- {
116
- type: 'image',
117
- source: {
118
- type: 'base64',
119
- media_type: 'image/png',
120
- data: input.screenshotPng.toString('base64'),
121
- },
122
- },
123
- {
124
- type: 'text',
125
- text: `URL: ${input.url}\n\n` +
126
- `${describeIntent(input.ticket)}\n\n` +
127
- `Elements on the page:\n${renderInventory(input.inventory)}`,
128
- },
129
- ],
130
- },
131
- ],
132
- });
133
- const message = await stream.finalMessage();
134
- if (message.stop_reason === 'refusal') {
135
- throw new Error(`Model declined the request (${message.stop_details?.category ?? 'unknown'}).`);
136
- }
137
- const call = message.content.find((block) => block.type === 'tool_use' && block.name === 'report_findings');
138
- if (!call) {
139
- const text = message.content
140
- .filter((b) => b.type === 'text')
141
- .map((b) => b.text)
142
- .join(' ');
143
- throw new Error(`Model did not call report_findings (stop_reason: ${message.stop_reason}). Said: ${text.slice(0, 300)}`);
144
- }
145
- // Tool inputs are already parsed objects, but escaping varies by model, so
146
- // never string-match on them.
147
- const parsed = call.input;
148
- return normaliseFindings(parsed.findings);
149
- }
150
- }
151
- /**
152
- * With no ticket there is nothing to contradict, so the model is told to judge
153
- * the page on its own terms rather than being handed an empty requirement it
154
- * might try to reason against.
155
- */
156
- function describeIntent(ticket) {
157
- const trimmed = ticket.trim();
158
- return trimmed
159
- ? `Ticket / what this page is supposed to do:\n${trimmed}`
160
- : 'No ticket was supplied. Judge the page on its own terms: report anything that ' +
161
- 'looks broken, misaligned, unreadable, clipped, or otherwise unintentional.';
162
- }
163
- function normaliseFindings(raw) {
164
- if (!Array.isArray(raw))
165
- return [];
166
- const findings = [];
167
- for (const entry of raw) {
168
- if (typeof entry !== 'object' || entry === null)
169
- continue;
170
- const record = entry;
171
- const severity = SEVERITIES.includes(record.severity)
172
- ? record.severity
173
- : 'minor';
174
- findings.push({
175
- description: String(record.description ?? '').trim(),
176
- evidence: String(record.evidence ?? '').trim(),
177
- severity,
178
- ref: typeof record.ref === 'string' && record.ref ? record.ref : null,
179
- region: isRegion(record.region) ? record.region : null,
180
- });
181
- }
182
- return findings.filter((f) => f.description.length > 0);
183
- }
184
- function isRegion(value) {
185
- if (typeof value !== 'object' || value === null)
186
- return false;
187
- const r = value;
188
- return (typeof r.xPct === 'number' &&
189
- typeof r.yPct === 'number' &&
190
- typeof r.widthPct === 'number' &&
191
- typeof r.heightPct === 'number');
192
- }
package/dist/cli.d.ts DELETED
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
3
- //# sourceMappingURL=cli.d.ts.map
package/dist/cli.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js DELETED
@@ -1,84 +0,0 @@
1
- #!/usr/bin/env node
2
- import { writeFile } from 'node:fs/promises';
3
- import { parseArgs } from 'node:util';
4
- import { captureAnnotated } from './index.js';
5
- const USAGE = `
6
- Usage: cypress-annotate --url <url> --selector <css> [options]
7
-
8
- --url <url> Page to open (http(s):// or file://).
9
- --selector <css> Element to annotate. Repeatable.
10
- Use ">>>" to pierce iframes: "iframe#pay >>> .btn".
11
- --label <text> Label for the matching --selector. Repeatable.
12
- --out <path> Output PNG. Default: annotated.png
13
- --mode <m> viewport | fullPage | element. Default: viewport
14
- --shape <s> box | circle | arrow. Default: box
15
- --color <css> Outline colour. Default: #FF3B30
16
- --dim <0..1> Darken everything outside the annotation. Default: 0
17
- --width <px> Viewport width, CSS px. Default: 1280
18
- --height <px> Viewport height, CSS px. Default: 800
19
- --dpr <n> Device scale factor. Default: 2
20
- --crop-padding <px> Context to keep around the element in 'element' mode.
21
- --json Print the measurement report as JSON.
22
- `.trim();
23
- const { values } = parseArgs({
24
- options: {
25
- url: { type: 'string' },
26
- selector: { type: 'string', multiple: true, default: [] },
27
- label: { type: 'string', multiple: true, default: [] },
28
- out: { type: 'string', default: 'annotated.png' },
29
- mode: { type: 'string', default: 'viewport' },
30
- shape: { type: 'string', default: 'box' },
31
- color: { type: 'string' },
32
- dim: { type: 'string' },
33
- width: { type: 'string', default: '1280' },
34
- height: { type: 'string', default: '800' },
35
- dpr: { type: 'string', default: '2' },
36
- 'crop-padding': { type: 'string' },
37
- json: { type: 'boolean', default: false },
38
- help: { type: 'boolean', default: false },
39
- },
40
- allowPositionals: false,
41
- });
42
- if (values.help || !values.url || values.selector.length === 0) {
43
- console.log(USAGE);
44
- process.exit(values.help ? 0 : 1);
45
- }
46
- const annotations = values.selector.map((selector, i) => ({
47
- selector: selector.includes('>>>') ? selector.split('>>>').map((s) => s.trim()) : selector,
48
- label: values.label[i],
49
- shape: values.shape,
50
- }));
51
- /**
52
- * A CLI should print what went wrong and nothing else. Without this, a missing
53
- * playwright surfaces as an unhandled rejection: the useful sentence buried in
54
- * a Node module-loader stack, plus the whole `cause` chain printed underneath.
55
- */
56
- function fail(error) {
57
- console.error(error instanceof Error ? error.message : String(error));
58
- process.exit(1);
59
- }
60
- const result = await captureAnnotated(values.url, annotations, {
61
- mode: values.mode,
62
- viewport: { width: Number(values.width), height: Number(values.height) },
63
- deviceScaleFactor: Number(values.dpr),
64
- cropPadding: values['crop-padding'] ? Number(values['crop-padding']) : undefined,
65
- style: {
66
- ...(values.color ? { color: values.color } : {}),
67
- ...(values.dim ? { dimOutside: Number(values.dim) } : {}),
68
- },
69
- }).catch(fail);
70
- await writeFile(values.out, result.image).catch(fail);
71
- if (values.json) {
72
- console.log(JSON.stringify({ out: values.out, width: result.width, height: result.height, metrics: result.metrics, elements: result.elements, drawnRects: result.drawnRects, warnings: result.warnings }, null, 2));
73
- }
74
- else {
75
- console.log(`Wrote ${values.out} (${result.width}x${result.height})`);
76
- for (const element of result.elements) {
77
- const r = result.drawnRects[result.elements.indexOf(element)];
78
- console.log(` ${element.selector} -> <${element.tagName}> ` +
79
- `css ${element.viewportRect.width.toFixed(0)}x${element.viewportRect.height.toFixed(0)} ` +
80
- `@ image ${r ? `${r.x.toFixed(0)},${r.y.toFixed(0)}` : '?'}`);
81
- }
82
- for (const warning of result.warnings)
83
- console.log(` ! ${warning}`);
84
- }
@@ -1,45 +0,0 @@
1
- import Anthropic from '@anthropic-ai/sdk';
2
- import type { FailureRecord } from './failure-report.js';
3
- /**
4
- * Claude fallback for the failures registerFailureCapture could not resolve
5
- * deterministically - no selector recovered, or the recovered selector matched
6
- * nothing live. Deliberately a separate, narrower task from finder.ts's
7
- * open-ended bug hunting: the failure is already known (err.message says so);
8
- * the only open question is *where on screen it shows up*, from a fixed list
9
- * of candidate elements captured live at failure time. That's a smaller,
10
- * cheaper, more constrained ask than "find bugs on this page".
11
- */
12
- export interface FailureExplanation {
13
- /** One of the inventory selectors from the record, or null if none fit. */
14
- selector: string | null;
15
- label: string;
16
- /** Fallback region (percent of viewport) when no inventory item fits. */
17
- region: {
18
- xPct: number;
19
- yPct: number;
20
- widthPct: number;
21
- heightPct: number;
22
- } | null;
23
- }
24
- export interface FailureExplainer {
25
- explain(record: FailureRecord): Promise<FailureExplanation>;
26
- }
27
- export interface ClaudeFailureExplainerOptions {
28
- model?: string;
29
- effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
30
- client?: Anthropic;
31
- }
32
- export declare class ClaudeFailureExplainer implements FailureExplainer {
33
- private readonly client;
34
- private readonly model;
35
- private readonly effort;
36
- constructor(options?: ClaudeFailureExplainerOptions);
37
- explain(record: FailureRecord): Promise<FailureExplanation>;
38
- }
39
- /** For tests and offline runs - no API call. */
40
- export declare class ReplayFailureExplainer implements FailureExplainer {
41
- private readonly explanation;
42
- constructor(explanation: FailureExplanation);
43
- explain(): Promise<FailureExplanation>;
44
- }
45
- //# sourceMappingURL=failure-explainer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"failure-explainer.d.ts","sourceRoot":"","sources":["../../src/cypress/failure-explainer.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;;;;;;;GAQG;AAEH,MAAM,WAAW,kBAAkB;IACjC,2EAA2E;IAC3E,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,yEAAyE;IACzE,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CACpF;AAED,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;CAC7D;AA6DD,MAAM,WAAW,6BAA6B;IAC5C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;IACrD,MAAM,CAAC,EAAE,SAAS,CAAC;CACpB;AAED,qBAAa,sBAAuB,YAAW,gBAAgB;IAC7D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA8C;gBAEzD,OAAO,GAAE,6BAAkC;IAMjD,OAAO,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAoDlE;AAED,gDAAgD;AAChD,qBAAa,sBAAuB,YAAW,gBAAgB;IACjD,OAAO,CAAC,QAAQ,CAAC,WAAW;gBAAX,WAAW,EAAE,kBAAkB;IACtD,OAAO,IAAI,OAAO,CAAC,kBAAkB,CAAC;CAG7C"}