phation 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/audit.mjs ADDED
@@ -0,0 +1,456 @@
1
+ // Phation audit: measures the motion of any web page in headless Chrome, frame by frame, and scores it
2
+ // against the Phation Standard (§4 "Never", §5 UI, §6 reduced motion). Same detectors as the library's own QC.
3
+ //
4
+ // import { audit, formatReport } from './audit.mjs'
5
+ // const r = await audit('http://localhost:3000/checkout', { actions: ['click:#pay'], root: 'main' })
6
+ //
7
+ // Three loads of the page:
8
+ // A. timing rAF deltas only, no tracing overhead (dropped frames)
9
+ // B. trace every element under `root`: rect, cumulative opacity, visible area, inline layout styles, each frame
10
+ // C. reduced same as B with prefers-reduced-motion: reduce, to check the page respects it
11
+ // Each load: open → wait for the intro → run the actions → record a little longer.
12
+ import puppeteer from 'puppeteer-core'
13
+ import fs from 'fs'
14
+
15
+ // ---------- Chrome ----------
16
+ export function findChrome() {
17
+ const c = [process.env.CHROME_PATH, process.env.PUPPETEER_EXECUTABLE_PATH,
18
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium',
19
+ '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
20
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium',
21
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe']
22
+ const hit = c.find(p => p && fs.existsSync(p))
23
+ if (!hit) throw new Error('Chrome not found. Install Google Chrome or set CHROME_PATH to a Chrome/Chromium executable.')
24
+ return hit
25
+ }
26
+
27
+ // ---------- in-page tracer (delta-encoded: a row is sent only when it changes) ----------
28
+ function tracer(rootSel, cap) {
29
+ const ids = new WeakMap(), desc = [], paints = new WeakMap(); let next = 0
30
+ const paintOf = (el, cs) => {
31
+ const a = c => { const m = c.match(/[\d.]+/g); return m ? (m.length > 3 ? +m[3] : 1) : 0 }
32
+ if (/^(IMG|VIDEO|CANVAS|svg)$/i.test(el.tagName)) return 1
33
+ if (a(cs.backgroundColor) > 0.05 || cs.boxShadow !== 'none' || parseFloat(cs.borderTopWidth) > 0) return 1
34
+ if (cs.backgroundImage !== 'none' && cs.webkitBackgroundClip !== 'text' && cs.backgroundClip !== 'text') return 1
35
+ if ([...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim()) && a(cs.color) > 0.05) return 1
36
+ return 0
37
+ }
38
+ const name = el => {
39
+ let s = el.tagName.toLowerCase()
40
+ if (el.id) s += '#' + el.id
41
+ else if (typeof el.className === 'string' && el.className.trim()) s += '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.')
42
+ const label = el.getAttribute('aria-label') || (el.childElementCount < 4 ? el.textContent.trim().replace(/\s+/g, ' ') : '')
43
+ return label ? `${s} "${label.slice(0, 28)}"` : s
44
+ }
45
+ const T = (window.__trace = { frames: [], dts: [], on: false, desc, css: {} })
46
+ // CSS transitions / keyframes on layout properties (Motion's inline-style animation is caught by `sig` below)
47
+ const CSSLAYOUT = /^(top|left|right|bottom|width|height|inset|margin|padding|max-width|max-height|min-width|min-height)/
48
+ let tick = 0
49
+ const LAYOUT = ['width', 'height', 'top', 'left', 'right', 'bottom', 'marginTop', 'marginLeft', 'paddingTop', 'paddingLeft']
50
+ let last = 0, prev = new Map()
51
+ function walk(el, op, clip, out, fixed) {
52
+ if (el.dataset && el.dataset.audit === 'skip') return // a deliberate bad example (e.g. a "before" demo) is not judged
53
+ const cs = getComputedStyle(el)
54
+ if (cs.display === 'none' || cs.visibility === 'hidden') return
55
+ const fx = fixed || cs.position === 'fixed' || cs.position === 'sticky'
56
+ const o = op * (+cs.opacity)
57
+ if (!ids.has(el)) { ids.set(el, next); desc[next] = name(el); paints.set(el, paintOf(el, cs)); next++ }
58
+ const r = el.getBoundingClientRect()
59
+ const vw = Math.max(0, Math.min(r.right, clip[2]) - Math.max(r.left, clip[0])), vh = Math.max(0, Math.min(r.bottom, clip[3]) - Math.max(r.top, clip[1]))
60
+ let sig = ''
61
+ for (const k of LAYOUT) if (el.style[k]) sig += k + el.style[k]
62
+ const m = cs.transform.match(/matrix\(([^,]+),([^,]+)/)
63
+ out.push([ids.get(el), Math.round(r.x * 10) / 10, Math.round(r.y * 10) / 10, Math.round(r.width * 10) / 10, Math.round(r.height * 10) / 10, Math.round(o * 1000) / 1000, sig, Math.round(vw * vh), paints.get(el), cs.clipPath === 'none' ? '' : cs.clipPath, m ? Math.round(Math.atan2(+m[2], +m[1]) * 573) / 10 : 0, fx ? 1 : 0])
64
+ const nclip = cs.overflow !== 'visible' || cs.clipPath !== 'none' ? [Math.max(clip[0], r.left), Math.max(clip[1], r.top), Math.min(clip[2], r.right), Math.min(clip[3], r.bottom)] : clip
65
+ if (out.length < cap) for (const c of el.children) { if (/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|HEAD|META|LINK)$/.test(c.tagName)) continue; walk(c, o, nclip, out, fx) }
66
+ }
67
+ function loop(ts) {
68
+ if (last) T.dts.push(ts - last); last = ts
69
+ if (T.on) {
70
+ const root = (rootSel && document.querySelector(rootSel)) || document.body
71
+ if (root) {
72
+ const out = [], seen = new Set(), rows = []
73
+ for (const c of root.children) walk(c, 1, [0, 0, innerWidth, innerHeight], out, false)
74
+ for (const row of out) { const id = row[0], k = row.join('|'); seen.add(id); if (prev.get(id) !== k) { prev.set(id, k); rows.push(row) } }
75
+ for (const id of prev.keys()) if (!seen.has(id)) { rows.push([id, null]); prev.delete(id) }
76
+ T.frames.push([ts, rows, scrollX, scrollY])
77
+ if (++tick % 4 === 0 && document.getAnimations) for (const an of document.getAnimations()) {
78
+ const el = an.effect && an.effect.target; if (!el || !root.contains(el)) continue
79
+ let props = []
80
+ if (an.transitionProperty) props = [an.transitionProperty]
81
+ else if (an.effect.getKeyframes) props = an.effect.getKeyframes().flatMap(k => Object.keys(k)).filter(k => !['offset', 'easing', 'composite', 'computedOffset'].includes(k)).map(k => k.replace(/[A-Z]/g, c => '-' + c.toLowerCase()))
82
+ const b = el.getBoundingClientRect(), small = b.width <= 240 && b.height <= 80
83
+ for (const pr of props) if (CSSLAYOUT.test(pr) && !(small && /^(width|height|min-|max-)/.test(pr))) { if (!ids.has(el)) { ids.set(el, next); desc[next] = name(el); next++ } const key = ids.get(el) + '|' + pr; T.css[key] = T.css[key] || ts }
84
+ }
85
+ }
86
+ }
87
+ requestAnimationFrame(loop)
88
+ }
89
+ requestAnimationFrame(loop)
90
+ }
91
+
92
+ // rebuild full frames from the deltas, in page coordinates: scrolling the page is not element motion
93
+ // (fixed and sticky elements stay in viewport coordinates, because that is where they live)
94
+ function expand(deltas) {
95
+ const state = new Map()
96
+ return deltas.map(([ts, rows, sx = 0, sy = 0]) => {
97
+ for (const r of rows) r[1] === null ? state.delete(r[0]) : state.set(r[0], r)
98
+ return [ts, [...state.values()].map(r => r[11] ? r : [r[0], r[1] + sx, r[2] + sy, ...r.slice(3)])]
99
+ })
100
+ }
101
+
102
+ // ---------- in-page UI audit (text, targets, images inside the viewport) ----------
103
+ function uiAudit(rootSel) {
104
+ const root = (rootSel && document.querySelector(rootSel)) || document.body
105
+ const parse = c => { const m = c.match(/[\d.]+/g); return m ? m.map(Number) : [0, 0, 0, 0] }
106
+ const inView = r => r.width > 1 && r.height > 1 && r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth
107
+ const shown = el => {
108
+ const r = el.getBoundingClientRect(); if (!inView(r)) return false
109
+ let o = 1; for (let e = el; e && e.nodeType === 1; e = e.parentElement) { const cs = getComputedStyle(e); if (cs.visibility === 'hidden' || cs.display === 'none') return false; o *= +cs.opacity }
110
+ return o > 0.6 && !facesAway(el)
111
+ }
112
+ // the hidden side of a flip card (backface-visibility: hidden, turned past 90°) is not on screen
113
+ const facesAway = el => {
114
+ for (let e = el; e && e.nodeType === 1; e = e.parentElement) {
115
+ if (getComputedStyle(e).backfaceVisibility !== 'hidden') continue
116
+ let m = new DOMMatrix()
117
+ for (let a = e; a && a.nodeType === 1; a = a.parentElement) { const t = getComputedStyle(a).transform; if (t && t !== 'none') m = new DOMMatrix(t).multiply(m) }
118
+ if (m.m33 < 0) return true
119
+ }
120
+ return false
121
+ }
122
+ const texts = [], targets = [], imgs = []
123
+ let n = 0
124
+ for (const el of root.querySelectorAll('*')) {
125
+ if (++n > 4000) break
126
+ if (el.closest('[aria-hidden="true"],[data-qc="decorative"],[data-audit="skip"]')) continue
127
+ const cs = getComputedStyle(el)
128
+ const own = [...el.childNodes].some(t => t.nodeType === 3 && t.textContent.trim())
129
+ if (own && texts.length < 150 && shown(el)) {
130
+ const r = el.getBoundingClientRect(), fs = parseFloat(cs.fontSize), fg = parse(cs.color)
131
+ if (fg[3] === undefined || fg[3] > 0.5) texts.push({ t: el.textContent.trim().replace(/\s+/g, ' ').slice(0, 30), fs, large: fs >= 24 || (fs >= 18.6 && +cs.fontWeight >= 600), x: Math.max(0, r.x), y: Math.max(0, r.y), w: Math.min(r.width, innerWidth - Math.max(0, r.x)), h: Math.min(r.height, innerHeight - Math.max(0, r.y)), fg: fg.slice(0, 3) })
132
+ }
133
+ if (el.matches('button,a[href],input:not([type=hidden]),select,textarea,[role=button],[role=tab],[role=slider],[role=checkbox],[role=switch]') && shown(el)) {
134
+ const r = el.getBoundingClientRect(), inline = el.tagName === 'A' && getComputedStyle(el).display === 'inline' && el.closest('p,li')
135
+ if (!inline) targets.push({ t: (el.getAttribute('aria-label') || el.textContent.trim() || el.tagName).replace(/\s+/g, ' ').slice(0, 24), w: Math.round(r.width), h: Math.round(r.height) })
136
+ }
137
+ if (el.tagName === 'IMG' && el.naturalWidth && shown(el)) { const r = el.getBoundingClientRect(); imgs.push({ src: (el.currentSrc || el.src).split('/').pop().slice(0, 40), up: Math.round((r.width * devicePixelRatio) / el.naturalWidth * 100) / 100 }) }
138
+ }
139
+ return { texts, targets, imgs }
140
+ }
141
+
142
+ // pixel contrast, computed in a blank page (the audited page's CSP can't block it): same method as qc/contrast.py
143
+ async function pixelContrast(browser, png, texts, dpr) {
144
+ if (!texts.length) return texts
145
+ const p = await browser.newPage()
146
+ try {
147
+ const res = await p.evaluate(async (b64, rects, d) => {
148
+ const img = new Image(); img.src = 'data:image/png;base64,' + b64; await img.decode()
149
+ const cv = new OffscreenCanvas(img.width, img.height), g = cv.getContext('2d'); g.drawImage(img, 0, 0)
150
+ const lum = ([r, gg, b]) => { const f = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 }; return 0.2126 * f(r) + 0.7152 * f(gg) + 0.0722 * f(b) }
151
+ return rects.map(r => {
152
+ const x0 = Math.max(0, Math.floor(r.x * d)), y0 = Math.max(0, Math.floor(r.y * d)), w = Math.min(img.width - x0, Math.floor(r.w * d)), h = Math.min(img.height - y0, Math.floor(r.h * d))
153
+ if (w < 2 || h < 2) return null
154
+ const px = g.getImageData(x0, y0, w, h).data, text = [], rest = [], near = []
155
+ for (let i = 0; i < px.length; i += 4) {
156
+ const c = [px[i], px[i + 1], px[i + 2]], dist = Math.hypot(c[0] - r.fg[0], c[1] - r.fg[1], c[2] - r.fg[2])
157
+ if (dist < 40) text.push(c); if (dist > 90) rest.push(lum(c)); if (dist > 12) near.push(lum(c))
158
+ }
159
+ const n = px.length / 4, cover = text.length / n
160
+ let bg = rest; if (bg.length < 10 && cover > 0.6) bg = near.length >= 10 ? near : bg
161
+ if (bg.length < 10 || cover < 0.01) return { cr: null, cover }
162
+ bg.sort((a, b) => a - b); const lb = bg[bg.length >> 1], lf = lum(r.fg), hi = Math.max(lf, lb), lo = Math.min(lf, lb)
163
+ return { cr: Math.round((hi + 0.05) / (lo + 0.05) * 100) / 100, cover }
164
+ })
165
+ }, png, texts, dpr)
166
+ // text with no pixels of its colour on screen (covered, a back face) is not checked; tiny antialiased type keeps a few
167
+ return texts.map((t, i) => ({ ...t, cr: res[i]?.cr ?? null, hidden: res[i] && res[i].cover < 0.002 })).filter(t => !t.hidden)
168
+ } finally { await p.close() }
169
+ }
170
+
171
+ // ---------- actions ----------
172
+ // "click:#buy" · "hover:.card" · "scroll:600" · "drag:.thumb:200,0" · "hold:.btn:1500" · "key:Escape" · "type:input[name=q]:hello" · "wait:800"
173
+ export function parseAction(a) {
174
+ if (typeof a === 'object') return a
175
+ const i = a.indexOf(':'), type = (i < 0 ? a : a.slice(0, i)).trim().toLowerCase(), rest = i < 0 ? '' : a.slice(i + 1)
176
+ const tail = () => { const j = rest.lastIndexOf(':'); return j < 0 ? [rest, ''] : [rest.slice(0, j), rest.slice(j + 1)] }
177
+ switch (type) {
178
+ case 'click': case 'hover': case 'focus': return { type, selector: rest }
179
+ case 'scroll': return { type, y: +rest || 600 }
180
+ case 'wait': return { type, ms: +rest || 800 }
181
+ case 'key': return { type, key: rest || 'Enter' }
182
+ case 'drag': { const [s, d] = tail(); const [dx, dy] = (d || '200,0').split(',').map(Number); return { type, selector: s, dx: dx || 0, dy: dy || 0 } }
183
+ case 'hold': { const [s, ms] = tail(); return { type, selector: s, ms: +ms || 1500 } }
184
+ case 'type': { const [s, text] = tail(); return { type, selector: s, text } }
185
+ default: throw new Error(`Unknown action "${a}". Use click:, hover:, focus:, scroll:, drag:, hold:, key:, type: or wait:`)
186
+ }
187
+ }
188
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
189
+ async function centre(page, selector) {
190
+ const el = await page.$(selector); if (!el) throw new Error(`Action target not found: ${selector}`)
191
+ // only scroll when the target is not already fully on screen
192
+ const off = await el.evaluate(e => { const r = e.getBoundingClientRect(); return r.top < 0 || r.left < 0 || r.bottom > innerHeight || r.right > innerWidth })
193
+ if (off) { await el.evaluate(e => e.scrollIntoView({ block: 'center', inline: 'center' })); await sleep(400) }
194
+ const b = await el.boundingBox(); if (!b) throw new Error(`Action target is not visible: ${selector}`)
195
+ return { x: b.x + b.width / 2, y: b.y + b.height / 2 }
196
+ }
197
+ async function run(page, a, after) {
198
+ const m = page.mouse
199
+ if (a.type === 'wait') return sleep(a.ms)
200
+ if (a.type === 'scroll') { for (let i = 0; i < 20; i++) { await m.wheel({ deltaY: a.y / 20 }); await sleep(30) } }
201
+ else if (a.type === 'key') await page.keyboard.press(a.key)
202
+ else if (a.type === 'focus') await page.focus(a.selector)
203
+ else if (a.type === 'type') { await page.click(a.selector); await page.keyboard.type(a.text, { delay: 40 }) }
204
+ else {
205
+ const c = await centre(page, a.selector)
206
+ if (a.type === 'hover') await m.move(c.x, c.y, { steps: 12 })
207
+ if (a.type === 'click') { await m.move(c.x, c.y, { steps: 8 }); await sleep(80); await m.click(c.x, c.y) }
208
+ if (a.type === 'hold') { await m.move(c.x, c.y, { steps: 8 }); await m.down(); await sleep(a.ms); await m.up() }
209
+ if (a.type === 'drag') { await m.move(c.x, c.y); await m.down(); for (let i = 1; i <= 30; i++) { await m.move(c.x + a.dx * i / 30, c.y + a.dy * i / 30); await sleep(16) } await m.up() }
210
+ }
211
+ await sleep(after)
212
+ }
213
+ // no actions given: hover a few visible controls (never click: that could submit or navigate)
214
+ async function autoActions(page, root) {
215
+ const sels = await page.evaluate(r => {
216
+ const base = (r && document.querySelector(r)) || document.body, out = []
217
+ for (const el of base.querySelectorAll('button, a[href], [role=button], [role=tab]')) {
218
+ const b = el.getBoundingClientRect(); if (b.width < 8 || b.height < 8 || b.bottom < 0 || b.top > innerHeight) continue
219
+ el.setAttribute('data-hp-audit', String(out.length)); out.push(`[data-hp-audit="${out.length}"]`); if (out.length >= 4) break
220
+ }
221
+ return out
222
+ }, root)
223
+ return sels.map(s => ({ type: 'hover', selector: s }))
224
+ }
225
+
226
+ // ---------- analysis (shared with qc/certify.mjs) ----------
227
+ function analyse(frames, actFrame) {
228
+ const tracks = new Map()
229
+ frames.forEach(([ts, els], fi) => els.forEach(([id, x, y, w, h, o, sig, va, pt, cp, ang]) => {
230
+ if (!tracks.has(id)) tracks.set(id, [])
231
+ tracks.get(id).push({ fi, ts, x, y, w, h, o, sig, va, pt, cp, ang })
232
+ }))
233
+ const N = frames.length, issues = [], segs = []
234
+ const ends = []
235
+ for (const tr of tracks.values()) ends.push(tr[0], tr[tr.length - 1])
236
+ let movedAfterAct = false
237
+ for (const [id, tr] of tracks) {
238
+ const area = Math.max(...tr.map(p => p.w * p.h))
239
+ if (area < 16) continue
240
+ const first = tr[0], lastp = tr[tr.length - 1]
241
+ const same = (p, fi) => ends.some(q => q !== tr[0] && q !== tr[tr.length - 1] && Math.abs(q.fi - fi) <= 2 && Math.abs(q.x - p.x) < 3 && Math.abs(q.y - p.y) < 3 && Math.abs(q.w - p.w) < 3 && Math.abs(q.h - p.h) < 3)
242
+ const reveal = p0 => tr.slice(0, 8).some(q => q.cp !== p0.cp)
243
+ if (first.pt && !reveal(first) && first.fi > 8 && first.o > 0.9 && first.va > 6000 && tr[Math.min(3, tr.length - 1)].o > 0.9 && !same(first, first.fi)) issues.push({ k: 'cut-in', el: id, ts: first.ts, d: `${Math.round(first.w)}×${Math.round(first.h)} appears at full opacity` })
244
+ if (lastp.pt && lastp.fi < N - 2 && lastp.o > 0.9 && lastp.va > 6000 && !same(lastp, lastp.fi)) issues.push({ k: 'cut-out', el: id, ts: lastp.ts, d: `${Math.round(lastp.w)}×${Math.round(lastp.h)} vanishes at full opacity` })
245
+ const sigs = new Set(tr.map(p => p.sig).filter(Boolean))
246
+ // a small control morphing its own size is allowed by the standard (§1.6): ≤ 240 × 80 px
247
+ const small = Math.max(...tr.map(p => p.w)) <= 240 && Math.max(...tr.map(p => p.h)) <= 80
248
+ if (sigs.size >= 8 && !small) issues.push({ k: 'layout-anim', el: id, ts: tr[0].ts, d: `inline ${[...sigs][0].replace(/[\d.\-]+.*/, '')} changes on ${sigs.size} frames` })
249
+ // a container bigger than the screen growing because content loaded is layout, not motion: skip its size channels
250
+ const page = area > 1.2e6
251
+ for (const ch of ['x', 'y', 'w', 'h', 'o']) {
252
+ if (page && (ch === 'w' || ch === 'h')) continue
253
+ const thr = ch === 'o' ? 0.008 : 0.3
254
+ let i = 1
255
+ while (i < tr.length) {
256
+ if (Math.abs(tr[i][ch] - tr[i - 1][ch]) <= thr || tr[i].fi !== tr[i - 1].fi + 1) { i++; continue }
257
+ let j = i, still = 0
258
+ while (j < tr.length && tr[j].fi === tr[j - 1].fi + 1 && still <= 2) { still = Math.abs(tr[j][ch] - tr[j - 1][ch]) <= thr ? still + 1 : 0; j++ }
259
+ const s = tr.slice(i - 1, j - still)
260
+ i = j
261
+ if (s.length < 4) {
262
+ if (s.length >= 2) { const jump = Math.abs(s[s.length - 1][ch] - s[0][ch]); const vis = s[0].pt && Math.max(s[0].o, s[s.length - 1].o) > 0.5 && Math.max(s[0].va, s[s.length - 1].va) > 200
263
+ // an image or lazy block getting its size for the first time (from ~0) is loading, not motion
264
+ const loading = s[0].w < 4 || s[0].h < 4
265
+ if (vis && !loading && ((ch !== 'o' && jump > 40) || (ch === 'o' && jump > 0.6 && area > 3000))) segs.push({ id, ch, pop: true, ts: s[0].ts, fi: s[0].fi, jump, area }) }
266
+ continue
267
+ }
268
+ const v = s.map(p => p[ch]), dur = s[s.length - 1].ts - s[0].ts, travel = v[v.length - 1] - v[0]
269
+ const sp = v.slice(1).map((p, k) => Math.abs(p - v[k]))
270
+ const mid = sp.slice(Math.floor(sp.length * 0.15), Math.ceil(sp.length * 0.85))
271
+ const mean = mid.reduce((a, b) => a + b, 0) / (mid.length || 1)
272
+ const cv = Math.sqrt(mid.reduce((a, b) => a + (b - mean) ** 2, 0) / (mid.length || 1)) / (mean || 1)
273
+ const beyond = travel === 0 ? 0 : Math.max(0, ...v.map(p => (p - v[v.length - 1]) * Math.sign(travel)))
274
+ const spinning = Math.max(...s.map(p => p.ang)) - Math.min(...s.map(p => p.ang)) > 5
275
+ const ambient = spinning || dur > 2600 || s[s.length - 1].fi >= N - 2
276
+ const vis = Math.max(...s.map(p => p.o)) > 0.3 && Math.max(...s.map(p => p.va)) > 200
277
+ if (actFrame >= 0 && s[s.length - 1].fi > actFrame && Math.max(...v.map(p => Math.abs(p - v[0]))) > (ch === 'o' ? 0.1 : 3)) movedAfterAct = true
278
+ if (!vis) continue
279
+ segs.push({ id, ch, ts: s[0].ts, fi: s[0].fi, dur, frames: s.length, travel, mean, cv, over: travel ? beyond / Math.abs(travel) : 0, ambient, area, load: s[0].w < 4 || s[0].h < 4 })
280
+ }
281
+ }
282
+ }
283
+ const key = s => `${s.ch}|${Math.round(s.ts / 50)}|${Math.round(s.dur / 50)}|${Math.round((s.travel || s.jump || 0) * (s.ch === 'o' ? 20 : 0.2))}`
284
+ const uniq = [...new Map(segs.map(s => [key(s), s])).values()]
285
+ const shape = s => `${s.ch}|${Math.round(s.dur / 120)}|${Math.round(Math.abs(s.travel || 0) * (s.ch === 'o' ? 10 : 0.1))}`
286
+ const reps = {}; for (const s of uniq) if (!s.pop) reps[shape(s)] = (reps[shape(s)] || 0) + 1
287
+ for (const s of uniq) if (!s.pop && reps[shape(s)] >= 3) s.ambient = true
288
+ let moves = 0, dist = 0
289
+ for (const s of uniq) {
290
+ if (s.pop) { issues.push({ k: s.ch === 'o' ? 'opacity-pop' : 'teleport', el: s.id, ts: s.ts, d: `${s.ch} jumps ${s.ch === 'o' ? s.jump.toFixed(2) : Math.round(s.jump) + 'px'} in one frame` }); continue }
291
+ if (!s.ambient && !s.load && (s.ch === 'x' || s.ch === 'y') && Math.abs(s.travel) > 12) { moves++; dist += Math.abs(s.travel) }
292
+ const big = s.ch === 'o' ? Math.abs(s.travel) > 0.3 : Math.abs(s.travel) > 12
293
+ if (!s.ambient && big && s.frames >= 15 && s.mean > (s.ch === 'o' ? 0.01 : 0.6) && s.cv < 0.07)
294
+ issues.push({ k: s.ch === 'o' ? 'linear-fade' : 'linear-move', el: s.id, ts: s.ts, d: `${s.ch} ${s.ch === 'o' ? s.travel.toFixed(2) : Math.round(s.travel) + 'px'} at constant speed for ${Math.round(s.dur)} ms` })
295
+ if (!s.ambient && s.ch !== 'o' && Math.abs(s.travel) > 16 && s.over > 0.22) issues.push({ k: 'overshoot', el: s.id, ts: s.ts, d: `${s.ch} overshoots ${Math.round(s.over * 100)}% of ${Math.round(Math.abs(s.travel))}px` })
296
+ if (!s.ambient && s.ch !== 'o' && Math.abs(s.travel) > 60 && s.dur > 1300 && Math.abs(s.travel) / s.dur * 1000 < 300) issues.push({ k: 'slow', el: s.id, ts: s.ts, d: `${s.ch} ${Math.round(s.travel)}px takes ${Math.round(s.dur)} ms` })
297
+ if (!s.ambient && s.ch !== 'o' && Math.abs(s.travel) > 60 && s.dur < 110 && s.frames >= 4) issues.push({ k: 'snap', el: s.id, ts: s.ts, d: `${s.ch} ${Math.round(s.travel)}px in ${Math.round(s.dur)} ms` })
298
+ }
299
+ return { issues, movedAfterAct, moves, dist: Math.round(dist), segments: uniq.length }
300
+ }
301
+
302
+ // ---------- scoring + fixes (values from the Phation Standard) ----------
303
+ export const W = { 'page-error': 25, 'cut-in': 6, 'cut-out': 6, teleport: 6, 'opacity-pop': 4, 'linear-move': 8, 'linear-fade': 2, overshoot: 3, slow: 2, snap: 3, 'layout-anim': 2, 'no-response': 8, jank: 6, 'jank-heavy': 12, 'ignores-reduced-motion': 6, 'low-contrast': 8, 'weak-contrast': 2, 'tiny-text': 2, 'small-target': 3, 'upscaled-image': 3 }
304
+ const CAP = { 'linear-fade': 6, 'layout-anim': 6, 'weak-contrast': 6, 'tiny-text': 6, 'small-target': 9, 'upscaled-image': 6, overshoot: 9, 'opacity-pop': 12, 'cut-in': 12, 'cut-out': 12, teleport: 12, 'linear-move': 24, slow: 6, snap: 9 }
305
+ export const BLOCK = new Set(['page-error', 'linear-move', 'low-contrast', 'jank-heavy', 'no-response'])
306
+ export const FIX = {
307
+ 'linear-move': 'Moves at constant speed. Use `enter` cubic-bezier(0.16, 1, 0.3, 1), or the `snap` spring k420 c32 for controls (§2.1, §2.2). Linear is only for ambient loops.',
308
+ 'linear-fade': 'Linear fade. Use `fade` cubic-bezier(0.4, 0, 0.2, 1) for opacity (§2.1).',
309
+ teleport: 'Jumps more than 40 px in one frame. Animate transform (x/y) or use Motion `layout` / `layoutId` instead of setting the position (§1.6).',
310
+ 'opacity-pop': 'Appears or disappears in one frame. Fade it: 150–220 ms on `fade` (§2.3).',
311
+ 'cut-in': 'A large element appears at full opacity. Enter it: y 18–24 px + fade, 400 ms `enter` (§3), or grow it out of its trigger (§1.3).',
312
+ 'cut-out': 'A large element vanishes at full opacity. Exit it with a fade + small move at ≈0.7× its enter duration on `move` (§1.5).',
313
+ overshoot: 'Bounces too far. Use `snap` k420 c32 (≈2 %); keep `pop` k400 c20 for small elements only (§2.2).',
314
+ slow: 'Too slow for its distance. Large moves take 700–900 ms; nothing over 1.3 s (§2.3).',
315
+ snap: 'Too abrupt for its distance. Moves over 60 px take at least 300 ms (§2.3).',
316
+ 'layout-anim': 'Animates width/height/top/left. Animate transform, or use Motion `layout` (§1.6). A small control morphing its own width is the one exception.',
317
+ 'no-response': 'Nothing moved after the action. Give feedback: press = scale 0.96 for 160 ms, or show the next state (§3).',
318
+ jank: 'Drops frames. Animate only transform and opacity; avoid animating filter, box-shadow or blur on large areas (§1.6).',
319
+ 'jank-heavy': 'Drops many frames. Animate only transform and opacity; avoid animating filter, box-shadow or blur on large areas (§1.6).',
320
+ 'ignores-reduced-motion': 'Still moves with prefers-reduced-motion. Use useReducedMotion() and replace movement with a ≤ 150 ms fade (§6).',
321
+ 'low-contrast': 'Text under 3:1. Raise it to 4.5:1 (3:1 for ≥ 24 px); add a scrim over photos (§5).',
322
+ 'weak-contrast': 'Body text under 4.5:1. Darken the text or add a scrim (§5).',
323
+ 'tiny-text': 'Text under 10.5 px. Use at least 11 px (§5).',
324
+ 'small-target': 'Touch target under 24 px. Make it at least 24 px, 44 px on mobile (§5).',
325
+ 'upscaled-image': 'Image drawn bigger than its pixels. Serve a larger source (§5).',
326
+ 'page-error': 'The page threw an error during the audit. Fix it first; motion results may be incomplete.',
327
+ }
328
+
329
+ function uiIssues(ui, tag, mobile) {
330
+ const out = [], seen = new Set(), once = (k, d) => { if (!seen.has(k + d)) { seen.add(k + d); out.push({ k, d: `${tag}: ${d}` }) } }
331
+ for (const t of ui.texts) {
332
+ if (t.cr != null && t.cr < 3) once('low-contrast', `"${t.t}" ${t.cr}:1`)
333
+ else if (t.cr != null && t.cr < 4.5 && !t.large) once('weak-contrast', `"${t.t}" ${t.cr}:1 at ${t.fs}px`)
334
+ if (t.fs < 10.5) once('tiny-text', `"${t.t}" ${t.fs}px`)
335
+ }
336
+ for (const t of ui.targets) if (Math.min(t.w, t.h) < (mobile ? 24 : 20)) once('small-target', `"${t.t}" ${t.w}×${t.h}`)
337
+ for (const i of ui.imgs) if (i.up > 1.3) once('upscaled-image', `${i.src} ×${i.up}`)
338
+ return out
339
+ }
340
+
341
+ /**
342
+ * Audit the motion of a page.
343
+ * @param {string} url
344
+ * @param {{ actions?: (string|object)[], root?: string, mobile?: boolean, intro?: number, after?: number, reduced?: boolean, cap?: number, shots?: string }} opts
345
+ */
346
+ export async function audit(url, { actions = [], root = null, mobile = false, dark = false, intro = 2500, after = 1200, reduced = true, cap = 1500, shots = null, onStep = () => {}, launch = {}, guard = null } = {}) {
347
+ const acts = actions.map(parseAction)
348
+ const view = mobile ? { width: 390, height: 844, deviceScaleFactor: 2, isMobile: true, hasTouch: true } : { width: 1440, height: 900, deviceScaleFactor: 2 }
349
+ const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, ...launch, args: ['--force-color-profile=srgb', '--hide-scrollbars', '--no-first-run', ...(launch.args || [])] })
350
+ const rep = { url, viewport: (mobile ? 'mobile 390×844' : 'desktop 1440×900') + (dark ? ' · dark' : ''), root: root || 'body', actions: [], issues: [] }
351
+ const desc = []
352
+ try {
353
+ const open = async (traceOn, media) => {
354
+ const p = await browser.newPage(); await p.setViewport(view)
355
+ await p.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: dark ? 'dark' : 'light' }, ...(media ? [{ name: 'prefers-reduced-motion', value: 'reduce' }] : [])])
356
+ await p.evaluateOnNewDocument(tracer, root, cap)
357
+ if (traceOn) await p.evaluateOnNewDocument(() => { window.__hpTraceFromStart = true })
358
+ const errs = []; p.on('pageerror', e => errs.push(String(e.message).slice(0, 160)))
359
+ // hosted audits: `guard(url) → bool` vets every request the page makes (no private hosts behind a public page)
360
+ if (guard) { await p.setRequestInterception(true); p.on('request', r => (guard(r.url()) ? r.continue() : r.abort('blockedbyclient'))) }
361
+ await p.evaluateOnNewDocument(() => { if (window.__hpTraceFromStart) { const s = () => window.__trace ? (window.__trace.on = true) : requestAnimationFrame(s); s() } })
362
+ const res = await p.goto(url, { waitUntil: 'networkidle2', timeout: 30000 })
363
+ if (!res || res.status() >= 400) throw new Error(`Could not load ${url} (${res ? 'HTTP ' + res.status() : 'no response'}). Is the dev server running?`)
364
+ return { p, errs }
365
+ }
366
+ const play = async (p, list) => {
367
+ await sleep(intro)
368
+ const actFrame = await p.evaluate(() => window.__trace.frames.length)
369
+ const done = []
370
+ for (const a of list) { await run(p, a, after); done.push(a) }
371
+ await sleep(after)
372
+ return { actFrame, done }
373
+ }
374
+
375
+ // A — timing
376
+ onStep('timing')
377
+ let { p, errs } = await open(false)
378
+ const list = acts.length ? acts : await autoActions(p, root)
379
+ await play(p, list)
380
+ const dts = await p.evaluate(() => window.__trace.dts.slice(30)); await p.close()
381
+ const dropped = dts.filter(d => d > 25).length / (dts.length || 1)
382
+ rep.dropped = Math.round(dropped * 1000) / 10
383
+ if (dropped > 0.15) rep.issues.push({ k: 'jank-heavy', d: `${rep.dropped}% of frames over 25 ms` })
384
+ else if (dropped > 0.05) rep.issues.push({ k: 'jank', d: `${rep.dropped}% of frames over 25 ms` })
385
+
386
+ // B — trace, from the first frame so entrance motion counts
387
+ onStep('trace')
388
+ ;({ p, errs } = await open(true))
389
+ const listB = acts.length ? acts : await autoActions(p, root)
390
+ const shot = async f => { const png = await p.screenshot({ encoding: 'base64' }); if (shots) { fs.mkdirSync(shots, { recursive: true }); fs.writeFileSync(`${shots}/${f}.png`, Buffer.from(png, 'base64')) } return png }
391
+ await sleep(intro)
392
+ const uiRest = await p.evaluate(uiAudit, root); uiRest.texts = await pixelContrast(browser, await shot('rest'), uiRest.texts, view.deviceScaleFactor)
393
+ // waiting is not an interaction: only real actions must get a visible response
394
+ const interacts = acts.some(a => a.type !== 'wait')
395
+ const actFrame = interacts ? await p.evaluate(() => window.__trace.frames.length) : -1
396
+ for (const a of listB) { await run(p, a, after); rep.actions.push(a.type + (a.selector && !a.selector.startsWith('[data-hp-audit') ? ' ' + a.selector : a.y ? ' ' + a.y : a.key ? ' ' + a.key : '')) }
397
+ await sleep(after)
398
+ const uiEnd = await p.evaluate(uiAudit, root); uiEnd.texts = await pixelContrast(browser, await shot('end'), uiEnd.texts, view.deviceScaleFactor)
399
+ const raw = await p.evaluate(() => { window.__trace.on = false; return { frames: window.__trace.frames, desc: window.__trace.desc, css: window.__trace.css } })
400
+ await p.close()
401
+ desc.push(...raw.desc)
402
+ const frames = expand(raw.frames)
403
+ if (!frames.length) throw new Error('No frames recorded. Check the root selector.')
404
+ const a = analyse(frames, actFrame)
405
+ const t0 = frames[0][0]
406
+ rep.frames = frames.length; rep.segments = a.segments
407
+ rep.issues.push(...a.issues.map(i => ({ k: i.k, at: i.ts ? `${((i.ts - t0) / 1000).toFixed(2)}s` : undefined, el: i.el != null ? desc[i.el] : undefined, d: i.d })))
408
+ for (const [key, ts] of Object.entries(raw.css || {})) { const [id, prop] = key.split('|'); rep.issues.push({ k: 'layout-anim', at: `${((ts - t0) / 1000).toFixed(2)}s`, el: desc[+id], d: `CSS animates ${prop}` }) }
409
+ if (interacts && !a.movedAfterAct) rep.issues.push({ k: 'no-response', d: `nothing moved after: ${rep.actions.join(', ')}` })
410
+ rep.issues.push(...uiIssues(uiRest, 'rest', mobile), ...uiIssues(uiEnd, 'after actions', mobile))
411
+ errs.forEach(e => rep.issues.push({ k: 'page-error', d: e }))
412
+
413
+ // C — reduced motion: the same run should barely move
414
+ if (reduced && a.dist > 60) {
415
+ onStep('reduced')
416
+ ;({ p } = await open(true, true))
417
+ const listC = acts.length ? acts : await autoActions(p, root)
418
+ await play(p, listC)
419
+ const rf = expand(await p.evaluate(() => { window.__trace.on = false; return window.__trace.frames })); await p.close()
420
+ const r = analyse(rf, -1)
421
+ rep.reduced = { normalPx: a.dist, reducedPx: r.dist, share: Math.round(r.dist / a.dist * 100) }
422
+ // movement is measured as total travel; under 30 % left means the page swapped motion for fades
423
+ if (r.dist > Math.max(60, a.dist * 0.3)) rep.issues.push({ k: 'ignores-reduced-motion', d: `${rep.reduced.share}% of the movement (${r.dist} of ${a.dist} px) still plays with prefers-reduced-motion: reduce` })
424
+ }
425
+ } catch (e) {
426
+ // could not load or drive the page at all: that is an error to fix, not a motion score
427
+ if (!rep.frames) rep.error = /ERR_CONNECTION_REFUSED|ERR_NAME_NOT_RESOLVED|Could not load/.test(e.message) ? `Could not open ${url}. Is the dev server running?` : String(e.message).slice(0, 240)
428
+ else rep.issues.push({ k: 'page-error', d: 'audit: ' + String(e.message).slice(0, 200) })
429
+ } finally { await browser.close() }
430
+ if (rep.error) { rep.status = 'ERROR'; rep.score = null; rep.blockers = []; return rep }
431
+
432
+ for (const i of rep.issues) i.fix = FIX[i.k]
433
+ const by = {}; for (const i of rep.issues) by[i.k] = (by[i.k] || 0) + (W[i.k] || 1)
434
+ let score = 100; for (const [k, v] of Object.entries(by)) score -= Math.min(v, CAP[k] ?? v)
435
+ rep.score = Math.max(0, score)
436
+ rep.blockers = [...new Set(rep.issues.filter(i => BLOCK.has(i.k)).map(i => i.k))]
437
+ rep.status = rep.blockers.length ? 'FAIL' : rep.score >= 85 ? 'PASS' : 'REVIEW'
438
+ return rep
439
+ }
440
+
441
+ // human-readable report, grouped by kind, blockers first
442
+ export function formatReport(r) {
443
+ if (r.status === 'ERROR') return `Phation audit · ERROR · ${r.url}\n${r.error}`
444
+ const L = [`Phation audit · ${r.status} ${r.score}/100 · ${r.url}`, `${r.viewport} · root ${r.root} · ${r.frames ?? 0} frames · ${r.dropped ?? '–'}% dropped · actions: ${r.actions.join(', ') || 'none'}`]
445
+ if (r.reduced) L.push(`reduced motion: ${r.reduced.share}% of the movement still plays (${r.reduced.reducedPx} of ${r.reduced.normalPx} px)`)
446
+ if (!r.issues.length) { L.push('', 'No issues. The motion meets the Phation Standard on this run.'); return L.join('\n') }
447
+ const groups = {}; for (const i of r.issues) (groups[i.k] = groups[i.k] || []).push(i)
448
+ const order = Object.keys(groups).sort((a, b) => (BLOCK.has(b) - BLOCK.has(a)) || (W[b] || 1) - (W[a] || 1))
449
+ for (const k of order) {
450
+ const g = groups[k]
451
+ L.push('', `${BLOCK.has(k) ? '✗' : '!'} ${k} (${g.length})${BLOCK.has(k) ? ' — blocker' : ''}`, ` fix: ${FIX[k] || ''}`)
452
+ for (const i of g.slice(0, 6)) L.push(` · ${i.at ? i.at.padStart(6) + ' ' : ''}${i.el ? i.el + ': ' : ''}${i.d}`)
453
+ if (g.length > 6) L.push(` · … ${g.length - 6} more`)
454
+ }
455
+ return L.join('\n')
456
+ }
package/bin/cli.mjs ADDED
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+ // Phation CLI, for projects without an AI agent.
3
+ // phation list [category]
4
+ // phation search <words…>
5
+ // phation show <slug>
6
+ // phation add <slug> [--from <studio link>] [--dir src/motion] [--public public] [--force]
7
+ // phation init [claude|cursor|codex|windsurf|vscode|all] [--force] install the Phation Standard for your agent
8
+ // phation standard [section] print the standard (or one section, e.g. springs)
9
+ // phation audit <url> [--do click:#buy]… [--root main] [--mobile] [--dark] [--json] [--shots dir] [--no-reduced]
10
+ // phation animate <file|folder> [--feel snappy] [--only press] [--role 12=button] [--apply] [--write] animate your own UI
11
+ // phation mcp start the MCP server (stdio)
12
+ // phation login <license-key> | logout | whoami Pro: add, audit, animate (https://phation.app/pricing)
13
+ import { ENTRIES, CATEGORIES, search, get, suggest, add, summary, install, standardSection, TOOLS, login, logout, licenseKey, requirePro, motionBlock } from '../lib.mjs'
14
+
15
+ const [cmd, ...rest] = process.argv.slice(2)
16
+ const flag = (n, d) => { const i = rest.indexOf(`--${n}`); return i < 0 ? d : rest[i + 1] }
17
+ const has = n => rest.includes(`--${n}`)
18
+ const args = rest.filter((a, i) => !a.startsWith('--') && !(i > 0 && rest[i - 1].startsWith('--') && !['--force', '--apply', '--write', '--json', '--mobile', '--dark', '--no-reduced'].includes(rest[i - 1])))
19
+ const row = e => ` ${e.slug.padEnd(26)} ${e.name}${e.interaction ? ` · ${e.interaction}` : ''}`
20
+
21
+ switch (cmd) {
22
+ case 'list': {
23
+ const c = args[0]
24
+ if (c && !CATEGORIES.some(x => x.toLowerCase() === c.toLowerCase())) { console.error(`Unknown category. Use one of: ${CATEGORIES.join(', ')}`); process.exit(1) }
25
+ for (const cat of CATEGORIES.filter(x => !c || x.toLowerCase() === c.toLowerCase())) {
26
+ const list = ENTRIES.filter(e => e.category === cat); if (!list.length) continue
27
+ console.log(`\n${cat}`); list.map(summary).forEach(e => console.log(row(e)))
28
+ }
29
+ break
30
+ }
31
+ case 'search': {
32
+ const hits = search(args.join(' '))
33
+ if (!hits.length) { console.log('Nothing matched. Try: phation list'); break }
34
+ hits.forEach(e => console.log(row(e)))
35
+ break
36
+ }
37
+ case 'show': {
38
+ const e = get(args[0])
39
+ if (!e) { console.error(`No entry "${args[0]}".${suggest(args[0] || '').length ? ' Did you mean: ' + suggest(args[0]).join(', ') + '?' : ''}`); process.exit(1) }
40
+ console.log(`${e.name} · ${e.category}\n${e.description}\n`)
41
+ for (const [k, v] of Object.entries(e.spec)) console.log(` ${k.padEnd(16)} ${v}`)
42
+ if (motionBlock(e)) console.log(`\n${motionBlock(e)}`)
43
+ console.log(`\n file ${e.file} · needs ${e.dependencies.join(', ')}${e.assets.length ? ` · ${e.assets.length} media file(s)` : ''}`)
44
+ console.log(` add npx phation add ${e.slug} (Pro)`)
45
+ break
46
+ }
47
+ case 'add': {
48
+ try {
49
+ const r = await add(args[0]?.startsWith('--') ? undefined : args[0], { dir: flag('dir', 'src/motion'), publicDir: flag('public', 'public'), force: has('force'), from: flag('from', undefined) })
50
+ console.log(`Added ${r.entry}:`); r.files.forEach(f => console.log(` + ${f}`))
51
+ if (r.tuned) console.log(`\nStudio values applied: ${r.tuned.applied.join(', ') || 'none'}${r.tuned.skipped.length ? ` (not in this file: ${r.tuned.skipped.join(', ')})` : ''}`)
52
+ if (r.install) console.log(`\nInstall: ${r.install}`)
53
+ console.log(`\nUse it:\n${r.usage.split('\n').map(l => ' ' + l).join('\n')}`)
54
+ } catch (e) { console.error(e.message); process.exit(1) }
55
+ break
56
+ }
57
+ case 'init': {
58
+ try {
59
+ const r = install(args[0] || 'all', { force: has('force') })
60
+ console.log(`Phation Standard v${r.version}`)
61
+ r.results.forEach(x => console.log(` ${x.state.startsWith('skipped') ? '!' : '+'} ${x.file.padEnd(48)} ${x.label} · ${x.state}`))
62
+ console.log('\nYour agent now follows the standard when it writes motion. Ask it to "add motion to …" or "review the motion in …".')
63
+ } catch (e) { console.error(e.message); process.exit(1) }
64
+ break
65
+ }
66
+ case 'audit': {
67
+ const url = rest.find(a => /^https?:\/\//.test(a))
68
+ if (!url) { console.error('Usage: phation audit <url> [--do click:#buy] [--do hover:.card] [--root main] [--mobile] [--json] [--shots dir] [--no-reduced]\nActions: click:<sel> hover:<sel> focus:<sel> scroll:<px> drag:<sel>:dx,dy hold:<sel>:ms key:<Key> type:<sel>:text wait:<ms>'); process.exit(1) }
69
+ const all = (n) => rest.flatMap((a, i) => a === `--${n}` && rest[i + 1] ? [rest[i + 1]] : [])
70
+ try { await requirePro() } catch (e) { console.error(e.message); process.exit(1) }
71
+ const { audit, formatReport } = await import('../audit.mjs')
72
+ if (!has('json')) console.error(`Auditing ${url} … (three runs: timing, trace, reduced motion)`)
73
+ const r = await audit(url, { actions: all('do'), root: flag('root', null), mobile: has('mobile'), dark: has('dark'), shots: flag('shots', null), reduced: !has('no-reduced') })
74
+ console.log(has('json') ? JSON.stringify(r, null, 2) : formatReport(r))
75
+ process.exit(r.status === 'ERROR' ? 1 : r.status === 'FAIL' ? 2 : 0)
76
+ }
77
+ case 'animate': { // phation animate <file|folder> [--feel snappy] [--only press,sheet-open] [--apply] [--write]
78
+ if (!args[0]) { console.error('Usage: phation animate <file|folder> [--feel fluid|calm|snappy|playful|heavy|mechanical] [--only press,list-enter] [--role 12=button]… [--apply] [--write]'); process.exit(1) }
79
+ try {
80
+ await requirePro()
81
+ const { animate } = await import('../animate/index.mjs')
82
+ const roles = Object.fromEntries(rest.flatMap((a, i) => a === '--role' && rest[i + 1] ? [rest[i + 1].split('=')] : []))
83
+ const only = flag('only', undefined)?.split(',')
84
+ const r = animate(args[0], { feel: flag('feel', undefined), only, roles, apply: has('apply'), write: has('write') })
85
+ console.log(r.text)
86
+ } catch (e) { console.error(e.message); process.exit(1) }
87
+ break
88
+ }
89
+ case 'standard': {
90
+ const s = standardSection(args.join(' '))
91
+ if (!s) { console.error(`No section "${args.join(' ')}". Try: principles, tokens, curves, springs, durations, stagger, recipes, never, ui, accessibility, code, workflow`); process.exit(1) }
92
+ console.log(s)
93
+ break
94
+ }
95
+ case 'login': {
96
+ if (!args[0]) { console.error('Usage: phation login <license-key> (the key is in your Polar receipt email)'); process.exit(1) }
97
+ try { const r = await login(args[0]); console.log(`Signed in: ${r.email || 'Pro'} · ${r.kind}${r.until ? ` until ${r.until.slice(0, 10)}` : ''}\nSaved to ${r.file}`) } catch (e) { console.error(e.message); process.exit(1) }
98
+ break
99
+ }
100
+ case 'logout': console.log(`Removed ${logout()}`); break
101
+ case 'whoami': {
102
+ if (!licenseKey()) { console.log('Free (no license). Pro: https://phation.app/pricing then phation login <key>'); break }
103
+ try { const r = await login(licenseKey()); console.log(`Pro · ${r.email || ''} · ${r.kind}${r.until ? ` until ${r.until.slice(0, 10)}` : ''}`) } catch (e) { console.error(e.message); process.exit(1) }
104
+ break
105
+ }
106
+ case 'mcp': { // `npx -y phation mcp` starts the MCP server over stdio
107
+ await import('./server.mjs')
108
+ break
109
+ }
110
+ default:
111
+ console.log(`phation list [category] | search <words> | show <slug> | add <slug> [--from <studio link>] [--dir src/motion] [--public public] [--force]\n init [${Object.keys(TOOLS).filter(k => !TOOLS[k].hidden).join('|')}|all] [--force] | standard [section]\n audit <url> [--do click:#buy]… [--root sel] [--mobile] [--json]\n animate <file|folder> [--feel fluid] [--only press] [--apply] [--write]\n mcp (start the MCP server) | login <license-key> | logout | whoami\n\nFree: list, search, show, standard, init. Pro: add, audit, animate.`)
112
+ if (cmd && cmd !== 'help') process.exit(1)
113
+ }