@snap/valdi 1.0.7 → 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 (160) hide show
  1. package/README.md +12 -3
  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/bundled-skills/skills/valdi-overview/skill.md +63 -0
  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 +0 -7
  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 +0 -1
  53. package/dist/setup/versions.js +1 -1
  54. package/dist/utils/skillsAdapters.js +140 -0
  55. package/dist/utils/skillsRegistry.js +40 -0
  56. package/package.json +6 -1
  57. package/.bazelignore +0 -2
  58. package/.bootstrap/apps/cli_application/BUILD.bazel.template +0 -7
  59. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +0 -11
  60. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +0 -1
  61. package/.bootstrap/apps/ui_application/.eslint.rc +0 -27
  62. package/.bootstrap/apps/ui_application/BUILD.bazel.template +0 -19
  63. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +0 -21
  64. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  65. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +0 -133
  66. package/.bootstrap/apps/ui_application/package.json +0 -24
  67. package/.bootstrap/modules/cpp_bridge_module/BUILD.bazel.template +0 -21
  68. package/.bootstrap/modules/cpp_bridge_module/cpp/CalculatorModuleFactory.cpp.template +0 -28
  69. package/.bootstrap/modules/cpp_bridge_module/src/Calculator.d.ts +0 -4
  70. package/.bootstrap/modules/ios_android_bridge_module/BUILD.bazel.template +0 -39
  71. package/.bootstrap/modules/ios_android_bridge_module/android/CalculatorModuleFactory.kt.template +0 -18
  72. package/.bootstrap/modules/ios_android_bridge_module/ios/SCCCalculatorModuleFactory.m.template +0 -31
  73. package/.bootstrap/modules/ios_android_bridge_module/src/Calculator.d.ts +0 -4
  74. package/.bootstrap/modules/ios_android_view_module/BUILD.bazel.template +0 -41
  75. package/.bootstrap/modules/ios_android_view_module/android/CircleView.kt.template +0 -42
  76. package/.bootstrap/modules/ios_android_view_module/android/CircleViewAttributesBinder.kt.template +0 -60
  77. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.h +0 -6
  78. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.m +0 -82
  79. package/.bootstrap/modules/ios_android_view_module/src/Circle.tsx.template +0 -15
  80. package/.bootstrap/modules/ui_component/BUILD.bazel.template +0 -34
  81. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +0 -45
  82. package/.config/copyconfig.json +0 -10
  83. package/.editorconfig +0 -21
  84. package/.eslintignore +0 -1
  85. package/.eslintrc.js +0 -72
  86. package/.github/README.md +0 -164
  87. package/.metadata/.bazelrc.template +0 -91
  88. package/.metadata/.bazelversion.template +0 -1
  89. package/.metadata/.cursorrules.template +0 -60
  90. package/.metadata/.editorconfig.template +0 -37
  91. package/.metadata/.eslintrc.js.template +0 -27
  92. package/.metadata/.gitignore.template +0 -4
  93. package/.metadata/.prettierrc.json.template +0 -7
  94. package/.metadata/.watchmanconfig.template +0 -8
  95. package/.metadata/AGENTS.md.template +0 -282
  96. package/.metadata/README.md.template +0 -31
  97. package/.metadata/WORKSPACE.template +0 -57
  98. package/.metadata/config.yaml.template +0 -1
  99. package/.metadata/package.json.template +0 -23
  100. package/.prettierignore +0 -2
  101. package/.prettierrc.json +0 -7
  102. package/LINUX_COMPATIBILITY.md +0 -248
  103. package/prettier.config.js +0 -4
  104. package/scripts/sync-agents-md.sh +0 -44
  105. package/scripts/update-agents-templates.ts +0 -170
  106. package/spec/support/jasmine.json +0 -6
  107. package/src/commands/bootstrap.ts +0 -410
  108. package/src/commands/build.ts +0 -89
  109. package/src/commands/devSetup.ts +0 -17
  110. package/src/commands/doctor.ts +0 -1832
  111. package/src/commands/export.ts +0 -131
  112. package/src/commands/hotreload.ts +0 -108
  113. package/src/commands/install.ts +0 -93
  114. package/src/commands/lint.ts +0 -15
  115. package/src/commands/lint_commands/lintCheck.ts +0 -53
  116. package/src/commands/lint_commands/lintFormat.ts +0 -49
  117. package/src/commands/log.ts +0 -108
  118. package/src/commands/newModule.ts +0 -286
  119. package/src/commands/package.ts +0 -102
  120. package/src/commands/projectsync.ts +0 -488
  121. package/src/commands/test.ts +0 -68
  122. package/src/core/constants.ts +0 -98
  123. package/src/core/errors.ts +0 -10
  124. package/src/index.ts +0 -27
  125. package/src/setup/DevSetupHelper.ts +0 -290
  126. package/src/setup/linuxSetup.ts +0 -261
  127. package/src/setup/macOSSetup.ts +0 -156
  128. package/src/setup/setupEntryPoint.ts +0 -64
  129. package/src/setup/versions.ts +0 -8
  130. package/src/utils/ArgumentsResolver.ts +0 -23
  131. package/src/utils/BazelClient.ts +0 -285
  132. package/src/utils/Digraph.ts +0 -81
  133. package/src/utils/LoadingIndicator.ts +0 -43
  134. package/src/utils/applicationUtils.ts +0 -276
  135. package/src/utils/buildInfo.ts +0 -99
  136. package/src/utils/byString.ts +0 -3
  137. package/src/utils/cliUtils.ts +0 -112
  138. package/src/utils/copyBootstrapFiles.ts +0 -30
  139. package/src/utils/deviceUtils.ts +0 -76
  140. package/src/utils/errorUtils.ts +0 -63
  141. package/src/utils/fileUtils.ts +0 -257
  142. package/src/utils/githubUtils.ts +0 -102
  143. package/src/utils/jsonUtils.ts +0 -30
  144. package/src/utils/lintUtils.ts +0 -190
  145. package/src/utils/linuxDistro.spec.ts +0 -219
  146. package/src/utils/linuxDistro.ts +0 -326
  147. package/src/utils/logUtils.ts +0 -9
  148. package/src/utils/pathUtils.ts +0 -12
  149. package/src/utils/stringUtils.spec.ts +0 -95
  150. package/src/utils/stringUtils.ts +0 -103
  151. package/src/utils/tempDir.ts +0 -24
  152. package/src/utils/zipUtils.ts +0 -14
  153. package/test/ValdiSmokeTest.ts +0 -279
  154. package/test/helpers/AsyncHelpers.ts +0 -113
  155. package/test/helpers/CommandHelpers.ts +0 -37
  156. package/test/helpers/ProjectHelpers.ts +0 -153
  157. package/test/helpers/StreamHelpers.ts +0 -37
  158. package/test/helpers/TypeScriptClient.ts +0 -217
  159. package/tsconfig.dist.json +0 -8
  160. package/tsconfig.json +0 -42
package/README.md CHANGED
@@ -82,6 +82,13 @@ For complete documentation, see:
82
82
  - Enables instant hot reload during development
83
83
  - Watches for file changes and updates app in milliseconds
84
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
+
85
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.
86
93
 
87
94
  For complete command documentation, see [Command Line Reference](https://github.com/Snapchat/Valdi/blob/main/docs/docs/command-line-references.md).
@@ -114,8 +121,10 @@ my_application/ # Root directory of your application
114
121
  └── modules/
115
122
  ├── module_a/
116
123
  │ ├── BUILD.bazel
117
- │ ├── android/ # Native Android sources
118
- │ ├── 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)
119
128
  │ ├── cpp/ # Native C++ sources
120
129
  │ └── src/ # Valdi sources
121
130
  │ └── ModuleAComponent.tsx
@@ -140,7 +149,7 @@ Options:
140
149
  --version Show version number [boolean]
141
150
  --help Show help [boolean]
142
151
  --skip-checks Skips confirmation prompts. [boolean]
143
- --template Module template to use (skips the prompt). One of: ui_component, ios_android_bridge_module, cpp_bridge_module, ios_android_view_module [string]
152
+ --template Module template to use (skips the prompt). One of: ui_component, polyglot_bridge_module, polyglot_view_module [string]
144
153
  ```
145
154
 
146
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.