@snap/valdi 1.0.6 → 1.0.8

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 (161) hide show
  1. package/README.md +22 -10
  2. package/bundled-skills/CONTRIBUTING_SKILLS.md +74 -0
  3. package/bundled-skills/registry.json +20 -0
  4. package/bundled-skills/skills/valdi-android/skill.md +89 -0
  5. package/bundled-skills/skills/valdi-async/skill.md +246 -0
  6. package/bundled-skills/skills/valdi-async/tests/BUILD.bazel +19 -0
  7. package/bundled-skills/skills/valdi-async/tests/README.md +25 -0
  8. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +210 -0
  9. package/bundled-skills/skills/valdi-async/tests/tsconfig.json +1 -0
  10. package/bundled-skills/skills/valdi-bazel/skill.md +122 -0
  11. package/bundled-skills/skills/valdi-compiler/skill.md +108 -0
  12. package/bundled-skills/skills/valdi-component-tests/skill.md +430 -0
  13. package/bundled-skills/skills/valdi-component-tests/tests/BUILD.bazel +24 -0
  14. package/bundled-skills/skills/valdi-component-tests/tests/README.md +35 -0
  15. package/bundled-skills/skills/valdi-component-tests/tests/src/ProfileCard.tsx +38 -0
  16. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +107 -0
  17. package/bundled-skills/skills/valdi-component-tests/tests/tsconfig.json +1 -0
  18. package/bundled-skills/skills/valdi-cpp-runtime/skill.md +103 -0
  19. package/bundled-skills/skills/valdi-custom-view/skill.md +62 -0
  20. package/bundled-skills/skills/valdi-ios/skill.md +93 -0
  21. package/bundled-skills/skills/valdi-migrate/skill.md +175 -0
  22. package/bundled-skills/skills/valdi-migrate/tests/BUILD.bazel +23 -0
  23. package/bundled-skills/skills/valdi-migrate/tests/README.md +70 -0
  24. package/bundled-skills/skills/valdi-migrate/tests/check_antipatterns.py +89 -0
  25. package/bundled-skills/skills/valdi-migrate/tests/compose_example.kt +94 -0
  26. package/bundled-skills/skills/valdi-migrate/tests/flutter_example.dart +129 -0
  27. package/bundled-skills/skills/valdi-migrate/tests/react_example.tsx +98 -0
  28. package/bundled-skills/skills/valdi-migrate/tests/src/expected_valdi.tsx +267 -0
  29. package/bundled-skills/skills/valdi-migrate/tests/tsconfig.json +3 -0
  30. package/{.metadata/.cursorrules.template → bundled-skills/skills/valdi-overview/skill.md} +23 -13
  31. package/bundled-skills/skills/valdi-perf/skill.md +197 -0
  32. package/bundled-skills/skills/valdi-perf/tests/BUILD.bazel +19 -0
  33. package/bundled-skills/skills/valdi-perf/tests/README.md +26 -0
  34. package/bundled-skills/skills/valdi-perf/tests/src/reference.tsx +202 -0
  35. package/bundled-skills/skills/valdi-perf/tests/tsconfig.json +1 -0
  36. package/bundled-skills/skills/valdi-polyglot-module/skill.md +85 -0
  37. package/bundled-skills/skills/valdi-setup/skill.md +129 -0
  38. package/bundled-skills/skills/valdi-testing/skill.md +65 -0
  39. package/bundled-skills/skills/valdi-tsx/skill.md +385 -0
  40. package/bundled-skills/skills/valdi-tsx/tests/BUILD.bazel +19 -0
  41. package/bundled-skills/skills/valdi-tsx/tests/README.md +29 -0
  42. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +173 -0
  43. package/bundled-skills/skills/valdi-tsx/tests/tsconfig.json +1 -0
  44. package/dist/commands/bootstrap.js +3 -9
  45. package/dist/commands/newModule.js +10 -14
  46. package/dist/commands/skills.js +16 -0
  47. package/dist/commands/skills_commands/create.js +125 -0
  48. package/dist/commands/skills_commands/install.js +96 -0
  49. package/dist/commands/skills_commands/list.js +83 -0
  50. package/dist/commands/skills_commands/remove.js +41 -0
  51. package/dist/commands/skills_commands/update.js +59 -0
  52. package/dist/core/constants.js +1 -1
  53. package/dist/index.js +5 -0
  54. package/dist/setup/versions.js +1 -1
  55. package/dist/utils/skillsAdapters.js +140 -0
  56. package/dist/utils/skillsRegistry.js +40 -0
  57. package/package.json +6 -1
  58. package/.bazelignore +0 -2
  59. package/.bootstrap/apps/cli_application/AGENTS.md.template +0 -291
  60. package/.bootstrap/apps/cli_application/BUILD.bazel.template +0 -7
  61. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +0 -11
  62. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +0 -1
  63. package/.bootstrap/apps/ui_application/.eslint.rc +0 -27
  64. package/.bootstrap/apps/ui_application/AGENTS.md.template +0 -278
  65. package/.bootstrap/apps/ui_application/BUILD.bazel.template +0 -19
  66. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +0 -21
  67. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  68. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +0 -133
  69. package/.bootstrap/apps/ui_application/package.json +0 -24
  70. package/.bootstrap/modules/cpp_bridge_module/BUILD.bazel.template +0 -21
  71. package/.bootstrap/modules/cpp_bridge_module/cpp/CalculatorModuleFactory.cpp.template +0 -28
  72. package/.bootstrap/modules/cpp_bridge_module/src/Calculator.d.ts +0 -4
  73. package/.bootstrap/modules/ios_android_bridge_module/BUILD.bazel.template +0 -39
  74. package/.bootstrap/modules/ios_android_bridge_module/android/CalculatorModuleFactory.kt.template +0 -18
  75. package/.bootstrap/modules/ios_android_bridge_module/ios/SCCCalculatorModuleFactory.m.template +0 -31
  76. package/.bootstrap/modules/ios_android_bridge_module/src/Calculator.d.ts +0 -4
  77. package/.bootstrap/modules/ios_android_view_module/BUILD.bazel.template +0 -41
  78. package/.bootstrap/modules/ios_android_view_module/android/CircleView.kt.template +0 -42
  79. package/.bootstrap/modules/ios_android_view_module/android/CircleViewAttributesBinder.kt.template +0 -60
  80. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.h +0 -6
  81. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.m +0 -82
  82. package/.bootstrap/modules/ios_android_view_module/src/Circle.tsx.template +0 -15
  83. package/.bootstrap/modules/ui_component/BUILD.bazel.template +0 -34
  84. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +0 -45
  85. package/.config/copyconfig.json +0 -10
  86. package/.editorconfig +0 -21
  87. package/.eslintignore +0 -1
  88. package/.eslintrc.js +0 -72
  89. package/.github/README.md +0 -164
  90. package/.metadata/.bazelrc.template +0 -91
  91. package/.metadata/.bazelversion.template +0 -1
  92. package/.metadata/.editorconfig.template +0 -37
  93. package/.metadata/.eslintrc.js.template +0 -27
  94. package/.metadata/.gitignore.template +0 -4
  95. package/.metadata/.prettierrc.json.template +0 -7
  96. package/.metadata/.watchmanconfig.template +0 -8
  97. package/.metadata/README.md.template +0 -31
  98. package/.metadata/WORKSPACE.template +0 -57
  99. package/.metadata/config.yaml.template +0 -1
  100. package/.metadata/package.json.template +0 -23
  101. package/.prettierignore +0 -2
  102. package/.prettierrc.json +0 -7
  103. package/LINUX_COMPATIBILITY.md +0 -248
  104. package/prettier.config.js +0 -4
  105. package/scripts/sync-agents-md.sh +0 -44
  106. package/scripts/update-agents-templates.ts +0 -170
  107. package/spec/support/jasmine.json +0 -6
  108. package/src/commands/bootstrap.ts +0 -409
  109. package/src/commands/build.ts +0 -89
  110. package/src/commands/devSetup.ts +0 -17
  111. package/src/commands/doctor.ts +0 -1832
  112. package/src/commands/export.ts +0 -131
  113. package/src/commands/hotreload.ts +0 -108
  114. package/src/commands/install.ts +0 -93
  115. package/src/commands/lint.ts +0 -15
  116. package/src/commands/lint_commands/lintCheck.ts +0 -53
  117. package/src/commands/lint_commands/lintFormat.ts +0 -49
  118. package/src/commands/log.ts +0 -108
  119. package/src/commands/newModule.ts +0 -286
  120. package/src/commands/package.ts +0 -102
  121. package/src/commands/projectsync.ts +0 -488
  122. package/src/commands/test.ts +0 -68
  123. package/src/core/constants.ts +0 -97
  124. package/src/core/errors.ts +0 -10
  125. package/src/index.ts +0 -22
  126. package/src/setup/DevSetupHelper.ts +0 -290
  127. package/src/setup/linuxSetup.ts +0 -261
  128. package/src/setup/macOSSetup.ts +0 -156
  129. package/src/setup/setupEntryPoint.ts +0 -64
  130. package/src/setup/versions.ts +0 -8
  131. package/src/utils/ArgumentsResolver.ts +0 -23
  132. package/src/utils/BazelClient.ts +0 -285
  133. package/src/utils/Digraph.ts +0 -81
  134. package/src/utils/LoadingIndicator.ts +0 -43
  135. package/src/utils/applicationUtils.ts +0 -276
  136. package/src/utils/buildInfo.ts +0 -99
  137. package/src/utils/byString.ts +0 -3
  138. package/src/utils/cliUtils.ts +0 -112
  139. package/src/utils/copyBootstrapFiles.ts +0 -30
  140. package/src/utils/deviceUtils.ts +0 -76
  141. package/src/utils/errorUtils.ts +0 -63
  142. package/src/utils/fileUtils.ts +0 -257
  143. package/src/utils/githubUtils.ts +0 -102
  144. package/src/utils/jsonUtils.ts +0 -30
  145. package/src/utils/lintUtils.ts +0 -190
  146. package/src/utils/linuxDistro.spec.ts +0 -219
  147. package/src/utils/linuxDistro.ts +0 -326
  148. package/src/utils/logUtils.ts +0 -9
  149. package/src/utils/pathUtils.ts +0 -12
  150. package/src/utils/stringUtils.spec.ts +0 -95
  151. package/src/utils/stringUtils.ts +0 -103
  152. package/src/utils/tempDir.ts +0 -24
  153. package/src/utils/zipUtils.ts +0 -14
  154. package/test/ValdiSmokeTest.ts +0 -279
  155. package/test/helpers/AsyncHelpers.ts +0 -113
  156. package/test/helpers/CommandHelpers.ts +0 -37
  157. package/test/helpers/ProjectHelpers.ts +0 -153
  158. package/test/helpers/StreamHelpers.ts +0 -37
  159. package/test/helpers/TypeScriptClient.ts +0 -217
  160. package/tsconfig.dist.json +0 -8
  161. package/tsconfig.json +0 -42
package/README.md CHANGED
@@ -47,6 +47,7 @@ Now you can edit your TypeScript files and see changes instantly on your device!
47
47
  For complete documentation, see:
48
48
  - [Command Line Reference](https://github.com/Snapchat/Valdi/blob/main/docs/docs/command-line-references.md)
49
49
  - [Installation Guide](https://github.com/Snapchat/Valdi/blob/main/docs/INSTALL.md)
50
+ - [Troubleshooting](https://github.com/Snapchat/Valdi/blob/main/docs/TROUBLESHOOTING.md) — run `valdi doctor` to diagnose issues, or ask on [Discord](https://discord.gg/uJyNEeYX2U)
50
51
 
51
52
  ### Key Commands
52
53
 
@@ -71,6 +72,7 @@ For complete documentation, see:
71
72
  - Creates a new Valdi project in the current directory
72
73
  - Sets up BUILD.bazel, WORKSPACE, package.json, and source files
73
74
  - Supports multiple application templates (Hello World, Counter, etc.)
75
+ - Options: `-y` (skip confirmation), `-n` (project name), `-t` (application type), `-l` (local Valdi path), `-c` (clean directory first). Run `valdi bootstrap --help` for all options.
74
76
 
75
77
  **`valdi install <platform>`** - Build and install
76
78
  - Builds and installs app to connected device/simulator
@@ -80,6 +82,15 @@ For complete documentation, see:
80
82
  - Enables instant hot reload during development
81
83
  - Watches for file changes and updates app in milliseconds
82
84
 
85
+ **`valdi skills`** - AI assistant skills
86
+ - Installs Valdi context files into Claude Code, Cursor, or GitHub Copilot so AI tools generate correct Valdi code instead of React patterns
87
+ - `valdi skills install` — auto-detects installed AI tools and installs all skills
88
+ - `valdi skills list` — show available skills and install status per agent
89
+ - `valdi skills update` — re-install already-installed skills from the bundled package
90
+ - `valdi skills create` — scaffold a new skill (run from within the Valdi repo)
91
+
92
+ **Other commands:** `valdi build <platform>` (build without installing), `valdi package <platform>` (create distributable app), `valdi export <platform>` (export library for native apps), `valdi test` (run tests), `valdi lint check` / `valdi lint format` (lint and format code), `valdi log` (stream device logs), `valdi projectsync` (sync VS Code project and native bindings), `valdi completion` (shell autocomplete setup). Use `valdi <command> --help` for options.
93
+
83
94
  For complete command documentation, see [Command Line Reference](https://github.com/Snapchat/Valdi/blob/main/docs/docs/command-line-references.md).
84
95
 
85
96
  ### Creating New Modules
@@ -87,8 +98,8 @@ For complete command documentation, see [Command Line Reference](https://github.
87
98
  ```sh
88
99
  valdi new_module
89
100
 
90
- # Create module without prompts
91
- valdi new_module my_new_module --skip-checks --android-class-path='com.example.my_module' --ios-module-name='XYZMyModule'
101
+ # Create module without prompts (specify template to skip the prompt)
102
+ valdi new_module my_new_module --skip-checks --template=ui_component
92
103
 
93
104
  # Help
94
105
  $ valdi new_module --help
@@ -110,8 +121,10 @@ my_application/ # Root directory of your application
110
121
  └── modules/
111
122
  ├── module_a/
112
123
  │ ├── BUILD.bazel
113
- │ ├── android/ # Native Android sources
114
- │ ├── ios/ # Native iOS sources
124
+ │ ├── android/ # Native Android sources (Kotlin)
125
+ │ ├── ios/ # Native iOS sources (Objective-C)
126
+ │ ├── macos/ # Native macOS sources (Objective-C)
127
+ │ ├── web/ # Web sources (TypeScript, compiled by tsc)
115
128
  │ ├── cpp/ # Native C++ sources
116
129
  │ └── src/ # Valdi sources
117
130
  │ └── ModuleAComponent.tsx
@@ -132,12 +145,11 @@ Positionals:
132
145
  module-name Name of the Valdi module.
133
146
 
134
147
  Options:
135
- --debug Run with debug logging [boolean] [default: false]
136
- --version Show version number [boolean]
137
- --help Show help [boolean]
138
- --skip-checks Skips confirmation prompts. [boolean]
139
- --android-class-path Android class path to use for generated Android sources. [string]
140
- --ios-module-name iOS class prefix to use for generated iOS sources. [string]
148
+ --debug Run with debug logging [boolean] [default: false]
149
+ --version Show version number [boolean]
150
+ --help Show help [boolean]
151
+ --skip-checks Skips confirmation prompts. [boolean]
152
+ --template Module template to use (skips the prompt). One of: ui_component, polyglot_bridge_module, polyglot_view_module [string]
141
153
  ```
142
154
 
143
155
  ## For Contributors
@@ -0,0 +1,74 @@
1
+ # Contributing Skills
2
+
3
+ Skills are neutral, agent-agnostic markdown files that teach AI assistants how to work with the Valdi framework. They are installed into your AI tool of choice using `valdi skills install`.
4
+
5
+ ## What is a skill?
6
+
7
+ A skill is a single `skill.md` file containing focused guidance for a specific area of Valdi development. Skills are:
8
+
9
+ - **Agent-agnostic** — plain markdown with no tool-specific frontmatter or directives
10
+ - **Self-contained** — each skill covers one topic without assuming other skills are loaded
11
+ - **Code-first** — concrete examples with correct and incorrect patterns labeled clearly
12
+ - **Accurate** — verified against the actual Valdi source and documentation
13
+
14
+ ## skill.md format
15
+
16
+ ```markdown
17
+ # Skill Title
18
+
19
+ Brief description of what this skill covers.
20
+
21
+ ## When to use
22
+
23
+ Optional section: describe the file types or scenarios where this skill applies.
24
+
25
+ ## Key concepts
26
+
27
+ Prose or list explaining important ideas.
28
+
29
+ ## Correct patterns
30
+
31
+ \`\`\`typescript
32
+ // ✅ Correct example
33
+ \`\`\`
34
+
35
+ ## Common mistakes
36
+
37
+ \`\`\`typescript
38
+ // ❌ Wrong example
39
+ \`\`\`
40
+ ```
41
+
42
+ Rules:
43
+ - Start with an H1 title
44
+ - Include code examples — skills without examples are less useful
45
+ - Label examples as `// ✅` (correct) or `// ❌` (wrong)
46
+ - No agent-specific frontmatter (no `alwaysApply`, no YAML blocks)
47
+ - No secrets, API keys, or proprietary Snap information
48
+
49
+ ## Scaffolding a new skill
50
+
51
+ Run the interactive scaffold command from within the Valdi framework checkout:
52
+
53
+ ```bash
54
+ valdi skills create
55
+ ```
56
+
57
+ You will be prompted for a name, description, and category. The command creates `ai-skills/skills/<name>/skill.md` in the correct location and registers the entry in `ai-skills/registry.json` automatically.
58
+
59
+ ## Submitting a skill to the public registry
60
+
61
+ 1. Fork [github.com/Snapchat/Valdi](https://github.com/Snapchat/Valdi)
62
+ 2. Run `valdi skills create` from the repo root — it creates the skill file and registers it in `registry.json` automatically
63
+ 3. Fill in the `skill.md` content
64
+ 4. Open a pull request — title it `[skill] Add <your-skill-name>`
65
+
66
+ ## Review criteria
67
+
68
+ Pull requests adding or updating skills are reviewed for:
69
+
70
+ - **Accuracy** — does the code compile and run correctly against current Valdi?
71
+ - **Code examples** — are there concrete `✅` / `❌` examples?
72
+ - **Breadth** — does it cover the common cases a developer would encounter?
73
+ - **No hallucinations** — especially for TSX skills, ensure no React patterns are presented as valid Valdi
74
+ - **Conciseness** — focused guidance is more useful than exhaustive reference dumps
@@ -0,0 +1,20 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "skills": [
4
+ { "name": "valdi-tsx", "description": "Valdi TSX component patterns, lifecycle, styling — NOT React", "tags": ["tsx", "components", "patterns", "styling"], "path": "skills/valdi-tsx/skill.md", "category": ["client"] },
5
+ { "name": "valdi-bazel", "description": "Valdi Bazel build rules, valdi_module, platform builds", "tags": ["bazel", "build"], "path": "skills/valdi-bazel/skill.md", "category": ["framework", "client"] },
6
+ { "name": "valdi-testing", "description": "Valdi unit and integration testing patterns", "tags": ["testing"], "path": "skills/valdi-testing/skill.md", "category": ["client"] },
7
+ { "name": "valdi-ios", "description": "Valdi iOS platform integration, Swift/ObjC bridging", "tags": ["ios", "swift", "objc"], "path": "skills/valdi-ios/skill.md", "category": ["framework", "client"] },
8
+ { "name": "valdi-android", "description": "Valdi Android platform integration, Kotlin/Java bridging", "tags": ["android", "kotlin"], "path": "skills/valdi-android/skill.md", "category": ["framework", "client"] },
9
+ { "name": "valdi-cpp-runtime", "description": "Valdi C++ runtime internals, renderer, event system", "tags": ["cpp", "runtime"], "path": "skills/valdi-cpp-runtime/skill.md", "category": ["framework"] },
10
+ { "name": "valdi-compiler", "description": "Valdi compiler pipeline, TSX→native compilation", "tags": ["compiler"], "path": "skills/valdi-compiler/skill.md", "category": ["framework"] },
11
+ { "name": "valdi-polyglot-module", "description": "Valdi polyglot module system: cross-platform APIs, web polyglot entry pattern, webPolyglotViews", "tags": ["polyglot", "modules", "web"], "path": "skills/valdi-polyglot-module/skill.md", "category": ["client"] },
12
+ { "name": "valdi-custom-view", "description": "Valdi custom native view integration", "tags": ["custom-view", "native"], "path": "skills/valdi-custom-view/skill.md", "category": ["client"] },
13
+ { "name": "valdi-overview", "description": "Valdi framework overview and project conventions", "tags": ["overview", "conventions"], "path": "skills/valdi-overview/skill.md", "category": ["client"] },
14
+ { "name": "valdi-async", "description": "Valdi async lifecycle safety: CancelablePromise, registerDisposable, isDestroyed guards", "tags": ["async", "lifecycle", "http"], "path": "skills/valdi-async/skill.md", "category": ["client"] },
15
+ { "name": "valdi-perf", "description": "Valdi performance: viewModel identity stability, createReusableCallback, layout vs view, Style interning", "tags": ["performance", "rendering"], "path": "skills/valdi-perf/skill.md", "category": ["client"] },
16
+ { "name": "valdi-component-tests", "description": "Valdi component test patterns: elementKeyFind, componentTypeFind, tapNodeWithKey, discriminated unions, arrays", "tags": ["testing", "components", "jasmine"], "path": "skills/valdi-component-tests/skill.md", "category": ["client"] },
17
+ { "name": "valdi-setup", "description": "Valdi module setup: BUILD.bazel, valdi_module(), tsconfig, deps, ios_module_name, hot reload", "tags": ["setup", "bazel", "build"], "path": "skills/valdi-setup/skill.md", "category": ["client"] },
18
+ { "name": "valdi-migrate", "description": "Migrate Flutter, React, or Jetpack Compose code to Valdi — component model, lifecycle, element mapping tables", "tags": ["migration", "flutter", "react", "compose"], "path": "skills/valdi-migrate/skill.md", "category": ["client"] }
19
+ ]
20
+ }
@@ -0,0 +1,89 @@
1
+ # Android Runtime Rules
2
+
3
+ **Applies to**: Kotlin/Java files in `/valdi/src/valdi/android/` and related Android runtime code
4
+
5
+ ## Overview
6
+
7
+ The Valdi Android runtime bridges TypeScript/Valdi components to native Android views. It's implemented in Kotlin and C++ (via JNI).
8
+
9
+ ## Code Style
10
+
11
+ - **4-space indentation** for Kotlin/Java
12
+ - Follow Kotlin coding conventions
13
+ - Use Kotlin features (data classes, extension functions, etc.)
14
+
15
+ ## Key Concepts
16
+
17
+ ### View Rendering
18
+
19
+ - Valdi components map to Android Views
20
+ - View recycling for performance
21
+ - Efficient view updates
22
+
23
+ ### Platform Bridge
24
+
25
+ - JNI bridge to C++ runtime
26
+ - Kotlin/Java to native code communication
27
+ - Performance-critical paths
28
+
29
+ ## Common Patterns
30
+
31
+ ### Bazel Android Targets
32
+
33
+ ```python
34
+ android_library(
35
+ name = "valdi_android",
36
+ srcs = glob(["**/*.kt", "**/*.java"]),
37
+ )
38
+ ```
39
+
40
+ ### View Binding
41
+
42
+ - Custom view implementations
43
+ - Attribute binding for Valdi properties
44
+ - Event handling
45
+
46
+ ## Testing
47
+
48
+ ```bash
49
+ # Run Android runtime tests
50
+ bazel test //valdi:test_java
51
+
52
+ # Run with coverage
53
+ bazel coverage //valdi:test_java
54
+ ```
55
+
56
+ Test files are in `/valdi/test/java/`
57
+
58
+ ## Building
59
+
60
+ ```bash
61
+ # Build Android runtime library
62
+ bazel build //valdi:valdi_android
63
+
64
+ # Test with hello world app
65
+ valdi install android
66
+ cd apps/helloworld
67
+ valdi install android
68
+ ```
69
+
70
+ ## Platform-Specific Notes
71
+
72
+ 1. **API Level** - Be mindful of minimum API level
73
+ 2. **Android NDK** - C++ integration via NDK
74
+ 3. **Permissions** - Handle runtime permissions appropriately
75
+ 4. **Lifecycle** - Android Activity/Fragment lifecycle
76
+
77
+ ## Important
78
+
79
+ - **Performance** - View creation and updates are critical
80
+ - **Memory** - Be careful with leaks (Activity context)
81
+ - **Threading** - UI thread vs background threads
82
+ - **Compatibility** - Support multiple Android versions
83
+
84
+ ## More Information
85
+
86
+ - Runtime source: `/valdi/src/valdi/android/`
87
+ - Runtime tests: `/valdi/test/java/`
88
+ - Build config: `/valdi/BUILD.bazel`
89
+ - Framework docs: `/AGENTS.md`
@@ -0,0 +1,246 @@
1
+ # Valdi Async & Lifecycle Safety
2
+
3
+ Async operations that complete after a component is destroyed will call `setState()`
4
+ on a dead component — the framework throws an error. The fix is always to cancel or
5
+ guard before the callback fires.
6
+
7
+ ## HTTPClient: Store, Cancel, Repeat
8
+
9
+ `HTTPClient` methods return `CancelablePromise<HTTPResponse>`. Store it in a typed
10
+ field so you can cancel it in `onDestroy()` and before starting a new request in
11
+ `onViewModelUpdate()`.
12
+
13
+ ```typescript
14
+ import { Component, StatefulComponent } from 'valdi_core/src/Component';
15
+ import { CancelablePromise } from 'valdi_core/src/CancelablePromise';
16
+ import { HTTPClient } from 'valdi_http/src/HTTPClient';
17
+ import { HTTPResponse } from 'valdi_http/src/HTTPTypes';
18
+
19
+ interface UserState {
20
+ user: { name: string } | null;
21
+ loading: boolean;
22
+ }
23
+
24
+ class UserProfile extends StatefulComponent<UserProfileViewModel, UserState> {
25
+ state: UserState = { user: null, loading: true };
26
+
27
+ private client = new HTTPClient('https://api.example.com');
28
+ private request?: CancelablePromise<HTTPResponse>;
29
+
30
+ onCreate(): void {
31
+ this.fetchUser(this.viewModel.userId);
32
+ }
33
+
34
+ onViewModelUpdate(previous?: UserProfileViewModel): void {
35
+ if (this.viewModel.userId !== previous?.userId) {
36
+ this.request?.cancel?.(); // Cancel in-flight before starting new one
37
+ this.fetchUser(this.viewModel.userId);
38
+ }
39
+ }
40
+
41
+ onDestroy(): void {
42
+ this.request?.cancel?.(); // Always clean up
43
+ }
44
+
45
+ private fetchUser(id: string): void {
46
+ this.request = this.client.get(`/users/${id}`);
47
+ this.request.then(response => {
48
+ const user = JSON.parse(new TextDecoder().decode(response.body));
49
+ this.setState({ user, loading: false });
50
+ });
51
+ }
52
+
53
+ onRender(): void {
54
+ if (this.state.loading) {
55
+ <spinner />;
56
+ return;
57
+ }
58
+ <label value={this.state.user?.name ?? ''} />;
59
+ }
60
+ }
61
+ ```
62
+
63
+ **Important:** `cancel` is an optional method on `CancelablePromise` — always use
64
+ `?.cancel?.()`, not `?.cancel()`.
65
+
66
+ ## registerDisposable: Timers and Subscriptions
67
+
68
+ For anything that emits over time (timers, event emitters, observables), use
69
+ `registerDisposable()`. The framework calls `cancel()` on all registered disposables
70
+ in `onDestroy()` automatically — you don't need to override `onDestroy()` for these.
71
+
72
+ ```typescript
73
+ class LiveClock extends Component<{}> {
74
+ onCreate(): void {
75
+ // ❌ Timer leaks if component is destroyed
76
+ setInterval(() => this.tick(), 1000);
77
+
78
+ // ✅ Automatically cancelled on destroy
79
+ const id = setInterval(() => this.tick(), 1000);
80
+ this.registerDisposable({ cancel: () => clearInterval(id) });
81
+ }
82
+
83
+ private tick = () => { /* ... */ };
84
+ }
85
+ ```
86
+
87
+ Same pattern for any subscription-style API:
88
+
89
+ ```typescript
90
+ onCreate(): void {
91
+ const unsubscribe = eventEmitter.on('change', this.handleChange);
92
+ this.registerDisposable({ cancel: unsubscribe });
93
+ }
94
+ ```
95
+
96
+ ## isDestroyed() Guard for Plain Promises
97
+
98
+ When using `async/await` or plain `Promise` chains that can't be cancelled, guard
99
+ `setState()` with `isDestroyed()` before calling it:
100
+
101
+ ```typescript
102
+ private async loadData(): Promise<void> {
103
+ const result = await someAsyncOperation();
104
+
105
+ if (this.isDestroyed()) return; // Component unmounted while awaiting
106
+
107
+ this.setState({ data: result });
108
+ }
109
+ ```
110
+
111
+ Prefer `CancelablePromise` + `registerDisposable` over this pattern where possible —
112
+ they make cancellation explicit and don't rely on the check being remembered.
113
+
114
+ ## onViewModelUpdate: Cancel Before Restart
115
+
116
+ When a viewModel update requires fetching new data, always cancel the previous
117
+ request before starting a new one. Skipping this means two requests can be in flight
118
+ simultaneously and the earlier one can resolve last, overwriting newer data.
119
+
120
+ ```typescript
121
+ onViewModelUpdate(previous?: MyViewModel): void {
122
+ if (this.viewModel.query !== previous?.query) {
123
+ this.searchRequest?.cancel?.(); // ← required
124
+ this.searchRequest = this.client.get(`/search?q=${this.viewModel.query}`);
125
+ this.searchRequest.then(response => {
126
+ this.setState({ results: parse(response) });
127
+ });
128
+ }
129
+ }
130
+ ```
131
+
132
+ ## Observable Subscriptions
133
+
134
+ For RxJS or observable-based APIs, prefer `registerDisposable` for one-off subscriptions
135
+ or the `Subscription` class for managing multiple subscriptions as a group:
136
+
137
+ ```typescript
138
+ import { Subscription } from 'rxjs';
139
+
140
+ class FeedComponent extends StatefulComponent<FeedViewModel, FeedState> {
141
+ private subscription = new Subscription();
142
+
143
+ onCreate(): void {
144
+ // Add multiple subscriptions to the group
145
+ this.subscription.add(
146
+ this.viewModel.feedItems$.subscribe({ next: items => this.setState({ items }) })
147
+ );
148
+ this.subscription.add(
149
+ this.viewModel.loading$.subscribe({ next: loading => this.setState({ loading }) })
150
+ );
151
+ }
152
+
153
+ onDestroy(): void {
154
+ this.subscription?.unsubscribe(); // Cancels all at once
155
+ }
156
+ }
157
+ ```
158
+
159
+ For a single subscription, `registerDisposable` is simpler:
160
+
161
+ ```typescript
162
+ onCreate(): void {
163
+ this.registerDisposable(
164
+ this.viewModel.counter$.subscribe({ next: count => this.setState({ count }) })
165
+ );
166
+ // No onDestroy() override needed
167
+ }
168
+ ```
169
+
170
+ ### Preventing redundant re-renders with distinctUntilChanged
171
+
172
+ Subscribe with `distinctUntilChanged()` to skip emissions where the value hasn't
173
+ actually changed — avoids a `setState` call and a re-render for each identical value:
174
+
175
+ ```typescript
176
+ import { distinctUntilChanged } from 'rxjs/operators';
177
+
178
+ this.subscription.add(
179
+ this.viewModel.title$.pipe(distinctUntilChanged()).subscribe({
180
+ next: title => this.setState({ title }),
181
+ })
182
+ );
183
+ ```
184
+
185
+ ## setTimeoutInterruptible for Debounce / Race Conditions
186
+
187
+ When a delayed action must be cancelled if conditions change (e.g. search debounce,
188
+ retry delay), use `setTimeoutInterruptible` rather than a bare `setTimeout`:
189
+
190
+ ```typescript
191
+ import { setTimeoutInterruptible } from 'valdi_core/src/SetTimeout';
192
+
193
+ // setTimeoutInterruptible returns a number (timer ID) — cancel with clearTimeout()
194
+ class SearchBar extends StatefulComponent<SearchViewModel, SearchState> {
195
+ private debounceId?: number;
196
+
197
+ onViewModelUpdate(previous?: SearchViewModel): void {
198
+ if (this.viewModel.query !== previous?.query) {
199
+ clearTimeout(this.debounceId); // Cancel any pending debounce
200
+ this.debounceId = setTimeoutInterruptible(() => {
201
+ this.fetchResults(this.viewModel.query);
202
+ }, 300);
203
+ }
204
+ }
205
+ }
206
+ ```
207
+
208
+ ## promiseToCancelablePromise
209
+
210
+ When you have a plain `Promise` (e.g. from a third-party library) that needs to participate in Valdi's cancellation system, wrap it with `promiseToCancelablePromise`:
211
+
212
+ ```typescript
213
+ import { CancelablePromise, promiseToCancelablePromise } from 'valdi_core/src/CancelablePromise';
214
+
215
+ class MyComponent extends StatefulComponent<MyViewModel, MyState> {
216
+ private request?: CancelablePromise<string>;
217
+
218
+ onCreate(): void {
219
+ const rawPromise: Promise<string> = thirdPartyApi.fetchData();
220
+ this.request = promiseToCancelablePromise(rawPromise, () => {
221
+ // optional cleanup on cancel
222
+ });
223
+ this.request.then(data => {
224
+ if (this.isDestroyed()) return;
225
+ this.setState({ data });
226
+ });
227
+ }
228
+
229
+ onDestroy(): void {
230
+ this.request?.cancel?.();
231
+ }
232
+ }
233
+ ```
234
+
235
+ Prefer `CancelablePromise` directly (e.g. `HTTPClient`) when available — `promiseToCancelablePromise` is the bridge for external APIs.
236
+
237
+ ## Import Paths
238
+
239
+ ```typescript
240
+ import { CancelablePromise, promiseToCancelablePromise } from 'valdi_core/src/CancelablePromise';
241
+ import { HTTPClient } from 'valdi_http/src/HTTPClient';
242
+ import { HTTPResponse } from 'valdi_http/src/HTTPTypes';
243
+ import { setTimeoutInterruptible } from 'valdi_core/src/SetTimeout';
244
+ import { Subscription } from 'rxjs';
245
+ import { distinctUntilChanged } from 'rxjs/operators';
246
+ ```
@@ -0,0 +1,19 @@
1
+ load("//bzl/valdi:valdi_module.bzl", "valdi_module")
2
+
3
+ valdi_module(
4
+ name = "tests",
5
+ srcs = glob([
6
+ "src/**/*.ts",
7
+ "src/**/*.tsx",
8
+ ]) + [
9
+ "tsconfig.json",
10
+ ],
11
+ android_output_target = "release",
12
+ ios_module_name = "SCCValdiAsyncRef",
13
+ ios_output_target = "release",
14
+ visibility = ["//visibility:public"],
15
+ deps = [
16
+ "//src/valdi_modules/src/valdi/valdi_core",
17
+ "//src/valdi_modules/src/valdi/valdi_http",
18
+ ],
19
+ )
@@ -0,0 +1,25 @@
1
+ # valdi-async skill tests
2
+
3
+ Compile check for the async lifecycle safety patterns taught in `skill.md`.
4
+
5
+ ## What's tested
6
+
7
+ `src/reference.tsx` exercises:
8
+ - `HTTPClient` + `CancelablePromise`: store in field, cancel in `onDestroy`, cancel before restart in `onViewModelUpdate`
9
+ - `registerDisposable` with `setInterval` for auto-cleanup subscriptions
10
+ - `isDestroyed()` guard for plain `Promise` / `async/await`
11
+ - `setTimeoutInterruptible` for debounce — returns `number`, cancel with `clearTimeout()`
12
+ - `promiseToCancelablePromise` wrapping a third-party `Promise`
13
+
14
+ ## Compile check
15
+
16
+ ```bash
17
+ cd client/src/open_source
18
+ bazel build //ai-skills/skills/valdi-async/tests:tests
19
+ ```
20
+
21
+ Expected: `Build completed successfully`
22
+
23
+ ## Updating
24
+
25
+ When Valdi APIs change (import paths, type signatures), update `src/reference.tsx` to match and keep it compiling. Also update `../skill.md` with any corrected patterns.