@ultimat3/cli 31.52.0 → 31.53.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.
Files changed (111) hide show
  1. package/CLAUDE.md +1 -1
  2. package/package.json +29 -29
  3. package/src/app-kit-disk.ts +39 -0
  4. package/src/app-kit-forms.ts +27 -0
  5. package/src/app-kit.ts +146 -0
  6. package/src/budgets.ts +3 -1
  7. package/src/cdp-shot-driver-screen.ts +72 -0
  8. package/src/cdp-shot-driver.ts +17 -1
  9. package/src/cmd-design-capture.ts +210 -0
  10. package/src/cmd-design-errors.ts +50 -0
  11. package/src/cmd-design-paths.ts +47 -0
  12. package/src/cmd-design-publish.ts +64 -0
  13. package/src/cmd-design-run.ts +229 -0
  14. package/src/cmd-design-spec.ts +47 -0
  15. package/src/cmd-design-theme.ts +107 -0
  16. package/src/cmd-design-url.ts +201 -0
  17. package/src/cmd-design.ts +188 -0
  18. package/src/cmd-doctor.ts +3 -0
  19. package/src/cmd-generate-spec.ts +5 -0
  20. package/src/cmd-generate.ts +3 -1
  21. package/src/cmd-kit-spec.ts +13 -0
  22. package/src/cmd-kit.ts +133 -0
  23. package/src/cmd-shot-against.ts +275 -0
  24. package/src/cmd-shot-spec.ts +9 -1
  25. package/src/cmd-shot.ts +19 -0
  26. package/src/cmd-upgrade.ts +11 -0
  27. package/src/codemods/agent-kit.ts +130 -0
  28. package/src/codemods/agents-md-budget.ts +47 -0
  29. package/src/codemods/docs-visual-quality.ts +198 -0
  30. package/src/codemods/index.ts +8 -0
  31. package/src/codemods/settings-kit-allow.ts +49 -0
  32. package/src/design-extract-script.ts +187 -0
  33. package/src/design-extract.ts +311 -0
  34. package/src/design-map-colors.ts +180 -0
  35. package/src/design-map.ts +288 -0
  36. package/src/doctor-kit.ts +25 -0
  37. package/src/error-catalog.ts +4 -2
  38. package/src/error-codes-kit.ts +24 -0
  39. package/src/error-codes.ts +12 -10
  40. package/src/generate-files.ts +31 -1
  41. package/src/guards-shipped-names.ts +5 -0
  42. package/src/kit/agent-audit.ts +56 -0
  43. package/src/kit/agent-data.ts +32 -0
  44. package/src/kit/agent-server.ts +34 -0
  45. package/src/kit/agent-shape.ts +61 -0
  46. package/src/kit/agent-web.ts +49 -0
  47. package/src/kit/design-map.ts +106 -0
  48. package/src/kit/managed.ts +12 -0
  49. package/src/kit/registry.ts +89 -0
  50. package/src/kit/skill-design-research.ts +119 -0
  51. package/src/kit/skill-feature.ts +166 -0
  52. package/src/kit/skill-planx.ts +140 -0
  53. package/src/kit/skill-upgrade.ts +94 -0
  54. package/src/kit/skill-verify.ts +80 -0
  55. package/src/mcp-errors.ts +5 -0
  56. package/src/mcp-ui-diff.ts +13 -38
  57. package/src/mcp-ui.ts +30 -1
  58. package/src/messages-design.ts +104 -0
  59. package/src/messages-upgrade.ts +9 -0
  60. package/src/messages.ts +2 -0
  61. package/src/registry.ts +4 -0
  62. package/src/shot-diff.ts +96 -0
  63. package/src/shot-gpu.ts +17 -5
  64. package/src/templates/guard-animated-layout-script.ts +173 -0
  65. package/src/templates/guard-effect-without-fallback.ts +117 -0
  66. package/src/templates/guard-motion-adapter.ts +161 -0
  67. package/src/templates/guard-raw-frame-loop.ts +134 -0
  68. package/src/templates/guard-raw-motion-script.ts +132 -0
  69. package/src/templates/guard-raw-motion-ts-scan.ts +95 -0
  70. package/src/templates/guard-released-forms.ts +10 -0
  71. package/src/templates/index.ts +1 -2
  72. package/src/templates/island.ts +55 -8
  73. package/src/templates/kit-released-forms.ts +64 -0
  74. package/src/templates/motion-scale.ts +115 -0
  75. package/src/templates/scaffold-claude.ts +39 -26
  76. package/src/templates/scaffold-design.ts +41 -0
  77. package/src/templates/scaffold-docs.ts +31 -7
  78. package/src/templates/scaffold-guards.ts +31 -2
  79. package/src/templates/scaffold-verify-floor.ts +3 -0
  80. package/src/templates/shapes/blog-site.ts +15 -0
  81. package/src/templates/shapes/blog.ts +2 -0
  82. package/src/templates/shapes/content-site.ts +13 -0
  83. package/src/templates/shapes/content.ts +2 -0
  84. package/src/templates/shapes/dashboard-detail.ts +2 -0
  85. package/src/templates/shapes/dashboard-motion.ts +284 -0
  86. package/src/templates/shapes/dashboard.ts +19 -1
  87. package/src/templates/shapes/landing-motion.ts +67 -0
  88. package/src/templates/shapes/saas.ts +4 -0
  89. package/src/upgrade-gate.ts +14 -2
  90. package/src/upgrade-kit.ts +65 -0
  91. package/src/upgrade-report-kit.ts +28 -0
  92. package/src/upgrade-report.ts +3 -0
  93. package/src/verify-checks.ts +9 -1
  94. package/src/workspace-checks.ts +3 -3
  95. package/wiki/Agents.md +33 -1
  96. package/wiki/CLI-Reference-Tools.md +24 -3
  97. package/wiki/CLI-Reference.md +4 -2
  98. package/wiki/Design-Research.md +96 -0
  99. package/wiki/Effects.md +83 -0
  100. package/wiki/FAQ.md +1 -1
  101. package/wiki/Getting-Started.md +1 -1
  102. package/wiki/Home.md +2 -2
  103. package/wiki/Known-Gaps.md +3 -2
  104. package/wiki/MCP-And-AI.md +4 -0
  105. package/wiki/Motion.md +85 -0
  106. package/wiki/Project-Layout.md +1 -1
  107. package/wiki/Tutorial-02-First-Feature.md +1 -1
  108. package/wiki/UI-Components.md +2 -0
  109. package/wiki/Upgrading.md +4 -2
  110. package/src/templates/scaffold-claude-agents.ts +0 -161
  111. package/src/templates/scaffold-claude-commands.ts +0 -239
@@ -0,0 +1,96 @@
1
+ // Two captures compared, the shared half of `ui.diff` and `x shot --against`: decode both PNGs
2
+ // through `@ultimat3/core`'s raw-pixel seam, count what changed by `ui-diff.ts`'s rule, and encode the
3
+ // diff picture. No file paths and no error codes — each caller gates its own paths and sizes.
4
+
5
+ import type { Raster } from '@ultimat3/core';
6
+ import {
7
+ decodeImage,
8
+ encodeImage,
9
+ ImageUnsupportedError,
10
+ transformImageBytes,
11
+ } from '@ultimat3/core';
12
+ import type { UiInspectBox } from '@ultimat3/mcp';
13
+ import { changedPercent, diffPixels } from './ui-diff';
14
+
15
+ /**
16
+ * The seam reads 8-bit RGBA and nothing else. A PNG in any other shape — Chrome's RGB when the page
17
+ * is opaque, a palette from an optimiser — goes once through Bun's codecs, which always write the
18
+ * shape the seam reads. Only `imageUnsupported` is retried that way: a truncated file is a
19
+ * truncated file in either decoder.
20
+ */
21
+ export async function decodeCapture(bytes: Uint8Array): Promise<Raster> {
22
+ try {
23
+ return decodeImage(bytes);
24
+ } catch (error) {
25
+ if (!(error instanceof ImageUnsupportedError)) throw error;
26
+ return decodeImage(await transformImageBytes(bytes, { format: 'png' }));
27
+ }
28
+ }
29
+
30
+ /** Eight hex digits of the path's 64-bit hash: enough to keep two diffs of one `after` apart. */
31
+ export const hash8 = (text: string): string =>
32
+ Bun.hash(text).toString(16).padStart(16, '0').slice(0, 8);
33
+
34
+ /**
35
+ * `raster` on a `width`×`height` canvas, top-left, the rest transparent. A reference shot and a
36
+ * route shot are both full-page and almost never one height: the part only one of them covers is
37
+ * a difference, so it is compared as one rather than cropped away.
38
+ */
39
+ export function padRaster(raster: Raster, width: number, height: number): Raster {
40
+ if (raster.width === width && raster.height === height) return raster;
41
+ const pixels = new Uint8ClampedArray(width * height * 4);
42
+ const rows = Math.min(raster.height, height);
43
+ const rowBytes = Math.min(raster.width, width) * 4;
44
+ for (let y = 0; y < rows; y += 1) {
45
+ const from = y * raster.width * 4;
46
+ pixels.set(raster.pixels.subarray(from, from + rowBytes), y * width * 4);
47
+ }
48
+ return { width, height, pixels };
49
+ }
50
+
51
+ /** The unchanged share of the canvas, four decimals; an empty canvas is identical to itself. */
52
+ export function similarityOf(changed: number, width: number, height: number): number {
53
+ const total = width * height;
54
+ if (total === 0) return 1;
55
+ return Math.round((1 - changed / total) * 10_000) / 10_000;
56
+ }
57
+
58
+ export interface CaptureDiff {
59
+ readonly width: number;
60
+ readonly height: number;
61
+ readonly changedPixels: number;
62
+ readonly changedPercent: number;
63
+ readonly changedBox: UiInspectBox | null;
64
+ /** `1` is identical, `0` is every pixel changed. */
65
+ readonly similarity: number;
66
+ /** The diff picture: the faded `after` with every changed pixel red. */
67
+ readonly diffPng: Uint8Array;
68
+ }
69
+
70
+ /** Two decoded captures, compared on the larger of their two canvases. */
71
+ export function compareRasters(before: Raster, after: Raster, threshold: number): CaptureDiff {
72
+ const width = Math.max(before.width, after.width);
73
+ const height = Math.max(before.height, after.height);
74
+ const a = padRaster(before, width, height);
75
+ const b = padRaster(after, width, height);
76
+ const result = diffPixels(a.pixels, b.pixels, width, height, threshold);
77
+ return {
78
+ width,
79
+ height,
80
+ changedPixels: result.changedPixels,
81
+ changedPercent: changedPercent(result.changedPixels, width, height),
82
+ changedBox: result.changedBox,
83
+ similarity: similarityOf(result.changedPixels, width, height),
84
+ diffPng: encodeImage({ width, height, pixels: result.diffRgba }),
85
+ };
86
+ }
87
+
88
+ /** Two PNGs' bytes, decoded and compared. */
89
+ export async function compareCaptures(
90
+ before: Uint8Array,
91
+ after: Uint8Array,
92
+ threshold: number,
93
+ ): Promise<CaptureDiff> {
94
+ const [a, b] = await Promise.all([decodeCapture(before), decodeCapture(after)]);
95
+ return compareRasters(a, b, threshold);
96
+ }
package/src/shot-gpu.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  // The GPU backend the photographed page could reach, read from `navigator.gpu` inside the page.
2
+ // The same page is asked for WebGL2 beside it, because `@ultimat3/effects` picks its backend on it.
2
3
  // A WebGPU canvas that came out blank on a headless machine with no adapter is a fact about the
3
4
  // machine, not the app — and a picture alone cannot tell the two apart. Recorded, never gating.
4
5
 
@@ -7,6 +8,8 @@ import { t, validate } from '@ultimat3/schema';
7
8
  import type { JsonValue } from './output';
8
9
 
9
10
  export interface ShotGpu {
11
+ /** A `webgl2` context could be made on a canvas and was not lost — the shader tier of an effect. */
12
+ readonly webgl2: boolean;
10
13
  /** `navigator.gpu` exists — the browser exposes WebGPU at all. */
11
14
  readonly api: boolean;
12
15
  /** `requestAdapter()` answered an adapter: WebGPU is usable on this page, on this machine. */
@@ -24,17 +27,20 @@ export interface ShotGpu {
24
27
  * spell the flag `isFallbackAdapter` on the adapter, which is why both are read.
25
28
  */
26
29
  export const GPU_PROBE =
27
- '(async function(){var g=navigator.gpu;' +
28
- 'if(!g)return{api:false,available:false,adapter:null,fallback:false};var a=null;' +
30
+ '(async function(){var w=false;' +
31
+ 'try{var c=document.createElement("canvas").getContext("webgl2");' +
32
+ 'w=!!c&&!c.isContextLost();}catch(e){w=false;}var g=navigator.gpu;' +
33
+ 'if(!g)return{api:false,webgl2:w,available:false,adapter:null,fallback:false};var a=null;' +
29
34
  'try{a=await Promise.race([g.requestAdapter(),' +
30
35
  'new Promise(function(r){setTimeout(function(){r(null);},2000);})]);}catch(e){a=null;}' +
31
- 'if(!a)return{api:true,available:false,adapter:null,fallback:false};var i=a.info||{};' +
36
+ 'if(!a)return{api:true,webgl2:w,available:false,adapter:null,fallback:false};var i=a.info||{};' +
32
37
  'var n=[i.vendor,i.architecture,i.device,i.description].filter(function(s){return !!s;})' +
33
- '.join(" ");return{api:true,available:true,adapter:n===""?null:n,' +
38
+ '.join(" ");return{api:true,webgl2:w,available:true,adapter:n===""?null:n,' +
34
39
  'fallback:!!(a.isFallbackAdapter||i.isFallbackAdapter)};})()';
35
40
 
36
41
  const gpuProbeSchema: StandardSchemaV1<unknown, ShotGpu> = t.object({
37
42
  api: t.boolean,
43
+ webgl2: t.boolean,
38
44
  available: t.boolean,
39
45
  adapter: t.nullable(t.string),
40
46
  fallback: t.boolean,
@@ -58,4 +64,10 @@ export const readShotGpu = (page: {
58
64
  export const gpuJson = (gpu: ShotGpu | null | undefined): JsonValue =>
59
65
  gpu === null || gpu === undefined
60
66
  ? null
61
- : { api: gpu.api, available: gpu.available, adapter: gpu.adapter, fallback: gpu.fallback };
67
+ : {
68
+ api: gpu.api,
69
+ webgl2: gpu.webgl2,
70
+ available: gpu.available,
71
+ adapter: gpu.adapter,
72
+ fallback: gpu.fallback,
73
+ };
@@ -0,0 +1,173 @@
1
+ // The `animated-layout-script` guard: `animated-layout-property`'s rule for TypeScript. A layout
2
+ // property handed to `.animate(` costs a layout or paint pass per frame; a box that must move
3
+ // through the layout is `layout()` from `@ultimat3/ui/motion`. A guard of its own, REPORT ONLY
4
+ // (`severity: 'warning'`), because `animated-layout-property` gates and a stricter rule on `main`
5
+ //
6
+ // is a break; `x new` writes the `"error"` row.
7
+
8
+ import { guardCode } from './guard';
9
+ import { TS_ANIMATE_SCAN_SOURCE } from './guard-raw-motion-ts-scan';
10
+ import type { GeneratedFile } from './naming';
11
+
12
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
13
+ const NAME = 'animated-layout-script';
14
+ const CODE = guardCode(NAME);
15
+
16
+ const source =
17
+ (): string => `// animated-layout-script: an animation moves transform and opacity, never the layout.
18
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
19
+ // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
20
+ //
21
+ // Read: a layout property (\`width\`, \`marginLeft\`, \`'box-shadow'\`) as a KEY of the keyframes a
22
+ // \`.animate(\` call is given (its first argument), in a script outside tests. REPORT ONLY (\`severity: 'warning'\`).
23
+
24
+ import type { Finding, Guard } from '@ultimat3/cli';
25
+
26
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
27
+ const CODE = '${CODE}';
28
+
29
+ /** What each layout property should have been, so the fix is an edit and not a category. */
30
+ const INSTEAD = new Map([
31
+ ['top', 'transform: translateY(…)'],
32
+ ['bottom', 'transform: translateY(…)'],
33
+ ['left', 'transform: translateX(…)'],
34
+ ['right', 'transform: translateX(…)'],
35
+ ['inset', 'transform: translate(…)'],
36
+ ['width', 'transform: scaleX(…)'],
37
+ ['height', 'transform: scaleY(…)'],
38
+ ['box-shadow', 'opacity on a shadow layer that is already painted'],
39
+ ]);
40
+
41
+ /** A property whose change the browser cannot composite: it re-lays-out or re-paints the frame. */
42
+ const isLayoutProperty = (property: string): boolean =>
43
+ INSTEAD.has(property) ||
44
+ property.startsWith('margin') ||
45
+ property.startsWith('padding') ||
46
+ /^(?:min|max)-(?:width|height)$/.test(property);
47
+
48
+ ${TS_ANIMATE_SCAN_SOURCE}
49
+ /**
50
+ * A keyframe key: \`width\`, \`'margin-left'\`, \`marginLeft\` — spelled either way in a script, and
51
+ * only in KEY position (after \`{\` or \`,\`): \`up ? top : bottom\` is a value, not a key.
52
+ */
53
+ const KEYFRAME_KEY = /(?<=[{,]\\s*)(['"]?)([A-Za-z][\\w-]*)\\1\\s*:(?!:)/g;
54
+
55
+ /** The text up to a call's first top-level comma: the keyframes, never the options object. */
56
+ const firstArgument = (body: string): string => {
57
+ let depth = 0;
58
+ let quote = '';
59
+ for (let i = 0; i < body.length; i += 1) {
60
+ const ch = body[i] ?? '';
61
+ if (quote !== '') {
62
+ if (ch === '\\\\') i += 1;
63
+ else if (ch === quote) quote = '';
64
+ } else if (ch === "'" || ch === '"' || ch === '\`') quote = ch;
65
+ else if ('([{'.includes(ch)) depth += 1;
66
+ else if (')]}'.includes(ch)) depth -= 1;
67
+ else if (ch === ',' && depth === 0) return body.slice(0, i);
68
+ }
69
+ return body;
70
+ };
71
+
72
+ /** Whether \`index\` sits inside a string literal; a quoted key's opening quote does not. */
73
+ const insideString = (text: string, index: number): boolean => {
74
+ let quote = '';
75
+ for (let i = 0; i < index; i += 1) {
76
+ const ch = text[i] ?? '';
77
+ if (quote !== '') {
78
+ if (ch === '\\\\') i += 1;
79
+ else if (ch === quote) quote = '';
80
+ } else if (ch === "'" || ch === '"' || ch === '\`') quote = ch;
81
+ }
82
+ return quote !== '';
83
+ };
84
+ const kebab = (key: string): string => key.replaceAll(/[A-Z]/g, (ch) => \`-\${ch.toLowerCase()}\`);
85
+
86
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
87
+ export function animatedLayoutScripts(files: readonly ScriptFile[]): readonly Finding[] {
88
+ const findings: Finding[] = [];
89
+ for (const file of files) {
90
+ if (!isAppScript(file.path)) continue;
91
+ const text = blankScriptComments(file.source);
92
+ for (const call of animateCalls(text)) {
93
+ const keyframes = firstArgument(call.body);
94
+ for (const match of keyframes.matchAll(KEYFRAME_KEY)) {
95
+ if (insideString(keyframes, match.index)) continue;
96
+ const property = kebab(match[2] ?? '');
97
+ if (!isLayoutProperty(property)) continue;
98
+ const at = \`\${file.path}:\${scriptLineOf(text, call.start + match.index)}\`;
99
+ findings.push({
100
+ code: CODE,
101
+ cause: \`\${at} animates \${property} in a keyframe object — only transform and opacity are compositor-only, so every frame of this costs a full layout or paint pass on the same main thread the app runs on\`,
102
+ fix: \`animate the box with layout() — import { layout } from '@ultimat3/ui/motion' — or \${INSTEAD.get(property) ?? 'transform or opacity'} instead of \${property} at \${at}, then: x verify --only boundaries\`,
103
+ at,
104
+ });
105
+ }
106
+ }
107
+ }
108
+ return findings;
109
+ }
110
+
111
+ export const guard: Guard = {
112
+ summary: 'a script animation moves transform and opacity, never the layout',
113
+ severity: 'warning',
114
+ async check(_root, sources) {
115
+ const scripts = await sources.files('{apps,packages}/**/*.{ts,tsx}');
116
+ return animatedLayoutScripts(scripts.map((file) => ({ path: file.path, source: file.text })));
117
+ },
118
+ };
119
+ `;
120
+
121
+ const test =
122
+ (): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
123
+ // a green gate over the convention it was written to enforce.
124
+
125
+ import { expect, unitTest } from '@ultimat3/testing';
126
+ import { animatedLayoutScripts } from './animated-layout-script';
127
+
128
+ const script = (source: string) => [{ path: 'apps/web/app/feed/card.island.tsx', source }];
129
+
130
+ unitTest('a layout key in .animate( is refused in any spelling, and layout() is named', () => {
131
+ const findings = animatedLayoutScripts(
132
+ script('el.animate({ width: [0], marginLeft: 4, "box-shadow": x }, { duration: t });'),
133
+ );
134
+ expect(findings).toHaveLength(3);
135
+ expect(findings[0]?.code).toBe('${CODE}');
136
+ expect(findings[0]?.fix).toStartWith('animate the box with layout() — ');
137
+ expect(findings[0]?.at).toBe('apps/web/app/feed/card.island.tsx:1');
138
+ });
139
+
140
+ unitTest('only keyframe keys count: values, strings and the options object are silent', () => {
141
+ const silent = [
142
+ 'el.animate({ transform: up ? top : bottom }, { duration: t });',
143
+ "el.animate({ id: 'width: grow' }, { duration: t });",
144
+ 'el.animate({ opacity: 1 }, { duration: t, top: 1, width: 2 });',
145
+ "el.animate({ label: 'a, left: 1' }, o);",
146
+ ];
147
+ for (const source of silent) expect(animatedLayoutScripts(script(source))).toEqual([]);
148
+ const array = script('el.animate([{ left: 0 }, { left: 9 }], { duration: t });');
149
+ expect(animatedLayoutScripts(array)).toHaveLength(2);
150
+ });
151
+
152
+ unitTest('a comment-like string does not hide the call after it', () => {
153
+ const source = "const g = 'dist/*'; el.animate({ width: 1 }, o); /** doc */";
154
+ expect(animatedLayoutScripts(script(source))).toHaveLength(1);
155
+ });
156
+
157
+ unitTest('transform, opacity, other calls, a comment and a test file are silent', () => {
158
+ expect(
159
+ animatedLayoutScripts(script('el.animate({ transform: "none" }, { duration: t });')),
160
+ ).toEqual([]);
161
+ expect(animatedLayoutScripts(script('place({ width: 10, left: 4 });'))).toEqual([]);
162
+ expect(animatedLayoutScripts(script('// el.animate({ width: 1 });'))).toEqual([]);
163
+ expect(
164
+ animatedLayoutScripts([{ path: 'apps/web/card.test.ts', source: 'el.animate({ width: 1 });' }]),
165
+ ).toEqual([]);
166
+ });
167
+ `;
168
+
169
+ /** `guards/animated-layout-script.ts` and its test. The directory registers it. */
170
+ export const animatedLayoutScriptGuardFiles = (): readonly GeneratedFile[] => [
171
+ { path: `guards/${NAME}.ts`, contents: source() },
172
+ { path: `guards/${NAME}.test.ts`, contents: test() },
173
+ ];
@@ -0,0 +1,117 @@
1
+ // The `effect-without-fallback` guard: a GPU or canvas effect is `EffectCanvas` from
2
+ // `@ultimat3/effects`, whose `fallback` is required by type. A raw `<canvas`, a WebGL context or
3
+ // `navigator.gpu` in a page is an effect with no static frame: blank under reduced motion, no
4
+ // WebGL, a lost context, and in every screenshot and server-rendered byte. REPORT ONLY in an app
5
+ //
6
+ // that predates it (`severity: 'warning'`); `x new` writes the `"error"` row.
7
+
8
+ import { guardCode } from './guard';
9
+ import { TS_BLANK_SOURCE } from './guard-raw-motion-ts-scan';
10
+ import type { GeneratedFile } from './naming';
11
+
12
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
13
+ const NAME = 'effect-without-fallback';
14
+ const CODE = guardCode(NAME);
15
+
16
+ const source =
17
+ (): string => `// effect-without-fallback: a canvas or GPU effect is EffectCanvas, whose fallback is required.
18
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
19
+ // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
20
+ //
21
+ // Read: \`<canvas\`, \`getContext('webgl…')\` and \`navigator.gpu\` in a \`.tsx\` outside tests. A canvas
22
+ // the app draws is
23
+ // \`<EffectCanvas draw={…} fallback={…} />\`. REPORT ONLY (\`severity: 'warning'\`) until clean.
24
+
25
+ import type { Finding, Guard } from '@ultimat3/cli';
26
+
27
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
28
+ const CODE = '${CODE}';
29
+
30
+ export interface SourceFile {
31
+ /** App-root-relative POSIX path, so the finding names the file an author opens. */
32
+ readonly path: string;
33
+ readonly source: string;
34
+ }
35
+
36
+ const SIGNATURES: readonly (readonly [RegExp, string])[] = [
37
+ [/<canvas\\b/g, 'a <canvas>'],
38
+ [/getContext\\s*\\(\\s*(['"\`])webgl/g, 'a WebGL context'],
39
+ [/(?<![\\w$])navigator\\s*\\.\\s*gpu\\b/g, 'navigator.gpu'],
40
+ ];
41
+
42
+ ${TS_BLANK_SOURCE}
43
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
44
+ export function effectsWithoutFallback(files: readonly SourceFile[]): readonly Finding[] {
45
+ const findings: Finding[] = [];
46
+ for (const file of files) {
47
+ const text = blankScript(file.source);
48
+ for (const [pattern, name] of SIGNATURES) {
49
+ for (const match of text.matchAll(pattern)) {
50
+ const at = \`\${file.path}:\${text.slice(0, match.index).split('\\n').length}\`;
51
+ findings.push({
52
+ code: CODE,
53
+ cause: \`\${at} draws with \${name} outside EffectCanvas — no static frame stands in when motion is reduced, WebGL is missing or the context is lost\`,
54
+ fix: \`render <EffectCanvas draw={…} fallback={…} /> — import { EffectCanvas } from '@ultimat3/effects' — at \${at} (a ready-made effect such as ShaderBackground needs no canvas of yours), then: x verify --only boundaries\`,
55
+ at,
56
+ });
57
+ }
58
+ }
59
+ }
60
+ return findings.sort((a, b) => (a.at ?? '').localeCompare(b.at ?? '', 'en', { numeric: true }));
61
+ }
62
+
63
+ export const guard: Guard = {
64
+ summary: 'a canvas or GPU effect is EffectCanvas, whose fallback is required, never a raw canvas',
65
+ severity: 'warning',
66
+ async check(_root, sources) {
67
+ const code = await sources.files('{apps,packages}/**/*.tsx');
68
+ return effectsWithoutFallback(
69
+ code
70
+ .filter((file) => !/\\.(?:test|spec)\\.tsx$/.test(file.path))
71
+ .map((file) => ({ path: file.path, source: file.text })),
72
+ );
73
+ },
74
+ };
75
+ `;
76
+
77
+ const test =
78
+ (): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
79
+ // a green gate over the convention it was written to enforce.
80
+
81
+ import { expect, unitTest } from '@ultimat3/testing';
82
+ import { effectsWithoutFallback } from './effect-without-fallback';
83
+
84
+ const file = (source: string, path = 'apps/web/app/feed/orb.island.tsx') => [{ path, source }];
85
+
86
+ unitTest('a raw canvas is refused at its line, and the fix names EffectCanvas', () => {
87
+ const findings = effectsWithoutFallback(file('const a = 1;\\nexport const V = () => <canvas />;'));
88
+ expect(findings).toHaveLength(1);
89
+ expect(findings[0]?.code).toBe('${CODE}');
90
+ expect(findings[0]?.at).toBe('apps/web/app/feed/orb.island.tsx:2');
91
+ expect(findings[0]?.fix).toContain('EffectCanvas');
92
+ });
93
+
94
+ unitTest('a WebGL context and navigator.gpu are the same rule', () => {
95
+ expect(effectsWithoutFallback(file("const gl = el.getContext('webgl2');"))).toHaveLength(1);
96
+ expect(effectsWithoutFallback(file('const gl = el.getContext("webgl");'))).toHaveLength(1);
97
+ expect(effectsWithoutFallback(file('const gpu = navigator.gpu;'))).toHaveLength(1);
98
+ });
99
+
100
+ unitTest('a comment-like string hides nothing: the canvas after it is still refused', () => {
101
+ expect(effectsWithoutFallback(file("const u = '//cdn'; const v = <canvas />;"))).toHaveLength(1);
102
+ });
103
+
104
+ unitTest('EffectCanvas, a 2d context, a comment and a string are silent', () => {
105
+ expect(effectsWithoutFallback(file('<EffectCanvas draw={d} fallback={<img />} />'))).toEqual([]);
106
+ expect(effectsWithoutFallback(file("const c = el.getContext('2d');"))).toEqual([]);
107
+ expect(effectsWithoutFallback(file('// <canvas /> navigator.gpu'))).toEqual([]);
108
+ const hidden = file("const s = '/* x */'; const t = <canvas />;");
109
+ expect(effectsWithoutFallback(hidden)).toHaveLength(1);
110
+ });
111
+ `;
112
+
113
+ /** `guards/effect-without-fallback.ts` and its test. The directory registers it. */
114
+ export const effectWithoutFallbackGuardFiles = (): readonly GeneratedFile[] => [
115
+ { path: `guards/${NAME}.ts`, contents: source() },
116
+ { path: `guards/${NAME}.test.ts`, contents: test() },
117
+ ];
@@ -0,0 +1,161 @@
1
+ // The `motion-adapter` guard: motion and GPU effects go through `@ultimat3/ui/motion` and
2
+ // `@ultimat3/effects`, never a second engine imported into app code. Every engine here is the
3
+ // framework's own (WAAPI for motion, a WebGL2 mount for shaders); a second one is a second tempo,
4
+ // a second reduced-motion story and a second bundle graph nobody budgeted. REPORT ONLY in an app
5
+ //
6
+ // that predates it (`severity: 'warning'`); `x new` writes the `"error"` row.
7
+
8
+ import { guardCode } from './guard';
9
+ import { TS_BLANK_SOURCE } from './guard-raw-motion-ts-scan';
10
+ import type { GeneratedFile } from './naming';
11
+
12
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
13
+ const NAME = 'motion-adapter';
14
+ const CODE = guardCode(NAME);
15
+
16
+ const source =
17
+ (): string => `// motion-adapter: motion and GPU effects come from the framework's adapter, never a direct engine.
18
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
19
+ // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
20
+ //
21
+ // Read: an import, re-export, \`import()\` or \`require()\` of an engine's package or one of its
22
+ // subpaths, in a script outside tests. REPORT ONLY (\`severity: 'warning'\`): listed, never red,
23
+ // until an app is clean of it; \`"error"\` in \`guards/shipped.json\` makes it gate.
24
+
25
+ import type { Finding, Guard } from '@ultimat3/cli';
26
+
27
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
28
+ const CODE = '${CODE}';
29
+
30
+ const MOTION_FIX =
31
+ "animate, stagger, inView, scrollLinked, layout, Presence from '@ultimat3/ui/motion'";
32
+ const GPU_FIX =
33
+ "ShaderBackground, EffectCanvas or another effect from '@ultimat3/effects' (its static frame is the fallback)";
34
+
35
+ /** Package → the framework surface that does its job. */
36
+ const ENGINES: Readonly<Record<string, string>> = {
37
+ motion: MOTION_FIX,
38
+ 'motion-dom': MOTION_FIX,
39
+ 'framer-motion': MOTION_FIX,
40
+ gsap: MOTION_FIX,
41
+ animejs: MOTION_FIX,
42
+ 'solid-motionone': MOTION_FIX,
43
+ 'solid-transition-group': "Presence, PresenceList from '@ultimat3/ui/motion'",
44
+ '@paper-design/shaders': GPU_FIX,
45
+ shaders: GPU_FIX,
46
+ ogl: GPU_FIX,
47
+ three: GPU_FIX,
48
+ };
49
+
50
+ export interface ScriptFile {
51
+ /** App-root-relative POSIX path, so the finding names the file an author opens. */
52
+ readonly path: string;
53
+ readonly source: string;
54
+ }
55
+
56
+ const SPECIFIER = /(?:\\bfrom\\s*|\\bimport\\s*\\(?\\s*|\\brequire\\s*\\(\\s*)(['"])([^'"\\n]+)\\1/g;
57
+
58
+ /** \`three/examples/jsm/x\` → \`three\`; \`@paper-design/shaders/react\` → \`@paper-design/shaders\`. */
59
+ const packageOf = (specifier: string): string =>
60
+ specifier
61
+ .split('/')
62
+ .slice(0, specifier.startsWith('@') ? 2 : 1)
63
+ .join('/');
64
+
65
+ ${TS_BLANK_SOURCE}
66
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
67
+ export function motionAdapter(files: readonly ScriptFile[]): readonly Finding[] {
68
+ const findings: Finding[] = [];
69
+ for (const file of files) {
70
+ const text = blankScript(file.source);
71
+ for (const match of text.matchAll(SPECIFIER)) {
72
+ const engine = packageOf(match[2] ?? '');
73
+ if (!Object.hasOwn(ENGINES, engine)) continue;
74
+ const at = \`\${file.path}:\${text.slice(0, match.index).split('\\n').length}\`;
75
+ findings.push({
76
+ code: CODE,
77
+ cause: \`\${at} imports \${engine}, a second animation or effect engine — the app moves at one tempo, under one reduced-motion rule, through the framework's own\`,
78
+ fix: \`import \${ENGINES[engine]} at \${at}, then remove \${engine} from package.json and run: x verify --only boundaries\`,
79
+ at,
80
+ });
81
+ }
82
+ }
83
+ return findings;
84
+ }
85
+
86
+ export const guard: Guard = {
87
+ summary:
88
+ 'motion and effects come from @ultimat3/ui/motion and @ultimat3/effects, never a direct engine',
89
+ severity: 'warning',
90
+ async check(_root, sources) {
91
+ const code = await sources.files('{apps,packages}/**/*.{ts,tsx}');
92
+ return motionAdapter(
93
+ code
94
+ .filter((file) => !/\\.(?:test|spec|d)\\.tsx?$/.test(file.path))
95
+ .map((file) => ({ path: file.path, source: file.text })),
96
+ );
97
+ },
98
+ };
99
+ `;
100
+
101
+ const test =
102
+ (): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
103
+ // a green gate over the convention it was written to enforce.
104
+
105
+ import { expect, unitTest } from '@ultimat3/testing';
106
+ import { motionAdapter } from './motion-adapter';
107
+
108
+ const file = (source: string) => [{ path: 'apps/web/app/feed/card.island.tsx', source }];
109
+
110
+ unitTest('a direct engine import is refused, at its line, with the adapter to use', () => {
111
+ const findings = motionAdapter(file("import { a } from './a';\\nimport b from 'motion';"));
112
+ expect(findings).toHaveLength(1);
113
+ expect(findings[0]?.code).toBe('${CODE}');
114
+ expect(findings[0]?.at).toBe('apps/web/app/feed/card.island.tsx:2');
115
+ expect(findings[0]?.fix).toContain('@ultimat3/ui/motion');
116
+ });
117
+
118
+ unitTest('every engine, its subpaths, import(), require() and re-exports are the same rule', () => {
119
+ const engines = [
120
+ "import 'gsap';",
121
+ "import { motion } from 'framer-motion';",
122
+ "import { animate } from 'motion/react';",
123
+ "import { x } from 'motion-dom';",
124
+ "import a from 'animejs';",
125
+ "import { Motion } from 'solid-motionone';",
126
+ "import { TransitionGroup } from 'solid-transition-group';",
127
+ "import { Mesh } from '@paper-design/shaders/react';",
128
+ "import { Shader } from 'shaders';",
129
+ "import { Renderer } from 'ogl';",
130
+ "import { Scene } from 'three/examples/jsm/Addons.js';",
131
+ "const m = await import('gsap');",
132
+ "const t = require('three');",
133
+ "export { animate } from 'motion';",
134
+ ];
135
+ for (const line of engines) expect(motionAdapter(file(line))).toHaveLength(1);
136
+ });
137
+
138
+ unitTest('a comment-like string hides nothing: the import after it is still refused', () => {
139
+ expect(motionAdapter(file("const g = 'dist/*'; import('gsap'); /** d */"))).toHaveLength(1);
140
+ expect(motionAdapter(file("const u = '//cdn'; const t = require('three');"))).toHaveLength(1);
141
+ });
142
+
143
+ unitTest('the adapter, a lookalike package, a comment and a string are silent', () => {
144
+ const silent = [
145
+ "import { animate } from '@ultimat3/ui/motion';",
146
+ "import { Aurora } from '@ultimat3/effects';",
147
+ "import { x } from 'motionless';",
148
+ "import { x } from 'threes';",
149
+ "import { x } from './motion';",
150
+ "// import { animate } from 'motion';",
151
+ "const s = 'gsap';",
152
+ ];
153
+ for (const line of silent) expect(motionAdapter(file(line))).toEqual([]);
154
+ });
155
+ `;
156
+
157
+ /** `guards/motion-adapter.ts` and its test. No index, no registry — the directory registers it. */
158
+ export const motionAdapterGuardFiles = (): readonly GeneratedFile[] => [
159
+ { path: `guards/${NAME}.ts`, contents: source() },
160
+ { path: `guards/${NAME}.test.ts`, contents: test() },
161
+ ];