@commmerce/review 1.21.3 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/api.mjs DELETED
@@ -1,91 +0,0 @@
1
- // Client for the Commmerce review service (API v1). The key comes from COMMMERCE_REVIEW_KEY; keys are issued by
2
- // Commmerce by email: `commmerce-review key request` (or ask your agent: request_key).
3
-
4
- export const FEEDBACK_FORM = 'https://commmerce.com/commmerceui/#apps--feedback';
5
- export const DEFAULT_BASE = 'https://commmerce.com/commmerceui/api/v1';
6
- export const KEY_HELP = 'Set COMMMERCE_REVIEW_KEY to your review key. Get one by email: npx @commmerce/review key request --email you@company.com --name "Your name" --team "Your team"';
7
-
8
- export class ApiError extends Error {
9
- /** @param {number} status @param {string} code @param {string} message */
10
- constructor(status, code, message) { super(message); this.status = status; this.code = code; }
11
- }
12
-
13
- /** @param {{ key?: string, base?: string, fetch?: typeof fetch }} [opts] */
14
- export function createClient(opts = {}) {
15
- const key = opts.key ?? process.env.COMMMERCE_REVIEW_KEY;
16
- const base = (opts.base ?? process.env.COMMMERCE_REVIEW_URL ?? DEFAULT_BASE).replace(/\/+$/, '');
17
- const f = opts.fetch ?? fetch;
18
-
19
- /** @param {string} method @param {string} path @param {unknown} [body] @returns {Promise<any>} */
20
- async function call(method, path, body) {
21
- if (!key) throw new ApiError(0, 'no_key', KEY_HELP);
22
- let res;
23
- try {
24
- res = await f(base + path, {
25
- method,
26
- headers: { authorization: `Bearer ${key}`, accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
27
- body: body === undefined ? undefined : JSON.stringify(body),
28
- });
29
- } catch (e) {
30
- throw new ApiError(0, 'network', `Could not reach ${base}: ${e instanceof Error ? e.message : e}`);
31
- }
32
- const text = await res.text();
33
- let data = null;
34
- try { data = text ? JSON.parse(text) : null; } catch { /* not JSON */ }
35
- if (!res.ok) {
36
- const msg = data?.error?.message ?? `HTTP ${res.status}`;
37
- throw new ApiError(res.status, data?.error?.code ?? 'http', res.status === 401 ? `${msg} ${KEY_HELP}` : msg);
38
- }
39
- return data;
40
- }
41
-
42
- return {
43
- base,
44
- hasKey: !!key,
45
- /** @param {object} body */
46
- submitReview: (body) => call('POST', '/reviews', body),
47
- /** @param {string} id */
48
- getItem: (id) => call('GET', `/reviews/${encodeURIComponent(id)}`),
49
- listItems: () => call('GET', '/reviews'),
50
- /** @param {{name: string, need: string, app: string, example?: string}} body */
51
- requestComponent: (body) => call('POST', '/component-requests', body),
52
- /** @param {{kind: string, title: string, body: string, app?: string, images?: string[]}} body */
53
- sendFeedback: (body) => call('POST', '/feedback', body),
54
- /**
55
- * Asks Commmerce to email a key (no key needed). Goes through the remote MCP endpoint's request_key tool, which has
56
- * the same rules and limits as the form. The answer never contains the key.
57
- * @param {{email: string, name: string, team: string, kind?: string}} args
58
- */
59
- async requestKey(args) {
60
- const mcpUrl = base.replace(/\/v1$/, '/mcp');
61
- let res;
62
- try {
63
- res = await f(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'request_key', arguments: args } }) });
64
- } catch (e) { throw new ApiError(0, 'network', `Could not reach ${mcpUrl}: ${e instanceof Error ? e.message : e}`); }
65
- const data = await res.json().catch(() => null);
66
- const result = data?.result;
67
- if (!res.ok || !result) throw new ApiError(res.status, 'http', data?.error?.message ?? `HTTP ${res.status}`);
68
- if (result.isError) throw new ApiError(400, 'invalid', result.content?.[0]?.text ?? 'Request refused');
69
- return JSON.parse(result.content[0].text);
70
- },
71
- };
72
- }
73
-
74
- const FINAL = ['done', 'failed'];
75
- /**
76
- * Polls an item until it is done/failed (or needs-owner, which can take days), or the timeout passes.
77
- * @param {ReturnType<typeof createClient>} client @param {string} id
78
- * @param {{ timeoutS?: number, onPoll?: (item: any) => void, sleep?: (ms: number) => Promise<void>, untilNeedsOwner?: boolean }} [opts]
79
- */
80
- export async function waitFor(client, id, opts = {}) {
81
- const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
82
- const deadline = Date.now() + (opts.timeoutS ?? 1800) * 1000;
83
- for (;;) {
84
- const item = await client.getItem(id);
85
- opts.onPoll?.(item);
86
- if (FINAL.includes(item.status) || (item.status === 'needs-owner' && opts.untilNeedsOwner !== false)) return { item, timedOut: false };
87
- const wait = Math.min(Math.max(item.poll_after_s ?? 60, 5), 300) * 1000;
88
- if (Date.now() + wait > deadline) return { item, timedOut: true };
89
- await sleep(wait);
90
- }
91
- }
package/lib/browser.mjs DELETED
@@ -1,37 +0,0 @@
1
- // Playwright is an optional peer dependency: found next to this package, or in the project the command runs in.
2
- import { createRequire } from 'node:module';
3
- import { join } from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
-
6
- export const PLAYWRIGHT_HELP = 'This needs Playwright and Chromium. In your project run:\n npm install --save-dev playwright\n npx playwright install chromium';
7
-
8
- export class SetupError extends Error {}
9
-
10
- export async function loadPlaywright() {
11
- try { return await import('playwright'); } catch { /* not next to this package */ }
12
- try {
13
- const path = createRequire(join(process.cwd(), 'package.json')).resolve('playwright');
14
- return await import(pathToFileURL(path).href);
15
- } catch { /* not in the project either */ }
16
- throw new SetupError(`Playwright is not installed. ${PLAYWRIGHT_HELP}`);
17
- }
18
-
19
- /** @returns {Promise<import('playwright').Browser>} */
20
- export async function launchChromium() {
21
- const pw = await loadPlaywright();
22
- try {
23
- return await pw.chromium.launch(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {});
24
- } catch (e) {
25
- const msg = e instanceof Error ? e.message : String(e);
26
- if (/Executable doesn't exist|playwright install/i.test(msg)) throw new SetupError(`Chromium for Playwright is not installed. Run: npx playwright install chromium`);
27
- throw e;
28
- }
29
- }
30
-
31
- /** Load a page and let it settle (network quiet, custom elements upgraded, two frames). @param {import('playwright').Page} page @param {string} url */
32
- export async function open(page, url) {
33
- const res = await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
34
- await page.waitForLoadState('networkidle', { timeout: 10_000 }).catch(() => {});
35
- await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(r, 150)))));
36
- return res;
37
- }
package/lib/check.mjs DELETED
@@ -1,205 +0,0 @@
1
- // `commmerce-review check <url>`: deterministic checks of a running page, no AI, nothing leaves the machine.
2
- // The same rules as the docs site's own checks (scripts/check-responsive.mjs, scripts/a11y-audit.mjs):
3
- // - Commmerce UI present, which version, cm-* tags used but never defined
4
- // - axe-core, WCAG 2.0/2.1/2.2 A and AA (at 390 and 1280px)
5
- // - sideways scroll at 320, 390, 768 and 1280px
6
- // - text under 12px, targets under 24x24px (inline links in sentences exempt, WCAG 2.5.8)
7
- // - native buttons, inputs, selects... where a cm-* component exists
8
- // Severity: blocker (fails CI) | major | minor.
9
- import { readFileSync } from 'node:fs';
10
- import { createRequire } from 'node:module';
11
- import { launchChromium, open } from './browser.mjs';
12
- import { components, UI_VERSION } from './components.mjs';
13
- import { docsUrl } from './components-index.mjs';
14
-
15
- export const WIDTHS = [320, 390, 768, 1280];
16
- const AXE_WIDTHS = [390, 1280];
17
- const AXE_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'];
18
- const IMPACT = { critical: 'blocker', serious: 'blocker', moderate: 'major', minor: 'minor' };
19
- // Native element -> the Commmerce UI component to use instead (only suggested when that component exists).
20
- const NATIVE = [
21
- ['button, input[type=button], input[type=submit], input[type=reset]', 'cm-button'],
22
- ['input[type=checkbox]', 'cm-checkbox'],
23
- ['input[type=radio]', 'cm-radio-group'],
24
- ['input[type=search]', 'cm-search'],
25
- ['input[type=date]', 'cm-date-picker'],
26
- ['input[type=time]', 'cm-time-picker'],
27
- ['input[type=color]', 'cm-color-field'],
28
- ['input[type=file]', 'cm-file-upload'],
29
- ['input:not([type]), input[type=text], input[type=email], input[type=number], input[type=tel], input[type=url], input[type=password], textarea', 'cm-text-field'],
30
- ['select', 'cm-select'],
31
- ['dialog', 'cm-modal'],
32
- ['progress', 'cm-progress-bar'],
33
- ];
34
-
35
- let axeSource = '';
36
- const axe = () => (axeSource ||= readFileSync(createRequire(import.meta.url).resolve('axe-core/axe.min.js'), 'utf8'));
37
-
38
- /**
39
- * Runs in the page. Returns raw observations for one width.
40
- * @param {{ tags: string[], native: [string, string][] }} arg
41
- */
42
- function inspect({ tags, native }) {
43
- const describe = (/** @type {Element} */ el) => {
44
- const part = (/** @type {Element} */ e) => `${e.localName}${e.id ? '#' + e.id : ''}${typeof e.className === 'string' && e.className.trim() ? '.' + e.className.trim().split(/\s+/).slice(0, 2).join('.') : ''}`;
45
- const parts = []; let e = el;
46
- for (let i = 0; e && e !== document.body && i < 3; i++, e = e.parentElement) { parts.unshift(part(e)); if (e.id) break; }
47
- return parts.join(' > ');
48
- };
49
- const label = (/** @type {Element} */ el) => (el.getAttribute('aria-label') || el.textContent || /** @type {any} */ (el).value || '').trim().replace(/\s+/g, ' ').slice(0, 40);
50
- const visible = (/** @type {Element} */ el) => {
51
- if (el.closest('[hidden], [inert]')) return false;
52
- const s = getComputedStyle(el);
53
- if (s.display === 'none' || s.visibility === 'hidden' || Number(s.opacity) === 0) return false;
54
- const r = el.getBoundingClientRect();
55
- return r.width > 0 && r.height > 0;
56
- };
57
- const inCm = (/** @type {Element} */ el) => { for (let a = el.parentElement; a; a = a.parentElement) if (a.localName.startsWith('cm-')) return true; return false; };
58
-
59
- // Commmerce UI: which components are defined, which cm-* tags are used, the version from the hosted build's URL.
60
- const defined = tags.filter((t) => customElements.get(t));
61
- const used = [...new Set([...document.querySelectorAll('*')].map((e) => e.localName).filter((n) => n.startsWith('cm-')))];
62
- const urls = [...document.querySelectorAll('script[src], link[href]')].map((e) => e.getAttribute('src') || e.getAttribute('href') || '');
63
- let version = null;
64
- for (const u of urls) {
65
- const m = /commmerceui\/v\/(\d+\.\d+\.\d+[\w.-]*)\//.exec(u) || /@commmerce\/(?:ui|tokens)@(\d+\.\d+\.\d+[\w.-]*)/.exec(u);
66
- if (m) { version = m[1]; break; }
67
- }
68
-
69
- const se = /** @type {Element} */ (document.scrollingElement);
70
- let overflow = null;
71
- if (se.scrollWidth > innerWidth + 1) {
72
- const clipped = (/** @type {Element} */ el) => { for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) if (getComputedStyle(a).overflowX !== 'visible') return true; return false; };
73
- const sticks = (/** @type {Element} */ el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.right > innerWidth + 1 && getComputedStyle(el).position !== 'fixed' && !clipped(el); };
74
- const wide = [...document.querySelectorAll('body *')].filter(sticks).filter((el) => !el.parentElement || !sticks(el.parentElement)).slice(0, 3);
75
- overflow = { scrollWidth: se.scrollWidth, elements: wide.map((el) => ({ element: describe(el), right: Math.round(el.getBoundingClientRect().right) })) };
76
- }
77
-
78
- // Text under 12px (the app's own text; components inside their shadow roots are tested by Commmerce UI).
79
- const small = new Map();
80
- const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
81
- for (let n = walker.nextNode(); n; n = walker.nextNode()) {
82
- const el = n.parentElement;
83
- if (!n.textContent?.trim() || !el || /^(SCRIPT|STYLE|TEMPLATE|NOSCRIPT|OPTION)$/.test(el.tagName)) continue;
84
- const size = parseFloat(getComputedStyle(el).fontSize);
85
- if (size < 12 && visible(el)) { const d = describe(el); if (!small.has(d)) small.set(d, { element: d, size, text: n.textContent.trim().slice(0, 40) }); }
86
- }
87
-
88
- // Targets under 24x24 (WCAG 2.5.8). Inline links inside sentences are exempt.
89
- const tiny = new Map();
90
- for (const el of document.querySelectorAll('button, a[href], input:not([type=hidden]), select, textarea, summary, [role=button], [role=link], [role=tab], [role=checkbox], [role=switch], [tabindex]:not([tabindex="-1"])')) {
91
- if (!visible(el)) continue;
92
- if (el.localName === 'a' && el.closest('p, li, td, dd, small, figcaption, label') && !el.closest('nav')) continue;
93
- if (el.localName === 'input' && /** @type {HTMLInputElement} */ (el).labels?.length && /^(checkbox|radio)$/.test(/** @type {HTMLInputElement} */ (el).type)) {
94
- // A checkbox's label is part of its target.
95
- const lr = /** @type {HTMLInputElement} */ (el).labels?.[0]?.getBoundingClientRect();
96
- if (lr && lr.height >= 24) continue;
97
- }
98
- const r = el.getBoundingClientRect();
99
- if (r.width < 23.5 || r.height < 23.5) { const d = describe(el); if (!tiny.has(d)) tiny.set(d, { element: d, label: label(el), w: Math.round(r.width), h: Math.round(r.height) }); }
100
- }
101
-
102
- // Native controls where a cm-* component exists (not ones placed inside a cm-* element, which may be intended).
103
- const natives = [];
104
- for (const [sel, tag] of native) {
105
- const els = [...document.querySelectorAll(sel)].filter((el) => !inCm(el) && !el.closest('[data-cm-allow-native]') && (el.localName === 'dialog' || visible(el)));
106
- if (els.length) natives.push({ tag, count: els.length, examples: els.slice(0, 3).map((el) => ({ element: describe(el), label: label(el) })) });
107
- }
108
-
109
- return { defined, used, version, overflow, small: [...small.values()].slice(0, 10), tiny: [...tiny.values()].slice(0, 10), natives, title: document.title };
110
- }
111
-
112
- /**
113
- * @param {string} url
114
- * @param {{ widths?: number[], axe?: boolean, browser?: import('playwright').Browser }} [opts]
115
- */
116
- export async function checkPage(url, opts = {}) {
117
- const index = components();
118
- const byTag = new Map(index.map((c) => [c.tag, c]));
119
- const tags = [...index.map((c) => c.tag), ...index.flatMap((c) => c.parts.map((/** @type {any} */ p) => p.tag))];
120
- const native = NATIVE.filter(([, tag]) => byTag.has(tag));
121
- const widths = opts.widths ?? WIDTHS;
122
- const browser = opts.browser ?? await launchChromium();
123
- /** @type {any[]} */
124
- const findings = [];
125
- let n = 0;
126
- const add = (/** @type {any} */ f) => findings.push({ id: `c${++n}`, ...f, ...(f.component && byTag.has(f.component) ? { docs_url: docsUrl(byTag.get(f.component).slug) } : {}) });
127
- /** @type {any} */
128
- let ui = null;
129
- const seen = new Set();
130
- try {
131
- for (const width of widths) {
132
- const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce' });
133
- const page = await ctx.newPage();
134
- /** @type {string[]} */
135
- const errors = [];
136
- page.on('pageerror', (e) => errors.push(e.message));
137
- try {
138
- const res = await open(page, url);
139
- if (res && res.status() >= 400) { add({ check: 'load', severity: 'blocker', width, element: 'page', problem: `The page answered HTTP ${res.status()}.`, fix: 'Check the URL and that the app is running.' }); continue; }
140
- } catch (e) {
141
- add({ check: 'load', severity: 'blocker', width, element: 'page', problem: `The page did not load: ${e instanceof Error ? e.message.split('\n')[0] : e}`, fix: 'Check the URL and that the app is running.' });
142
- await ctx.close();
143
- break;
144
- }
145
- const r = await page.evaluate(inspect, { tags, native });
146
- if (!ui) {
147
- ui = { present: r.defined.length > 0, version: r.version, latest: UI_VERSION(), components_defined: r.defined.length, components_used: r.used.filter((t) => byTag.has(t) || tags.includes(t)), title: r.title };
148
- const undef = r.used.filter((t) => !r.defined.includes(t));
149
- for (const t of undef) add({ check: 'commmerce-ui', severity: 'blocker', width, element: t, problem: `<${t}> is used but not defined${tags.includes(t) ? ': Commmerce UI is not loaded, or loaded after the page rendered' : ': no Commmerce UI component has this name'}.`, fix: tags.includes(t) ? 'Load Commmerce UI (cdn.js from the hosted build, or import \'@commmerce/ui\').' : 'Use a component from the docs (search_components).', ...(byTag.has(t) ? { component: t } : {}) });
150
- if (!ui.present) add({ check: 'commmerce-ui', severity: 'major', width, element: 'page', problem: 'Commmerce UI is not on this page: no cm-* component is defined.', fix: 'Build the screen with Commmerce UI components. Install: https://commmerce.com/commmerceui/#start--install' });
151
- else if (ui.version && cmp(ui.version, ui.latest) < 0) add({ check: 'commmerce-ui', severity: 'minor', width, element: 'page', problem: `Commmerce UI ${ui.version} is older than ${ui.latest}.`, fix: `Update to ${ui.latest} (release notes: https://commmerce.com/commmerceui/#releases).` });
152
- }
153
- for (const e of errors.slice(0, 3)) add({ check: 'errors', severity: 'major', width, element: 'page', problem: `JavaScript error: ${e.slice(0, 200)}`, fix: 'Fix the error (see the browser console).' });
154
- if (r.overflow) add({ check: 'sideways-scroll', severity: 'blocker', width, element: r.overflow.elements.map((x) => x.element).join(', ') || 'page', problem: `The page scrolls sideways at ${width}px (content is ${r.overflow.scrollWidth}px wide).`, fix: 'Let the content wrap or stack: use cm-layout / cm-stack / cm-grid, which reflow on narrow screens; let wide tables scroll inside their card.', component: 'cm-layout' });
155
- for (const s of r.small) if (!seen.has(`s${s.element}`)) { seen.add(`s${s.element}`); add({ check: 'small-text', severity: 'major', width, element: s.element, problem: `Text is ${s.size}px ("${s.text}"); nothing in the admin is under 12px.`, fix: 'Use the type scale: body 14px (--cm-font-size-*), supporting text 12px; or a component that sets its own text.' }); }
156
- for (const t of r.tiny) if (!seen.has(`t${t.element}`)) { seen.add(`t${t.element}`); add({ check: 'target-size', severity: 'major', width, element: t.element, problem: `Target "${t.label}" is ${t.w}x${t.h}px, under 24x24 (WCAG 2.5.8).`, fix: 'Use cm-button (36px; icon-only buttons are square) or give the control at least 24x24px.', component: 'cm-button' }); }
157
- for (const nat of r.natives) if (!seen.has(`n${nat.tag}`)) { seen.add(`n${nat.tag}`); add({ check: 'native-control', severity: 'major', width, element: nat.examples.map((x) => x.element + (x.label ? ` "${x.label}"` : '')).join(', '), problem: `${nat.count} native control(s) where Commmerce UI has <${nat.tag}>.`, fix: `Use <${nat.tag}> (see its docs for attributes and slots). If the native element is intended, mark it data-cm-allow-native.`, component: nat.tag }); }
158
- if (opts.axe !== false && AXE_WIDTHS.includes(width)) {
159
- await page.addScriptTag({ content: axe() });
160
- const violations = await page.evaluate(async (tagList) => {
161
- // @ts-ignore axe is injected above
162
- const res = await window.axe.run(document, { runOnly: { type: 'tag', values: tagList }, resultTypes: ['violations'] });
163
- return res.violations.map((/** @type {any} */ v) => ({ rule: v.id, impact: v.impact, help: v.help, url: v.helpUrl, nodes: v.nodes.slice(0, 3).map((/** @type {any} */ x) => x.target.flat().join(' >>> ')), count: v.nodes.length }));
164
- }, AXE_TAGS);
165
- for (const v of violations) {
166
- if (seen.has(`a${v.rule}`)) continue;
167
- seen.add(`a${v.rule}`);
168
- add({ check: 'axe', severity: IMPACT[/** @type {keyof IMPACT} */ (v.impact)] ?? 'major', width, element: v.nodes.join(', '), problem: `${v.help} (axe ${v.rule}, ${v.count} element${v.count === 1 ? '' : 's'}).`, fix: 'Use the cm-* component for this control (they are accessible as shipped) or fix the markup; see the Accessibility foundations: https://commmerce.com/commmerceui/#foundations--accessibility' });
169
- }
170
- }
171
- await ctx.close();
172
- }
173
- } finally {
174
- if (!opts.browser) await browser.close();
175
- }
176
- const counts = { blocker: 0, major: 0, minor: 0 };
177
- for (const f of findings) counts[/** @type {'blocker'|'major'|'minor'} */ (f.severity)]++;
178
- return { url, ok: counts.blocker === 0, ui, widths, counts, findings, tool: `@commmerce/review ${UI_VERSION()}` };
179
- }
180
-
181
- /** @param {string} a @param {string} b */
182
- function cmp(a, b) {
183
- const pa = a.split(/[.-]/).map((x) => (/^\d+$/.test(x) ? Number(x) : x));
184
- const pb = b.split(/[.-]/).map((x) => (/^\d+$/.test(x) ? Number(x) : x));
185
- for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return Number(pa[i]) - Number(pb[i]);
186
- return 0;
187
- }
188
-
189
- /** Readable text report. @param {Awaited<ReturnType<typeof checkPage>>} r */
190
- export function formatCheck(r) {
191
- const lines = [`Commmerce UI check: ${r.url}`];
192
- lines.push(r.ui ? `Commmerce UI: ${r.ui.present ? `yes, ${r.ui.components_defined} components defined, version ${r.ui.version ?? 'unknown (bundled)'}` : 'not found'}; ${r.ui.components_used.length} used on the page` : 'Page did not load.');
193
- lines.push(`Widths: ${r.widths.join(', ')}px`);
194
- for (const sev of ['blocker', 'major', 'minor']) {
195
- const fs = r.findings.filter((f) => f.severity === sev);
196
- if (!fs.length) continue;
197
- lines.push('', `${sev.toUpperCase()} (${fs.length})`);
198
- for (const f of fs) {
199
- lines.push(`- [${f.check} @${f.width}px] ${f.problem}`, ` where: ${f.element}`, ` fix: ${f.fix}`);
200
- if (f.docs_url) lines.push(` docs: ${f.docs_url}`);
201
- }
202
- }
203
- lines.push('', `${r.counts.blocker} blocker(s), ${r.counts.major} major, ${r.counts.minor} minor. ${r.ok ? 'No blockers.' : 'Blockers found.'}`);
204
- return lines.join('\n');
205
- }
package/lib/cli.mjs DELETED
@@ -1,188 +0,0 @@
1
- // commmerce-review: the CLI. Exit codes: 0 ok, 1 blockers / changes needed / failed review, 2 usage or setup error,
2
- // 3 timed out waiting.
3
- import { parseArgs } from 'node:util';
4
- import { readFileSync, writeFileSync } from 'node:fs';
5
- import { createClient, waitFor, KEY_HELP, ApiError } from './api.mjs';
6
- import { checkPage, formatCheck } from './check.mjs';
7
- import { prepareSubmission, DEMO_DATA_RULE } from './submit.mjs';
8
- import { mask } from './shoot.mjs';
9
- import { SetupError } from './browser.mjs';
10
- import { createMcp, serveStdio } from './mcp-protocol.mjs';
11
- import { localTools, INSTRUCTIONS, ANON_INSTRUCTIONS, ANON_TOOLS } from './tools.mjs';
12
-
13
- const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
14
-
15
- export const HELP = `commmerce-review ${VERSION}: review what you build with Commmerce UI, from your coding agent or CI.
16
-
17
- PRIVATE BY DEFAULT: everything you send (here, through the MCP server, or the feedback form) is seen only
18
- by Commmerce and your team, never published. Replies come back only to you: \`commmerce-review status <id>\` / get_review,
19
- or the form's private status link. Screenshots and source are deleted 30 days after a review is done. Send demo data only.
20
- Public GitHub issues are optional, only if you want to report a library bug in public.
21
-
22
- Usage: commmerce-review <command> [options]
23
-
24
- Commands
25
- mcp Run the MCP server on stdio (for Claude Code, Codex and other agents). Without a key it
26
- offers component lookup, check_page and request_key.
27
- check <url> Check a running page locally (no AI, nothing is sent): Commmerce UI present and version,
28
- axe-core, sideways scroll at 320/390/768/1280px, text under 12px, targets under 24px,
29
- native controls where a cm-* component exists. Exits 1 on blockers (use it in CI).
30
- --json JSON output --strict also fail on major findings
31
- --widths 390,1280 widths to check --out <file> also write the JSON report to a file
32
- submit <url> Take screenshots locally at 390, 768 and 1280px and send them for review.
33
- --screen name=/path a screen (path relative to <url>); repeat, up to 4. Default: the url itself.
34
- --images <file...> send image files instead (name@width=path, name=path or path); up to 12.
35
- --app <name> your app or product (required)
36
- --question <text> what to look at; repeat
37
- --source <file> include the screen's markup/code; repeat (200 KB total)
38
- --resubmission-of <id> previous review of the same screens
39
- --yes send even though emails/phone numbers are visible (you confirm they are demo data)
40
- --wait wait for the result (like \`wait\`)
41
- status <id> Show a review, component request or feedback item.
42
- wait <id> Poll until done. Exits 0 approved, 1 changes needed / needs a component / failed,
43
- --timeout <s> 3 timed out (default 1800s). --json for JSON.
44
- key request Get a review key by email (no key needed). Commmerce emails it with the command to add it.
45
- --email <work email> --name <name> --team <team or app> [--kind internal|third-party]
46
- request-component Ask for a component Commmerce UI doesn't have.
47
- --name <n> --need <text> --app <name> [--example <text or @file>]
48
- feedback Report a bug, suggest a refinement or ask a question.
49
- --kind bug|refinement|question --title <t> --body <text or @file> [--app <name>]
50
-
51
- Environment
52
- COMMMERCE_REVIEW_KEY your key (submit, status, wait, request-component, feedback). Get one with
53
- \`commmerce-review key request\`. check and component lookup need no key.
54
- COMMMERCE_REVIEW_URL API base (default https://commmerce.com/commmerceui/api/v1)
55
-
56
- Docs: https://commmerce.com/commmerceui/#apps--review
57
- Feedback form (no key needed): https://commmerce.com/commmerceui/#apps--feedback`;
58
-
59
- /** @param {string | undefined} v */
60
- const fileOrText = (v) => (v?.startsWith('@') ? readFileSync(v.slice(1), 'utf8') : v);
61
- const out = (/** @type {string} */ s) => process.stdout.write(`${s}\n`);
62
- const err = (/** @type {string} */ s) => process.stderr.write(`${s}\n`);
63
-
64
- /** @param {any} item */
65
- function formatItem(item) {
66
- const lines = [`${item.id} (${item.type}${item.app ? `, ${item.app}` : ''}): ${item.status}${item.verdict ? `, ${item.verdict}` : ''}`];
67
- if (item.summary) lines.push('', item.summary);
68
- for (const f of item.findings ?? []) {
69
- lines.push('', `[${f.severity}] ${f.id} ${f.screen} @${f.width}px: ${f.element}`, ` problem: ${f.problem}`, ` fix: ${f.fix}`);
70
- if (f.snippet) lines.push(` snippet:\n${f.snippet.split('\n').map((/** @type {string} */ l) => ` ${l}`).join('\n')}`);
71
- if (f.docs_url) lines.push(` docs: ${f.docs_url}`);
72
- }
73
- if (item.resolved?.length) lines.push('', `Resolved from the previous review: ${item.resolved.join(', ')}`);
74
- if (item.reply) lines.push('', item.reply);
75
- if (item.poll_after_s) lines.push('', `Not finished yet: check again in ${item.poll_after_s}s (commmerce-review wait ${item.id}).`);
76
- return lines.join('\n');
77
- }
78
- /** @param {any} item */
79
- const exitFor = (item) => (item.status === 'done' && item.verdict !== 'changes-needed' && item.verdict !== 'needs-component' ? 0 : 1);
80
-
81
- /** @param {string[]} argv @returns {Promise<number>} */
82
- export async function main(argv) {
83
- const [cmd, ...rest] = argv;
84
- /** @type {(options: any) => { values: any, positionals: string[] }} */
85
- const parse = (options) => parseArgs({ args: rest, options: { json: { type: 'boolean' }, ...options }, allowPositionals: true });
86
- try {
87
- switch (cmd) {
88
- case undefined: case 'help': case '--help': case '-h': out(HELP); return 0;
89
- case '--version': case '-v': case 'version': out(VERSION); return 0;
90
- case 'mcp': {
91
- const client = createClient();
92
- // Without a key: look components up, check pages locally, and request a key.
93
- const tools = localTools(client).filter((t) => client.hasKey || ANON_TOOLS.includes(t.name));
94
- const handle = createMcp({ name: 'commmerce-review', version: VERSION, instructions: client.hasKey ? INSTRUCTIONS : ANON_INSTRUCTIONS, tools });
95
- await serveStdio(handle);
96
- return 0;
97
- }
98
- case 'check': {
99
- const { values: v, positionals: [url] } = parse({ strict: { type: 'boolean' }, widths: { type: 'string' }, out: { type: 'string' } });
100
- if (!url) { err('usage: commmerce-review check <url> [--json] [--strict] [--widths 390,1280]'); return 2; }
101
- const widths = v.widths ? String(v.widths).split(',').map(Number) : undefined;
102
- const r = await checkPage(url, { widths });
103
- if (v.out) writeFileSync(String(v.out), JSON.stringify(r, null, 2));
104
- out(v.json ? JSON.stringify(r, null, 2) : formatCheck(r));
105
- return r.counts.blocker || (v.strict && r.counts.major) ? 1 : 0;
106
- }
107
- case 'submit': {
108
- const { values: v, positionals } = parse({
109
- screen: { type: 'string', multiple: true }, images: { type: 'string', multiple: true }, app: { type: 'string' },
110
- question: { type: 'string', multiple: true }, source: { type: 'string', multiple: true }, 'resubmission-of': { type: 'string' },
111
- yes: { type: 'boolean' }, wait: { type: 'boolean' }, timeout: { type: 'string' },
112
- });
113
- // --images a.png b.png: the extra files arrive as positionals after the first.
114
- const url = positionals[0];
115
- const images = v.images ? [...v.images, ...positionals] : undefined;
116
- const base = images ? undefined : url;
117
- if (!v.app || (!base && !images)) { err('usage: commmerce-review submit <url> --app <name> [--screen name=/path ...] | submit --images <file...> --app <name>'); return 2; }
118
- const client = createClient();
119
- if (!client.hasKey) { err(KEY_HELP); return 2; }
120
- const screens = (v.screen ?? []).map((/** @type {string} */ s) => { const i = s.indexOf('='); if (i < 1) throw new Error(`--screen ${s}: use name=/path`); return { name: s.slice(0, i), path: s.slice(i + 1) }; });
121
- err(images ? `Reading ${images.length} image(s)...` : `Taking screenshots of ${screens.length || 1} screen(s) at 390, 768 and 1280px...`);
122
- const prep = await prepareSubmission({ app: String(v.app), url: base, screens, images, questions: v.question, sourceFiles: v.source, resubmissionOf: v['resubmission-of'] });
123
- const { emails, phones } = prep.personal;
124
- if (prep.fromFiles) err(`Reminder: ${DEMO_DATA_RULE} (image files can't be scanned.)`);
125
- if (emails.length || phones.length) {
126
- err(`Warning: ${DEMO_DATA_RULE}\nVisible on the page: ${[...emails, ...phones].slice(0, 10).map(mask).join(', ')}`);
127
- if (!v.yes) { err('Not sent. Replace them with demo data (e.g. name@example.com), or re-run with --yes if they are fake.'); return 2; }
128
- }
129
- for (const s of prep.summary) err(` ${s}`);
130
- const res = await client.submitReview(prep.body);
131
- if (!v.wait) { out(v.json ? JSON.stringify(res, null, 2) : `Submitted privately: ${res.id}\nOnly Commmerce and your team see it. Result: commmerce-review wait ${res.id}`); return 0; }
132
- err(`Submitted privately: ${res.id}. Waiting for the review...`);
133
- return await doWait(client, res.id, Number(v.timeout ?? 1800), !!v.json);
134
- }
135
- case 'key': {
136
- const { values: v, positionals: [sub] } = parse({ email: { type: 'string' }, name: { type: 'string' }, team: { type: 'string' }, kind: { type: 'string' } });
137
- if (sub !== 'request' || !v.email || !v.name || !v.team) { err('usage: commmerce-review key request --email <work email> --name <name> --team <team or app> [--kind internal|third-party]'); return 2; }
138
- const res = await createClient().requestKey({ email: String(v.email), name: String(v.name), team: String(v.team), ...(v.kind ? { kind: String(v.kind) } : {}) });
139
- out(v.json ? JSON.stringify(res, null, 2) : `${res.message}\nKind: ${res.kind}, team ${res.team}, ${res.daily_quota} submissions a day.`);
140
- return 0;
141
- }
142
- case 'status': {
143
- const { values: v, positionals: [id] } = parse({});
144
- if (!id) { err('usage: commmerce-review status <id>'); return 2; }
145
- const item = await createClient().getItem(id);
146
- out(v.json ? JSON.stringify(item, null, 2) : formatItem(item));
147
- return 0;
148
- }
149
- case 'wait': {
150
- const { values: v, positionals: [id] } = parse({ timeout: { type: 'string' } });
151
- if (!id) { err('usage: commmerce-review wait <id> [--timeout seconds]'); return 2; }
152
- return await doWait(createClient(), id, Number(v.timeout ?? 1800), !!v.json);
153
- }
154
- case 'request-component': {
155
- const { values: v } = parse({ name: { type: 'string' }, need: { type: 'string' }, app: { type: 'string' }, example: { type: 'string' } });
156
- if (!v.name || !v.need || !v.app) { err('usage: commmerce-review request-component --name <name> --need <text> --app <app> [--example <text or @file>]'); return 2; }
157
- const res = await createClient().requestComponent({ name: String(v.name), need: String(fileOrText(String(v.need))), app: String(v.app), ...(v.example ? { example: fileOrText(String(v.example)) } : {}) });
158
- out(v.json ? JSON.stringify(res, null, 2) : `Requested privately: ${res.id}. The reply comes back here: commmerce-review status ${res.id}`);
159
- return 0;
160
- }
161
- case 'feedback': {
162
- const { values: v } = parse({ kind: { type: 'string' }, title: { type: 'string' }, body: { type: 'string' }, app: { type: 'string' } });
163
- if (!v.kind || !v.title || !v.body) { err('usage: commmerce-review feedback --kind bug|refinement|question --title <title> --body <text or @file> [--app <app>]'); return 2; }
164
- const res = await createClient().sendFeedback({ kind: String(v.kind), title: String(v.title), body: String(fileOrText(String(v.body))), ...(v.app ? { app: String(v.app) } : {}) });
165
- out(v.json ? JSON.stringify(res, null, 2) : `Sent privately: ${res.id}. The reply comes back here: commmerce-review status ${res.id}`);
166
- return 0;
167
- }
168
- default:
169
- err(`Unknown command "${cmd}".\n\n${HELP}`);
170
- return 2;
171
- }
172
- } catch (e) {
173
- if (e instanceof SetupError || (e instanceof ApiError && [0, 400, 401, 403, 404, 413, 429].includes(e.status))) { err(e.message); return 2; }
174
- if (e instanceof Error && e.name === 'TypeError' && /** @type {any} */ (e).code?.startsWith?.('ERR_PARSE_ARGS')) { err(`${e.message}\n\n${HELP}`); return 2; }
175
- err(e instanceof Error ? e.message : String(e));
176
- return 2;
177
- }
178
- }
179
-
180
- /** @param {ReturnType<typeof createClient>} client @param {string} id @param {number} timeoutS @param {boolean} json */
181
- async function doWait(client, id, timeoutS, json) {
182
- let last = '';
183
- const { item, timedOut } = await waitFor(client, id, { timeoutS, onPoll: (i) => { if (!json && i.status !== last) { err(`${id}: ${i.status}`); last = i.status; } } });
184
- out(json ? JSON.stringify(item, null, 2) : formatItem(item));
185
- if (timedOut) { err(`Still ${item.status} after ${timeoutS}s. Check later: commmerce-review status ${id}`); return 3; }
186
- if (item.status === 'needs-owner') { err('Waiting for a decision at Commmerce; you will get the reply here (commmerce-review status).'); return 3; }
187
- return exitFor(item);
188
- }
@@ -1,76 +0,0 @@
1
- // Component data for agents: built from the docs' written content (docs/content.js `components`) and the generated API
2
- // (packages/ui custom-elements.json). The same file is in the public repo (packages/review/lib/components-index.mjs):
3
- // keep both copies identical.
4
-
5
- export const DOCS_BASE = 'https://commmerce.com/commmerceui/';
6
- // The docs router turns /components/button into the hash #components--button (docs/app.js toHash).
7
- export const docsUrl = (slug) => `${DOCS_BASE}#components--${slug}`;
8
-
9
- const text = (v) => (v == null ? undefined : String(v).replace(/\[\[([^|\]]+)\|[^\]]+\]\]/g, '$1'));
10
- const list = (v) => (Array.isArray(v) ? v.map((x) => (typeof x === 'string' ? text(x) : x)) : undefined);
11
-
12
- function api(cem, tag) {
13
- const decl = cem.modules.flatMap((m) => m.declarations ?? []).find((d) => d.tagName === tag);
14
- if (!decl) return null;
15
- const pub = (m) => !m.privacy || m.privacy === 'public';
16
- return {
17
- properties: (decl.attributes ?? []).map((a) => ({ attribute: a.name, property: a.fieldName, type: a.type?.text, default: a.default, description: a.description })),
18
- // Properties without an attribute (set from script), e.g. `items` or `options`.
19
- script_properties: (decl.members ?? []).filter((m) => m.kind === 'field' && !m.static && pub(m) && !(decl.attributes ?? []).some((a) => a.fieldName === m.name) && m.description)
20
- .map((m) => ({ property: m.name, type: m.type?.text, description: m.description })),
21
- methods: (decl.members ?? []).filter((m) => m.kind === 'method' && !m.static && pub(m) && m.description).map((m) => ({ name: m.name, description: m.description })),
22
- slots: (decl.slots ?? []).map((s) => ({ name: s.name || '(default)', description: s.description })),
23
- events: (decl.events ?? []).filter((e) => e.name).map((e) => ({ name: e.name, description: e.description })),
24
- };
25
- }
26
-
27
- export function buildIndex(components, cem) {
28
- return components.map((c) => ({
29
- tag: c.tag, slug: c.slug, name: c.name, react: c.react, group: c.group,
30
- summary: text(c.summary), lead: text(c.lead),
31
- docs_url: docsUrl(c.slug),
32
- ...api(cem, c.tag),
33
- parts: (c.parts ?? []).map((p) => ({ tag: p.tag, react: p.react, ...api(cem, p.tag) })),
34
- examples: (c.examples ?? []).filter((e) => e.html).map((e) => ({ title: e.title, description: text(e.description), html: e.html })),
35
- do: list(c.do), dont: list(c.dont), content: list(c.content), accessibility: list(c.a11y), responsive: list(c.responsive),
36
- related: c.related,
37
- }));
38
- }
39
-
40
- // Words developers use for things the docs name differently.
41
- const SYNONYMS = { dropdown: ['select', 'menu'], popup: ['modal'], dialog: ['modal'], popover: ['menu'], grid: ['table'], datagrid: ['table'],
42
- list: ['resource'], toast: ['toast'], snackbar: ['toast'], notification: ['toast', 'banner'], alert: ['banner'], switch: ['toggle'],
43
- textarea: ['text', 'field'], input: ['text', 'field'], autocomplete: ['combobox'], typeahead: ['combobox'], drawer: ['side', 'panel'],
44
- sidebar: ['side', 'navigation'], kanban: ['board'], loader: ['spinner', 'skeleton'], upload: ['file'], datepicker: ['date', 'picker'] };
45
- const words = (s) => String(s ?? '').toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 1);
46
-
47
- // Ranks components for a free-text need ("a table of orders with bulk actions").
48
- export function search(index, query, limit = 8) {
49
- const q = words(query).filter((w) => !['cm', 'the', 'an', 'and', 'with', 'for', 'of', 'to', 'in', 'on', 'my', 'need', 'want', 'component'].includes(w));
50
- if (!q.length) return index.slice(0, limit).map(brief);
51
- const extra = q.flatMap((w) => SYNONYMS[w] ?? []);
52
- const scored = index.map((c) => {
53
- const name = words(`${c.name} ${c.tag} ${c.slug} ${c.react}`);
54
- const head = words(`${c.summary} ${c.group}`);
55
- const body = words(`${c.lead} ${(c.examples ?? []).map((e) => e.title).join(' ')} ${(c.do ?? []).join(' ')}`);
56
- let score = 0;
57
- for (const w of q) {
58
- const stem = w.replace(/(es|s)$/, '');
59
- const hit = (arr) => arr.some((x) => x === w || x.replace(/(es|s)$/, '') === stem || (stem.length > 3 && x.startsWith(stem)));
60
- if (hit(name)) score += 10;
61
- if (hit(head)) score += 4;
62
- if (hit(body)) score += 1;
63
- }
64
- for (const w of extra) if (name.includes(w)) score += 6;
65
- return { c, score };
66
- }).filter((s) => s.score > 0).sort((a, b) => b.score - a.score);
67
- return scored.slice(0, limit).map((s) => brief(s.c));
68
- }
69
-
70
- export const brief = (c) => ({ tag: c.tag, name: c.name, group: c.group, summary: c.summary, docs_url: c.docs_url });
71
-
72
- export function find(index, name) {
73
- const n = String(name ?? '').trim().toLowerCase().replace(/^<|>$/g, '');
74
- return index.find((c) => c.tag === n || c.slug === n || c.name.toLowerCase() === n || c.react?.toLowerCase() === n || c.tag === `cm-${n}`
75
- || c.parts.some((p) => p.tag === n));
76
- }
@@ -1,11 +0,0 @@
1
- // The component data bundled at build time (dist/components.json, from docs/content.js and custom-elements.json).
2
- import { readFileSync } from 'node:fs';
3
-
4
- /** @type {{ version: string, components: any[] } | null} */
5
- let data = null;
6
- export function bundle() {
7
- data ??= JSON.parse(readFileSync(new URL('../dist/components.json', import.meta.url), 'utf8'));
8
- return /** @type {{ version: string, components: any[] }} */ (data);
9
- }
10
- export const components = () => bundle().components;
11
- export const UI_VERSION = () => bundle().version;