@snap/valdi 1.0.11 → 1.1.5

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 (68) hide show
  1. package/.metadata/.bazelrc.template +6 -5
  2. package/.metadata/MODULE.bazel.template +62 -0
  3. package/bundled-skills/registry.json +13 -2
  4. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  5. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  6. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  7. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  8. package/bundled-skills/skills/valdi-custom-view/skill.md +43 -1
  9. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  10. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  11. package/bundled-skills/skills/valdi-inspect/skill.md +19 -1
  12. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  13. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  14. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  15. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  16. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  17. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  18. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  19. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  20. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  21. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  22. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  23. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  24. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  25. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  26. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  27. package/bundled-skills/skills/valdi-polyglot-module/skill.md +80 -0
  28. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  29. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  30. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  31. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  32. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  33. package/dist/commands/agentCheck.js +184 -0
  34. package/dist/commands/analyze.js +16 -0
  35. package/dist/commands/analyze_commands/duplicates.js +134 -0
  36. package/dist/commands/bootstrap.js +57 -73
  37. package/dist/commands/doctor.js +40 -203
  38. package/dist/commands/hotreload.js +15 -0
  39. package/dist/commands/inspect_commands/snapshot.js +71 -6
  40. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  41. package/dist/commands/preview.js +81 -0
  42. package/dist/commands/projectsync.js +9 -7
  43. package/dist/commands/skills_commands/install.js +6 -1
  44. package/dist/commands/skills_commands/update.js +2 -1
  45. package/dist/core/analyze/clusterer.js +150 -0
  46. package/dist/core/analyze/fingerprint.js +2 -0
  47. package/dist/core/analyze/knownPatterns.js +76 -0
  48. package/dist/core/analyze/parser.js +177 -0
  49. package/dist/core/analyze/reporter.js +83 -0
  50. package/dist/core/analyze/scanner.js +172 -0
  51. package/dist/core/analyze/similarity.js +56 -0
  52. package/dist/core/constants.js +1 -1
  53. package/dist/core/packageFiles.spec.js +1 -1
  54. package/dist/preview/previewGenerator.js +240 -0
  55. package/dist/preview/previewGenerator.spec.js +203 -0
  56. package/dist/preview/viewModelParser.js +86 -0
  57. package/dist/preview/viewModelParser.spec.js +171 -0
  58. package/dist/setup/DevSetupHelper.js +0 -51
  59. package/dist/setup/linuxSetup.js +0 -2
  60. package/dist/setup/macOSSetup.js +1 -4
  61. package/dist/utils/BazelClient.js +15 -0
  62. package/dist/utils/daemonClient.js +3 -1
  63. package/dist/utils/skillsAdapters.js +86 -5
  64. package/dist/utils/skillsAdapters.spec.js +60 -0
  65. package/dist/utils/skillsRegistry.js +8 -0
  66. package/package.json +16 -8
  67. package/.metadata/WORKSPACE.template +0 -57
  68. package/dist/setup/versions.js +0 -8
@@ -38,13 +38,14 @@ valdi_module(
38
38
 
39
39
  ```json
40
40
  {
41
- "extends": "../../../../src/valdi_modules/src/valdi/_configs/base.tsconfig.json"
41
+ "extends": "../_configs/base.tsconfig.json"
42
42
  }
43
43
  ```
44
44
 
45
- Adjust the `../../../../` prefix to match how many directories deep your module is
46
- from the repo root. The base config sets up `paths` aliases so `'valdi_core/src/...'`
47
- imports resolve correctly.
45
+ The `extends` path must resolve to a `_configs/base.tsconfig.json` file. The relative
46
+ depth depends on where your module lives — check neighboring modules for the correct
47
+ prefix. The base config sets up `paths` aliases so `'valdi_core/src/...'` imports
48
+ resolve correctly.
48
49
 
49
50
  ## Dependency Table
50
51
 
@@ -54,7 +55,6 @@ imports resolve correctly.
54
55
  | JSX elements (`<view>`, `<label>`, etc.), `NativeTemplateElements` | `//src/valdi_modules/src/valdi/valdi_tsx` |
55
56
  | `HTTPClient`, `HTTPResponse` | `//src/valdi_modules/src/valdi/valdi_http` |
56
57
  | `PersistentStore` | `//src/valdi_modules/src/valdi/persistence` |
57
- | Pre-built UI components (buttons, cards, etc.) | `//src/valdi_modules/src/valdi/valdi_widgets_core` |
58
58
 
59
59
  ## ios_module_name Convention
60
60
 
@@ -105,6 +105,21 @@ export class MyComponent extends StatefulComponent<MyComponentViewModel, MyState
105
105
  }
106
106
  ```
107
107
 
108
+ ## Registering in an App Target
109
+
110
+ Your module must be added as a dependency of an application target to be compiled
111
+ and linked. The exact location depends on your project — look for the list of
112
+ Valdi module deps in the app's `BUILD.bazel` (often a `VALDI_MODULES` list or
113
+ similar) and add your module:
114
+
115
+ ```python
116
+ "//path/to/my_module:my_module",
117
+ ```
118
+
119
+ Without this, the module will not be compiled or bundled — the app will fail at
120
+ runtime with "No item named '...' in module '...'" even though the build itself
121
+ may succeed.
122
+
108
123
  ## Building
109
124
 
110
125
  ```bash
@@ -127,3 +142,38 @@ valdi hotreload --network # Discover device over Wi-Fi instead of USB
127
142
 
128
143
  If hot reload stops reflecting changes, stop with `Ctrl+C` and restart — the CLI
129
144
  will clean stale build artifacts automatically.
145
+
146
+ ## Agent Iteration Workflow
147
+
148
+ When an AI agent is editing Valdi TypeScript, use the hot reloader for compile
149
+ feedback and `agent-check` for lint + test validation.
150
+
151
+ ### During iteration
152
+
153
+ 1. Hot reloader is running (`valdi hotreload`). It recompiles on every file save.
154
+ 2. Watch the hot reloader output for compile results:
155
+ - `"Recompilation pass finished"` — change compiled successfully
156
+ - `[ERROR]` lines — compile error, fix before continuing
157
+ 3. Run a quick validation (lint + tests, skips the Bazel build):
158
+
159
+ ```bash
160
+ valdi agent-check --module my_module --quick
161
+ valdi agent-check --module my_module --quick --json # machine-readable
162
+ ```
163
+
164
+ ### Before committing
165
+
166
+ Run the full pipeline to catch build config issues, lint drift, and test regressions:
167
+
168
+ ```bash
169
+ valdi agent-check --module my_module
170
+ ```
171
+
172
+ ### agent-check flags
173
+
174
+ | Flag | Effect |
175
+ |---|---|
176
+ | `--module <name>` | Valdi module name to validate |
177
+ | `--target <label>` | Bazel target path (alternative to --module) |
178
+ | `--quick` | Skip build step (hot reloader already compiled) |
179
+ | `--json` | Structured JSON output for agent consumption |
@@ -42,20 +42,24 @@ my_module/
42
42
 
43
43
  ## BUILD.bazel for Tests
44
44
 
45
- Add a `ts_project` or `valdi_module` test target. The test target lists test spec files in `srcs` and shares `deps` with the main module:
45
+ Tests are included in the same `valdi_module` target as source files. The `valdi_module` rule auto-generates a test target from `test/` files:
46
46
 
47
47
  ```python
48
48
  load("//bzl/valdi:valdi_module.bzl", "valdi_module")
49
49
 
50
50
  valdi_module(
51
- name = "my_module_tests",
52
- srcs = glob(["test/**/*.spec.tsx", "test/**/*.spec.ts"]),
53
- testonly = True,
51
+ name = "my_module",
52
+ srcs = glob([
53
+ "src/**/*.ts",
54
+ "src/**/*.tsx",
55
+ "test/**/*.ts",
56
+ "test/**/*.tsx",
57
+ ]) + ["tsconfig.json"],
54
58
  deps = [
55
- ":my_module",
56
- "//src/valdi_modules/src/valdi/valdi_test",
57
- "//src/valdi_modules/src/foundation/test/util",
59
+ "//src/valdi_modules/src/valdi/valdi_core",
58
60
  "//src/valdi_modules/src/valdi/valdi_tsx",
61
+ "//src/valdi_modules/src/valdi/valdi_test",
62
+ "//src/valdi_modules/src/valdi/foundation/test/util",
59
63
  ],
60
64
  )
61
65
  ```
@@ -63,3 +67,15 @@ valdi_module(
63
67
  ## Platform Tests
64
68
 
65
69
  For C++, iOS, and Android platform layer tests, see the `valdi-cpp-runtime`, `valdi-ios`, and `valdi-android` skills respectively.
70
+
71
+ ## Combined Validation with agent-check
72
+
73
+ Instead of running build and test separately, use `agent-check`:
74
+
75
+ ```bash
76
+ valdi agent-check --module my_module # build + lint + test
77
+ valdi agent-check --module my_module --quick # lint + test only (hot reloader running)
78
+ valdi agent-check --module my_module --quick --json # machine-readable output
79
+ ```
80
+
81
+ See the **valdi-setup** skill for the full hot reloader + agent-check iteration workflow.
@@ -106,9 +106,17 @@ document.addEventListener('click', ...); // Doesn't work!
106
106
  onChange={this.handleTextChange}
107
107
  onEditEnd={this.handleSubmit}
108
108
  />
109
+
110
+ // ✅ CORRECT - For keyboard input on macOS desktop, use a polyglot <custom-view>
111
+ // (see valdi-polyglot-module and valdi-custom-view skills for full pattern)
112
+ {Device.isDesktop() && (
113
+ <custom-view macosClass='SCKeyboardView' onKeyDown={this.handleKeyDown} width={200} height={200}>
114
+ {/* wrap visible content so the view has non-zero size for first responder */}
115
+ </custom-view>
116
+ )}
109
117
  ```
110
118
 
111
- **Important**: Valdi doesn't support `addEventListener`, `keydown`, or other global DOM events. Use element-specific callbacks like `onTap`, `onPress`, `onChange`, etc.
119
+ **Important**: Valdi doesn't support `addEventListener`, `keydown`, or other global DOM events. Use element-specific callbacks like `onTap`, `onPress`, `onChange`, etc. For keyboard input on macOS desktop, use a polyglot `<custom-view>` with a native NSView that captures `keyDown:` events and forwards them via a bound callback attribute.
112
120
 
113
121
  ## Timers and Scheduling
114
122
 
@@ -178,6 +186,26 @@ onRender() {
178
186
  }
179
187
  ```
180
188
 
189
+ ### Font weights
190
+
191
+ Only two system font weights are available:
192
+ - `'system 16'` — regular weight
193
+ - `'system-bold 16'` — bold weight
194
+
195
+ **No other weights exist.** `system-semibold`, `system-light`, `system-medium` etc. will cause build errors. If you need semibold, use `system-bold` instead.
196
+
197
+ ### ScrollView restrictions
198
+
199
+ `<scroll>` (ScrollView) does **not** support `flexDirection`. It always scrolls vertically. Do not set `flexDirection: 'column'` on a ScrollView style — it will cause a build error.
200
+
201
+ ```typescript
202
+ // ❌ WRONG - flexDirection not valid on ScrollView
203
+ new Style<ScrollView>({ flexDirection: 'column' })
204
+
205
+ // ✅ CORRECT - ScrollView scrolls vertically by default, no flexDirection needed
206
+ new Style<ScrollView>({ width: '100%', height: '100%' })
207
+ ```
208
+
181
209
  ### Style Composition
182
210
 
183
211
  ```typescript
@@ -230,6 +258,11 @@ new Style<View>({
230
258
  paddingVertical: 10, // ❌ Use padding: '10 0'
231
259
  paddingInline: 15, // ❌ Doesn't exist
232
260
  })
261
+
262
+ // ❌ WRONG - gap property doesn't exist on View
263
+ new Style<View>({ flexDirection: 'row', gap: '8' })
264
+ // ✅ CORRECT - use margin on child elements instead
265
+ // In JSX: <view marginRight={8}> or margin="0 8 0 0"
233
266
  ```
234
267
 
235
268
  ### Layout: Flexbox (Yoga)
@@ -328,6 +361,28 @@ const layoutStyle = new Style<Layout>({ padding: 10 });
328
361
  >
329
362
  > **📖 Best practices**: See `/docs/docs/core-styling.md` for styling patterns and examples
330
363
 
364
+ ## @ExportModel ViewModel Restrictions
365
+
366
+ Interfaces annotated with `@ViewModel @ExportModel` are exported to native code. The Valdi compiler can only export **primitive types** (`string`, `number`, `boolean`) and other `@ExportModel`-annotated interfaces. Custom type aliases (e.g. `type Direction = 'UP' | 'DOWN'`) are **not supported** in exported ViewModels.
367
+
368
+ ```typescript
369
+ // ❌ WRONG — type alias in @ExportModel ViewModel
370
+ type Direction = 'UP' | 'DOWN' | 'LEFT' | 'RIGHT';
371
+
372
+ /** @ViewModel @ExportModel */
373
+ interface GameViewModel {
374
+ initialDirection?: Direction; // ❌ Compiler error: "Unrecognized type"
375
+ }
376
+
377
+ // ✅ CORRECT — keep custom types in State (internal), not ViewModel (exported)
378
+ /** @ViewModel @ExportModel */
379
+ interface GameViewModel {} // Only export what native code needs
380
+
381
+ interface GameState {
382
+ direction: Direction; // ✅ Fine — State is not exported
383
+ }
384
+ ```
385
+
331
386
  ## Common Mistakes to Avoid
332
387
 
333
388
  1. **Returning JSX from onRender()** - It returns void, JSX is a statement
@@ -337,10 +392,17 @@ const layoutStyle = new Style<Layout>({ padding: 10 });
337
392
  5. **Suggesting scheduleRender()** - Deprecated, use StatefulComponent + setState()
338
393
  6. **Using addEventListener** - Use element callbacks like onTap, onPress, onChange
339
394
  7. **Using setInterval/setTimeout directly** - Use this.setTimeoutDisposable()
340
- 8. **Using CSS properties that don't exist** - No gap, paddingHorizontal, paddingVertical
395
+ 8. **Using CSS properties that don't exist** - No gap, paddingHorizontal, paddingVertical; use margin on children for gap
341
396
  9. **Using `flex: 1`** - `flex` doesn't exist on `View`; use `flexGrow: 1` instead
342
397
  10. **Using `fontSize` on Label** - Labels use `font: 'system 20'` (string), not `fontSize`
343
- 11. **Using `overflow: 'hidden'`** - `View` only accepts `'visible' | 'scroll'`; remove overflow or use 'scroll'
398
+ 11. **Typing SIGIcon values as `string`** - `SIGIcon.cameraStroke` etc. return `Asset`, not `string`; use `import { Asset } from 'valdi_core/src/Asset'` for ViewModel fields that store icon references
399
+ 12. **Using `overflow: 'hidden'`** - `View` only accepts `'visible' | 'scroll'`; remove overflow or use 'scroll'
400
+ 13. **Using type aliases in `@ExportModel` ViewModels** - Only primitives and other `@ExportModel` types are allowed
401
+ 14. **Importing `Shape` instead of `ShapeView`** - `Shape` is not exported; use `import { ShapeView } from 'valdi_tsx/src/NativeTemplateElements'` and `new Style<ShapeView>({...})`
402
+ 15. **Using per-side border properties** - No `borderRight`, `borderRightWidth`, etc. Only `borderWidth`, `borderColor`, `borderRadius` exist. Use a thin `<view>` as a divider instead.
403
+ 16. **Using `font: 'system-semibold 16'`** - Only `system` (regular) and `system-bold` are reliably available. Use `system-bold` for semibold.
404
+ 17. **ViewModel/Context name collisions** - When a module has multiple components, each exported `ViewModel` and `ComponentContext` must have a unique name (e.g. `WeatherCardViewModel` not just `ViewModel`), or the compiler will emit conflicting platform types.
405
+ 18. **Using `flexDirection` on ScrollView** - ScrollView doesn't support flexDirection; it scrolls vertically by default
344
406
 
345
407
  ## Platform Detection
346
408
 
@@ -354,14 +416,16 @@ class MyComponent extends Component<MyViewModel> {
354
416
  <view>
355
417
  {Device.isIOS() && <IOSOnlyView />}
356
418
  {Device.isAndroid() && <AndroidOnlyView />}
357
- {Device.isMacOS() && <MacOSOnlyView />}
419
+ {Device.isDesktop() && <DesktopOnlyView />}
358
420
  {Device.isWeb() && <WebOnlyView />}
359
421
  </view>;
360
422
  }
361
423
  }
362
424
  ```
363
425
 
364
- Also use `Device.isIOS()` / `Device.isAndroid()` guards before using `<custom-view>` elements that don't have implementations on all platforms.
426
+ **Available guards:** `Device.isIOS()`, `Device.isAndroid()`, `Device.isDesktop()`, `Device.isWeb()`
427
+
428
+ Use platform guards before using `<custom-view>` elements that don't have implementations on all platforms. `Device.isDesktop()` is true for macOS desktop apps (the preview/standalone app). There is no `Device.isMacOS()` — use `Device.isDesktop()` instead.
365
429
 
366
430
  ## Imports
367
431
 
@@ -71,12 +71,12 @@ class Counter extends StatefulComponent<CounterViewModel, CounterState> {
71
71
  }
72
72
 
73
73
  // Class arrow functions — never inline lambdas in JSX props
74
- private handleIncrement = (): void => {
74
+ private handleIncrement = (_event: unknown): void => {
75
75
  this.setState({ count: this.state.count + 1 });
76
76
  };
77
77
 
78
- private handleTextChange = (text: string): void => {
79
- this.setState({ inputText: text });
78
+ private handleTextChange = (event: { text: string }): void => {
79
+ this.setState({ inputText: event.text });
80
80
  };
81
81
 
82
82
  onRender(): void {
@@ -87,7 +87,7 @@ class Counter extends StatefulComponent<CounterViewModel, CounterState> {
87
87
  value={this.state.inputText}
88
88
  onChange={this.handleTextChange}
89
89
  />;
90
- <button title="Increment" onPress={this.handleIncrement} />;
90
+ <label value="Increment" onTap={this.handleIncrement} />;
91
91
  </view>;
92
92
  }
93
93
  }
@@ -127,7 +127,7 @@ class MediaPlayer extends Component<MediaPlayerViewModel> {
127
127
  <view>
128
128
  {Device.isIOS() && <label value="iOS player" />}
129
129
  {Device.isAndroid() && <label value="Android player" />}
130
- {Device.isMacOS() && <label value="macOS player" />}
130
+ {Device.isDesktop() && <label value="macOS player" />}
131
131
  </view>;
132
132
  }
133
133
  }
@@ -165,9 +165,33 @@ class AppRoot extends Component {
165
165
  }
166
166
  }
167
167
 
168
+ // ─── @ExportModel ViewModel: only primitives, no type aliases ────────────────
169
+
170
+ type Direction = 'UP' | 'DOWN' | 'LEFT' | 'RIGHT';
171
+
172
+ /**
173
+ * @ViewModel
174
+ * @ExportModel
175
+ */
176
+ interface GameViewModel {} // Don't put Direction here — it can't be exported
177
+
178
+ interface GameState {
179
+ direction: Direction; // Type aliases are fine in State (not exported)
180
+ score: number;
181
+ }
182
+
183
+ class GameComponent extends StatefulComponent<GameViewModel, GameState> {
184
+ state: GameState = { direction: 'RIGHT', score: 0 };
185
+
186
+ onRender(): void {
187
+ <label value={`Direction: ${this.state.direction}, Score: ${this.state.score}`} />;
188
+ }
189
+ }
190
+
168
191
  // Suppress unused-variable warnings for top-level declarations
169
192
  void Counter;
170
193
  void ItemList;
171
194
  void Greeting;
172
195
  void MediaPlayer;
173
196
  void AppRoot;
197
+ void GameComponent;
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handler = exports.builder = exports.describe = exports.command = void 0;
4
+ const constants_1 = require("../core/constants");
5
+ const BazelClient_1 = require("../utils/BazelClient");
6
+ const LoadingIndicator_1 = require("../utils/LoadingIndicator");
7
+ const errorUtils_1 = require("../utils/errorUtils");
8
+ const logUtils_1 = require("../utils/logUtils");
9
+ async function runStep(name, fn, json) {
10
+ const start = Date.now();
11
+ if (!json) {
12
+ console.log((0, logUtils_1.wrapInColor)(`▸ ${name}...`, constants_1.ANSI_COLORS.YELLOW_COLOR));
13
+ }
14
+ try {
15
+ await fn();
16
+ const durationMs = Date.now() - start;
17
+ if (!json) {
18
+ console.log((0, logUtils_1.wrapInColor)(` ✓ ${name} (${durationMs}ms)`, constants_1.ANSI_COLORS.GREEN_COLOR));
19
+ }
20
+ return { name, status: 'pass', durationMs };
21
+ }
22
+ catch (error) {
23
+ const durationMs = Date.now() - start;
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ if (!json) {
26
+ console.log((0, logUtils_1.wrapInColor)(` ✗ ${name}: ${message}`, constants_1.ANSI_COLORS.RED_COLOR));
27
+ }
28
+ return { name, status: 'fail', durationMs, message };
29
+ }
30
+ }
31
+ async function getModuleTargets(client, module) {
32
+ const allTargets = await client.queryTargetsByKindWithFilter('valdi_module', [module], 'pipe');
33
+ const androidDebug = allTargets.filter((t) => t.includes('android.debug'));
34
+ return androidDebug.length > 0 ? androidDebug : allTargets;
35
+ }
36
+ async function getTestTargets(client, module) {
37
+ return await client.queryTargetsByKindWithFilter('test', [module], 'pipe');
38
+ }
39
+ async function valdiAgentCheck(argv) {
40
+ const json = argv.getArgument('json') ?? false;
41
+ const quick = argv.getArgument('quick') ?? false;
42
+ const bazelClient = new BazelClient_1.BazelClient();
43
+ const moduleName = argv.getArgument('module');
44
+ const targetName = argv.getArgument('target');
45
+ if (!moduleName && !targetName) {
46
+ throw new Error('Either --module or --target is required');
47
+ }
48
+ const results = [];
49
+ const totalStart = Date.now();
50
+ if (!json) {
51
+ const mode = quick ? 'Quick' : 'Full';
52
+ console.log((0, logUtils_1.wrapInColor)(`\n═══ Valdi Agent Check (${mode}) ═══\n`, constants_1.ANSI_COLORS.GREEN_COLOR));
53
+ }
54
+ let buildTargets = [];
55
+ let testTargets = [];
56
+ if (targetName) {
57
+ buildTargets = [targetName];
58
+ }
59
+ else if (moduleName) {
60
+ const resolveResult = await runStep('Resolve module targets', async () => {
61
+ const task = getModuleTargets(bazelClient, moduleName);
62
+ buildTargets = json
63
+ ? await task
64
+ : await LoadingIndicator_1.LoadingIndicator.fromTask(task)
65
+ .setText((0, logUtils_1.wrapInColor)('Resolving module targets...', constants_1.ANSI_COLORS.YELLOW_COLOR))
66
+ .setSuccessText((0, logUtils_1.wrapInColor)('Resolved module targets.', constants_1.ANSI_COLORS.GREEN_COLOR))
67
+ .setFailureText((0, logUtils_1.wrapInColor)('Failed to resolve targets.', constants_1.ANSI_COLORS.RED_COLOR))
68
+ .show();
69
+ if (buildTargets.length === 0) {
70
+ throw new Error(`No valdi_module targets found for module "${moduleName}"`);
71
+ }
72
+ }, json);
73
+ results.push(resolveResult);
74
+ if (resolveResult.status === 'fail') {
75
+ return outputResults(results, totalStart, json);
76
+ }
77
+ testTargets = await getTestTargets(bazelClient, moduleName).catch(() => []);
78
+ }
79
+ if (!quick) {
80
+ const buildResult = await runStep('Build', async () => {
81
+ await bazelClient.buildTargets(buildTargets);
82
+ }, json);
83
+ results.push(buildResult);
84
+ }
85
+ else {
86
+ if (!json) {
87
+ console.log((0, logUtils_1.wrapInColor)(' ⊘ Build: skipped (--quick mode, hot reloader handles compilation)', constants_1.ANSI_COLORS.YELLOW_COLOR));
88
+ }
89
+ results.push({ name: 'Build', status: 'skip', durationMs: 0, message: 'Skipped in quick mode' });
90
+ }
91
+ const lintPromise = (buildTargets.length > 0)
92
+ ? runStep('Lint check', async () => {
93
+ const { runCliCommand } = await Promise.resolve().then(() => __importStar(require('../utils/cliUtils')));
94
+ const { globSync } = await Promise.resolve().then(() => __importStar(require('glob')));
95
+ const firstTarget = buildTargets[0] ?? '';
96
+ const packagePath = firstTarget.replace(/^\/\//, '').replace(/:.*$/, '') || '.';
97
+ const globPattern = `${packagePath}/**/*.{ts,tsx}`;
98
+ const tsFiles = globSync(globPattern);
99
+ if (tsFiles.length === 0) {
100
+ return;
101
+ }
102
+ const result = await runCliCommand(`npx prettier --check "${globPattern}"`);
103
+ if (result.returnCode !== 0) {
104
+ throw new Error('Lint check failed — files not formatted');
105
+ }
106
+ }, json)
107
+ : Promise.resolve({ name: 'Lint check', status: 'skip', durationMs: 0, message: 'No targets resolved for lint' });
108
+ const testPromise = (testTargets.length > 0)
109
+ ? runStep('Tests', async () => {
110
+ await bazelClient.testTargets(testTargets, '');
111
+ }, json)
112
+ : (() => {
113
+ if (!json) {
114
+ console.log((0, logUtils_1.wrapInColor)(' ⊘ Tests: skipped (no test targets found)', constants_1.ANSI_COLORS.YELLOW_COLOR));
115
+ }
116
+ return Promise.resolve({ name: 'Tests', status: 'skip', durationMs: 0, message: 'No test targets found' });
117
+ })();
118
+ const [lintResult, testResult] = await Promise.all([lintPromise, testPromise]);
119
+ results.push(lintResult);
120
+ results.push(testResult);
121
+ return outputResults(results, totalStart, json);
122
+ }
123
+ function outputResults(results, totalStart, json) {
124
+ const totalDurationMs = Date.now() - totalStart;
125
+ const passed = results.filter(r => r.status === 'pass').length;
126
+ const failed = results.filter(r => r.status === 'fail').length;
127
+ const skipped = results.filter(r => r.status === 'skip').length;
128
+ if (json) {
129
+ const output = {
130
+ timestamp: new Date().toISOString(),
131
+ totalDurationMs,
132
+ summary: { passed, failed, skipped, total: results.length },
133
+ results,
134
+ success: failed === 0,
135
+ };
136
+ console.log(JSON.stringify(output, null, 2));
137
+ }
138
+ else {
139
+ console.log((0, logUtils_1.wrapInColor)('\n═══ Summary ═══', constants_1.ANSI_COLORS.GREEN_COLOR));
140
+ console.log(` Passed: ${passed}`);
141
+ console.log(` Failed: ${failed}`);
142
+ console.log(` Skipped: ${skipped}`);
143
+ console.log(` Total: ${totalDurationMs}ms`);
144
+ if (failed > 0) {
145
+ console.log((0, logUtils_1.wrapInColor)('\n✗ Agent check FAILED', constants_1.ANSI_COLORS.RED_COLOR));
146
+ process.exitCode = 1;
147
+ }
148
+ else {
149
+ console.log((0, logUtils_1.wrapInColor)('\n✓ Agent check PASSED', constants_1.ANSI_COLORS.GREEN_COLOR));
150
+ }
151
+ }
152
+ if (failed > 0) {
153
+ process.exitCode = 1;
154
+ }
155
+ }
156
+ exports.command = 'agent-check [--module module_name] [--target target_name] [--quick]';
157
+ exports.describe = 'Validate a Valdi module: resolve targets, build, lint, and test in one command. '
158
+ + 'Use --quick to skip the build step when the hot reloader is already compiling your changes. '
159
+ + 'Use --json for structured output that AI agents can parse directly.';
160
+ const builder = (yargs) => {
161
+ yargs
162
+ .option('module', {
163
+ describe: 'Name of the Valdi module to validate',
164
+ type: 'string',
165
+ requiresArg: true,
166
+ })
167
+ .option('target', {
168
+ describe: 'Bazel target path to validate',
169
+ type: 'string',
170
+ requiresArg: true,
171
+ })
172
+ .option('quick', {
173
+ describe: 'Skip the build step (use when hot reloader is running). Runs only lint + test.',
174
+ type: 'boolean',
175
+ default: false,
176
+ })
177
+ .option('json', {
178
+ describe: 'Output results as machine-readable JSON',
179
+ type: 'boolean',
180
+ default: false,
181
+ });
182
+ };
183
+ exports.builder = builder;
184
+ exports.handler = (0, errorUtils_1.makeCommandHandler)(valdiAgentCheck);
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handler = exports.builder = exports.describe = exports.command = void 0;
4
+ exports.command = 'analyze <command>';
5
+ exports.describe = 'Analyze Valdi modules — component duplication, patterns, health';
6
+ const builder = (yargs) => {
7
+ return yargs
8
+ .commandDir('analyze_commands', { extensions: ['js', 'ts'] })
9
+ .demandCommand(1, 'Use: duplicates')
10
+ .recommendCommands()
11
+ .wrap(yargs.terminalWidth())
12
+ .help();
13
+ };
14
+ exports.builder = builder;
15
+ const handler = () => { };
16
+ exports.handler = handler;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handler = exports.builder = exports.describe = exports.command = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const errorUtils_1 = require("../../utils/errorUtils");
7
+ const scanner_1 = require("../../core/analyze/scanner");
8
+ const parser_1 = require("../../core/analyze/parser");
9
+ const clusterer_1 = require("../../core/analyze/clusterer");
10
+ const knownPatterns_1 = require("../../core/analyze/knownPatterns");
11
+ const reporter_1 = require("../../core/analyze/reporter");
12
+ async function analyzeDuplicates(argv) {
13
+ const moduleFilter = argv.getArgument('module');
14
+ const json = argv.getArgument('json');
15
+ const threshold = argv.getArgument('threshold');
16
+ const patternFilter = argv.getArgument('pattern');
17
+ const outputPath = argv.getArgument('output');
18
+ const verbose = argv.getArgument('verbose');
19
+ const scanRootArg = argv.getArgument('scan-root');
20
+ const sharedLibArg = argv.getArgument('shared-lib');
21
+ const startTime = Date.now();
22
+ const cwd = process.cwd();
23
+ const config = (0, scanner_1.resolveScanConfig)(cwd, scanRootArg, sharedLibArg);
24
+ if (!json) {
25
+ process.stdout.write('Scanning files...');
26
+ }
27
+ const tsxFiles = (0, scanner_1.discoverTsxFiles)(config, moduleFilter);
28
+ if (!json) {
29
+ process.stdout.write(` found ${tsxFiles.length} .tsx files\n`);
30
+ process.stdout.write('Fingerprinting components...');
31
+ }
32
+ const fingerprints = [];
33
+ for (const file of tsxFiles) {
34
+ const fp = (0, parser_1.parseFile)(file, config);
35
+ if (fp)
36
+ fingerprints.push(fp);
37
+ }
38
+ if (!json) {
39
+ process.stdout.write(` extracted ${fingerprints.length} component fingerprints\n`);
40
+ }
41
+ const modulesScanned = new Set(fingerprints.map(fp => fp.moduleName)).size;
42
+ if (!json) {
43
+ process.stdout.write('Detecting known patterns...');
44
+ }
45
+ const knownPatterns = (0, knownPatterns_1.detectKnownPatterns)(fingerprints, config, patternFilter);
46
+ if (!json) {
47
+ process.stdout.write(` found ${knownPatterns.length} patterns\n`);
48
+ process.stdout.write('Clustering similar components...');
49
+ }
50
+ const genericClusters = patternFilter ? [] : (0, clusterer_1.clusterFingerprints)(fingerprints, config, threshold);
51
+ if (!json) {
52
+ process.stdout.write(` found ${genericClusters.length} clusters\n\n`);
53
+ }
54
+ const durationMs = Date.now() - startTime;
55
+ const totalKnownPatternMatches = knownPatterns.reduce((sum, p) => sum + p.matchCount, 0);
56
+ const totalDuplicatedFiles = new Set(genericClusters.flatMap(c => c.files.map(f => f.path))).size;
57
+ const report = {
58
+ timestamp: new Date().toISOString(),
59
+ config,
60
+ scanStats: {
61
+ filesScanned: tsxFiles.length,
62
+ modulesScanned,
63
+ durationMs,
64
+ },
65
+ knownPatterns,
66
+ genericClusters,
67
+ summary: {
68
+ totalClusters: genericClusters.length,
69
+ totalDuplicatedFiles,
70
+ totalKnownPatternMatches,
71
+ },
72
+ };
73
+ if (outputPath) {
74
+ fs.writeFileSync(outputPath, (0, reporter_1.formatJsonReport)(report), 'utf8');
75
+ if (!json) {
76
+ console.log(`Report written to ${outputPath}`);
77
+ }
78
+ }
79
+ if (json) {
80
+ console.log((0, reporter_1.formatJsonReport)(report));
81
+ }
82
+ else {
83
+ (0, reporter_1.printHumanReport)(report, verbose);
84
+ }
85
+ }
86
+ exports.command = 'duplicates';
87
+ exports.describe = 'Find duplicated component patterns across Valdi modules';
88
+ const builder = (yargs) => {
89
+ yargs
90
+ .option('module', {
91
+ describe: 'Scope scan to a single module',
92
+ type: 'string',
93
+ })
94
+ .option('json', {
95
+ describe: 'Machine-readable JSON output',
96
+ type: 'boolean',
97
+ default: false,
98
+ alias: 'j',
99
+ })
100
+ .option('threshold', {
101
+ describe: 'Similarity threshold for clustering (0-1)',
102
+ type: 'number',
103
+ default: 0.6,
104
+ alias: 't',
105
+ })
106
+ .option('pattern', {
107
+ describe: 'Only detect a specific known pattern: async, button, shimmer',
108
+ type: 'string',
109
+ choices: ['async', 'button', 'shimmer'],
110
+ })
111
+ .option('output', {
112
+ describe: 'Write JSON report to file',
113
+ type: 'string',
114
+ alias: 'o',
115
+ })
116
+ .option('verbose', {
117
+ describe: 'Show per-file detail in output',
118
+ type: 'boolean',
119
+ default: false,
120
+ alias: 'v',
121
+ })
122
+ .option('scan-root', {
123
+ describe: 'Root directory to scan (repeatable). Auto-detected if omitted.',
124
+ type: 'string',
125
+ array: true,
126
+ })
127
+ .option('shared-lib', {
128
+ describe: 'Shared component library name (repeatable). Defaults: coreui (internal) or valdi_widgets (external).',
129
+ type: 'string',
130
+ array: true,
131
+ });
132
+ };
133
+ exports.builder = builder;
134
+ exports.handler = (0, errorUtils_1.makeCommandHandler)(analyzeDuplicates);