@snap/valdi 1.0.8 → 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 (121) hide show
  1. package/.bootstrap/apps/cli_application/BUILD.bazel.template +7 -0
  2. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +11 -0
  3. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +1 -0
  4. package/.bootstrap/apps/ui_application/.eslint.rc +27 -0
  5. package/.bootstrap/apps/ui_application/BUILD.bazel.template +19 -0
  6. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +21 -0
  7. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  8. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +133 -0
  9. package/.bootstrap/apps/ui_application/package.json +24 -0
  10. package/.bootstrap/modules/polyglot_bridge_module/BUILD.bazel.template +54 -0
  11. package/.bootstrap/modules/polyglot_bridge_module/android/CalculatorModuleFactory.kt.template +18 -0
  12. package/.bootstrap/modules/polyglot_bridge_module/ios/SCCCalculatorModuleFactory.m.template +31 -0
  13. package/.bootstrap/modules/polyglot_bridge_module/src/Calculator.d.ts +4 -0
  14. package/.bootstrap/modules/polyglot_bridge_module/web/Calculator.ts +11 -0
  15. package/.bootstrap/modules/polyglot_bridge_module/web/tsconfig.json +16 -0
  16. package/.bootstrap/modules/polyglot_view_module/BUILD.bazel.template +75 -0
  17. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeView.kt.template +41 -0
  18. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeViewAttributesBinder.kt.template +17 -0
  19. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.h +8 -0
  20. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.m +23 -0
  21. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.h +8 -0
  22. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.m +23 -0
  23. package/.bootstrap/modules/polyglot_view_module/src/PolyglotCustomView.tsx.template +23 -0
  24. package/.bootstrap/modules/polyglot_view_module/web/PolyglotWeb.ts.template +30 -0
  25. package/.bootstrap/modules/polyglot_view_module/web/tsconfig.json +16 -0
  26. package/.bootstrap/modules/ui_component/BUILD.bazel.template +34 -0
  27. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +45 -0
  28. package/.metadata/.bazelrc.template +92 -0
  29. package/.metadata/.bazelversion.template +1 -0
  30. package/.metadata/.editorconfig.template +37 -0
  31. package/.metadata/.eslintrc.js.template +27 -0
  32. package/.metadata/.gitignore.template +4 -0
  33. package/.metadata/.prettierrc.json.template +7 -0
  34. package/.metadata/.watchmanconfig.template +8 -0
  35. package/.metadata/AGENTS.md.template +16 -0
  36. package/.metadata/MODULE.bazel.template +62 -0
  37. package/.metadata/README.md.template +31 -0
  38. package/.metadata/config.yaml.template +1 -0
  39. package/.metadata/package.json.template +23 -0
  40. package/.metadata/skill-reference.tsx.template +8 -0
  41. package/.metadata/skill-tests-BUILD.bazel.template +21 -0
  42. package/.metadata/skill-tests-README.md.template +17 -0
  43. package/.metadata/skill.md.template +27 -0
  44. package/bundled-skills/registry.json +14 -2
  45. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  46. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  47. package/bundled-skills/skills/valdi-bazel/skill.md +21 -2
  48. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  49. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  50. package/bundled-skills/skills/valdi-custom-view/skill.md +49 -5
  51. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  52. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  53. package/bundled-skills/skills/valdi-inspect/skill.md +217 -0
  54. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  55. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  56. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  57. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  58. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  59. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  60. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  61. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  62. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  63. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  64. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  65. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  66. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  67. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  68. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  69. package/bundled-skills/skills/valdi-polyglot-module/skill.md +131 -12
  70. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  71. package/bundled-skills/skills/valdi-profile/skill.md +126 -0
  72. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  73. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  74. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  75. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  76. package/dist/commands/agentCheck.js +184 -0
  77. package/dist/commands/analyze.js +16 -0
  78. package/dist/commands/analyze_commands/duplicates.js +134 -0
  79. package/dist/commands/bootstrap.js +57 -73
  80. package/dist/commands/doctor.js +40 -203
  81. package/dist/commands/hotreload.js +15 -0
  82. package/dist/commands/inspect.js +16 -0
  83. package/dist/commands/inspect_commands/contexts.js +55 -0
  84. package/dist/commands/inspect_commands/devices.js +53 -0
  85. package/dist/commands/inspect_commands/heap.js +59 -0
  86. package/dist/commands/inspect_commands/select.js +43 -0
  87. package/dist/commands/inspect_commands/snapshot.js +129 -0
  88. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  89. package/dist/commands/inspect_commands/status.js +68 -0
  90. package/dist/commands/inspect_commands/tree.js +86 -0
  91. package/dist/commands/preview.js +81 -0
  92. package/dist/commands/profile.js +16 -0
  93. package/dist/commands/profile_commands/capture.js +106 -0
  94. package/dist/commands/projectsync.js +9 -7
  95. package/dist/commands/skills_commands/install.js +6 -1
  96. package/dist/commands/skills_commands/update.js +2 -1
  97. package/dist/core/analyze/clusterer.js +150 -0
  98. package/dist/core/analyze/fingerprint.js +2 -0
  99. package/dist/core/analyze/knownPatterns.js +76 -0
  100. package/dist/core/analyze/parser.js +177 -0
  101. package/dist/core/analyze/reporter.js +83 -0
  102. package/dist/core/analyze/scanner.js +172 -0
  103. package/dist/core/analyze/similarity.js +56 -0
  104. package/dist/core/constants.js +1 -1
  105. package/dist/core/packageFiles.spec.js +29 -0
  106. package/dist/preview/previewGenerator.js +240 -0
  107. package/dist/preview/previewGenerator.spec.js +203 -0
  108. package/dist/preview/viewModelParser.js +86 -0
  109. package/dist/preview/viewModelParser.spec.js +171 -0
  110. package/dist/setup/DevSetupHelper.js +0 -51
  111. package/dist/setup/linuxSetup.js +0 -2
  112. package/dist/setup/macOSSetup.js +1 -4
  113. package/dist/utils/BazelClient.js +15 -0
  114. package/dist/utils/daemonClient.js +344 -0
  115. package/dist/utils/hermesClient.js +252 -0
  116. package/dist/utils/skillsAdapters.js +86 -5
  117. package/dist/utils/skillsAdapters.spec.js +60 -0
  118. package/dist/utils/skillsRegistry.js +8 -0
  119. package/dist/utils/stringUtils.spec.js +1 -1
  120. package/package.json +30 -12
  121. package/dist/setup/versions.js +0 -8
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ require("jasmine");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const os = tslib_1.__importStar(require("os"));
7
+ const path = tslib_1.__importStar(require("path"));
8
+ const viewModelParser_1 = require("./viewModelParser");
9
+ describe('viewModelParser', () => {
10
+ let tmpDir;
11
+ beforeEach(() => {
12
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vmp-test-'));
13
+ });
14
+ afterEach(() => {
15
+ fs.rmSync(tmpDir, { recursive: true, force: true });
16
+ });
17
+ function writeComponent(filename, content) {
18
+ const filePath = path.join(tmpDir, filename);
19
+ fs.writeFileSync(filePath, content, 'utf8');
20
+ return filePath;
21
+ }
22
+ describe('parseComponentFile', () => {
23
+ it('parses a simple Component with ViewModel', () => {
24
+ const filePath = writeComponent('Simple.tsx', `
25
+ import { Component } from 'valdi_core/src/Component';
26
+
27
+ export interface SimpleViewModel {
28
+ title: string;
29
+ count: number;
30
+ enabled: boolean;
31
+ }
32
+
33
+ export class Simple extends Component<SimpleViewModel, {}> {
34
+ onRender(): void {}
35
+ }
36
+ `);
37
+ const result = (0, viewModelParser_1.parseComponentFile)(filePath);
38
+ expect(result.componentName).toBe('Simple');
39
+ expect(result.viewModelName).toBe('SimpleViewModel');
40
+ expect(result.props.length).toBe(3);
41
+ expect(result.props[0].name).toBe('title');
42
+ expect(result.props[0].typeString).toBe('string');
43
+ expect(result.props[0].optional).toBe(false);
44
+ expect(result.props[1].name).toBe('count');
45
+ expect(result.props[1].typeString).toBe('number');
46
+ expect(result.props[2].name).toBe('enabled');
47
+ expect(result.props[2].isBoolean).toBe(true);
48
+ });
49
+ it('parses optional props', () => {
50
+ const filePath = writeComponent('Optional.tsx', `
51
+ export interface OptViewModel {
52
+ label: string;
53
+ subtitle?: string;
54
+ icon?: number;
55
+ }
56
+ export class OptComponent extends Component<OptViewModel, {}> {
57
+ onRender(): void {}
58
+ }
59
+ `);
60
+ const result = (0, viewModelParser_1.parseComponentFile)(filePath);
61
+ expect(result.props.length).toBe(3);
62
+ expect(result.props[0].optional).toBe(false);
63
+ expect(result.props[1].optional).toBe(true);
64
+ expect(result.props[2].optional).toBe(true);
65
+ });
66
+ it('parses callback props', () => {
67
+ const filePath = writeComponent('Callback.tsx', `
68
+ export interface CbViewModel {
69
+ onTap: () => void;
70
+ onChange: (val: boolean) => void;
71
+ onSelect: (item: string) => void;
72
+ }
73
+ export class CbComponent extends Component<CbViewModel, {}> {
74
+ onRender(): void {}
75
+ }
76
+ `);
77
+ const result = (0, viewModelParser_1.parseComponentFile)(filePath);
78
+ expect(result.props.length).toBe(3);
79
+ expect(result.props[0].isCallback).toBe(true);
80
+ expect(result.props[0].callbackParamType).toBeUndefined();
81
+ expect(result.props[1].isCallback).toBe(true);
82
+ expect(result.props[1].callbackParamType).toBe('boolean');
83
+ expect(result.props[2].isCallback).toBe(true);
84
+ expect(result.props[2].callbackParamType).toBe('string');
85
+ });
86
+ it('parses StatefulComponent', () => {
87
+ const filePath = writeComponent('Stateful.tsx', `
88
+ export interface StatefulVM {
89
+ checked: boolean;
90
+ }
91
+ export class MyStateful extends StatefulComponent<StatefulVM> {
92
+ onRender(): void {}
93
+ }
94
+ `);
95
+ const result = (0, viewModelParser_1.parseComponentFile)(filePath);
96
+ expect(result.componentName).toBe('MyStateful');
97
+ expect(result.viewModelName).toBe('StatefulVM');
98
+ });
99
+ it('throws when no Component class is found', () => {
100
+ const filePath = writeComponent('NoClass.tsx', `
101
+ export interface SomeViewModel { title: string; }
102
+ `);
103
+ expect(() => (0, viewModelParser_1.parseComponentFile)(filePath)).toThrowError(/Could not find an exported Component class/);
104
+ });
105
+ it('throws when ViewModel interface is missing', () => {
106
+ const filePath = writeComponent('NoVM.tsx', `
107
+ export class Broken extends Component<MissingViewModel, {}> {
108
+ onRender(): void {}
109
+ }
110
+ `);
111
+ expect(() => (0, viewModelParser_1.parseComponentFile)(filePath)).toThrowError(/Could not find interface MissingViewModel/);
112
+ });
113
+ });
114
+ describe('detectInteractiveState', () => {
115
+ it('pairs boolean prop with onChange callback', () => {
116
+ const props = [
117
+ { name: 'on', typeString: 'boolean', optional: false, isBoolean: true, isCallback: false, callbackParamType: undefined },
118
+ { name: 'onChange', typeString: '(val: boolean) => void', optional: false, isBoolean: false, isCallback: true, callbackParamType: 'boolean' },
119
+ ];
120
+ const pairs = (0, viewModelParser_1.detectInteractiveState)(props);
121
+ expect(pairs.length).toBe(1);
122
+ expect(pairs[0].boolPropName).toBe('on');
123
+ expect(pairs[0].callbackPropName).toBe('onChange');
124
+ });
125
+ it('pairs boolean prop with onTap callback', () => {
126
+ const props = [
127
+ { name: 'selected', typeString: 'boolean', optional: false, isBoolean: true, isCallback: false, callbackParamType: undefined },
128
+ { name: 'onTap', typeString: '(val: boolean) => void', optional: false, isBoolean: false, isCallback: true, callbackParamType: 'boolean' },
129
+ ];
130
+ const pairs = (0, viewModelParser_1.detectInteractiveState)(props);
131
+ expect(pairs.length).toBe(1);
132
+ expect(pairs[0].boolPropName).toBe('selected');
133
+ expect(pairs[0].callbackPropName).toBe('onTap');
134
+ });
135
+ it('returns empty when no matching pair exists', () => {
136
+ const props = [
137
+ { name: 'title', typeString: 'string', optional: false, isBoolean: false, isCallback: false, callbackParamType: undefined },
138
+ { name: 'onTap', typeString: '() => void', optional: false, isBoolean: false, isCallback: true, callbackParamType: undefined },
139
+ ];
140
+ const pairs = (0, viewModelParser_1.detectInteractiveState)(props);
141
+ expect(pairs.length).toBe(0);
142
+ });
143
+ it('skips optional boolean props', () => {
144
+ const props = [
145
+ { name: 'checked', typeString: 'boolean', optional: true, isBoolean: true, isCallback: false, callbackParamType: undefined },
146
+ { name: 'onToggle', typeString: '(val: boolean) => void', optional: false, isBoolean: false, isCallback: true, callbackParamType: 'boolean' },
147
+ ];
148
+ const pairs = (0, viewModelParser_1.detectInteractiveState)(props);
149
+ expect(pairs.length).toBe(0);
150
+ });
151
+ });
152
+ describe('sampleValueForType', () => {
153
+ it('returns correct sample for primitive types', () => {
154
+ expect((0, viewModelParser_1.sampleValueForType)('boolean')).toBe('false');
155
+ expect((0, viewModelParser_1.sampleValueForType)('string')).toBe("'Sample'");
156
+ expect((0, viewModelParser_1.sampleValueForType)('number')).toBe('42');
157
+ expect((0, viewModelParser_1.sampleValueForType)('Date')).toBe('new Date()');
158
+ });
159
+ it('returns noop for function types', () => {
160
+ expect((0, viewModelParser_1.sampleValueForType)('() => void')).toBe('() => {}');
161
+ expect((0, viewModelParser_1.sampleValueForType)('(val: boolean) => void')).toBe('() => {}');
162
+ });
163
+ it('returns empty array for array types', () => {
164
+ expect((0, viewModelParser_1.sampleValueForType)('string[]')).toBe('[]');
165
+ expect((0, viewModelParser_1.sampleValueForType)('Array<number>')).toBe('[]');
166
+ });
167
+ it('falls back to undefined for unknown types', () => {
168
+ expect((0, viewModelParser_1.sampleValueForType)('SomeCustomType')).toBe('undefined as any');
169
+ });
170
+ });
171
+ });
@@ -8,20 +8,7 @@ const constants_1 = require("../core/constants");
8
8
  const LoadingIndicator_1 = require("../utils/LoadingIndicator");
9
9
  const cliUtils_1 = require("../utils/cliUtils");
10
10
  const logUtils_1 = require("../utils/logUtils");
11
- const tempDir_1 = require("../utils/tempDir");
12
- const zipUtils_1 = require("../utils/zipUtils");
13
- const versions_1 = require("./versions");
14
11
  exports.HOME_DIR = process.env['HOME'] ?? '';
15
- function getAndroidHomeDir() {
16
- const platform = process.platform;
17
- if (platform === 'darwin') {
18
- return path_1.default.join(exports.HOME_DIR, 'Library', 'Android', 'sdk');
19
- }
20
- else {
21
- return path_1.default.join(exports.HOME_DIR, 'Android', 'Sdk');
22
- }
23
- }
24
- const ANDROID_HOME_TARGET_DIR = getAndroidHomeDir();
25
12
  class DevSetupHelper {
26
13
  async download(url) {
27
14
  return new LoadingIndicator_1.LoadingIndicator(async () => {
@@ -160,44 +147,6 @@ class DevSetupHelper {
160
147
  .setText((0, logUtils_1.wrapInColor)('Setting up shell autocomplete...', constants_1.ANSI_COLORS.YELLOW_COLOR))
161
148
  .show();
162
149
  }
163
- async setupAndroidSDK(commandLineToolsURL, javaHomeOverride) {
164
- console.log((0, logUtils_1.wrapInColor)('Setting up Android SDK...', constants_1.ANSI_COLORS.YELLOW_COLOR));
165
- if (!process.env['ANDROID_HOME']) {
166
- await (0, tempDir_1.withTempDir)(async (tempDir) => {
167
- const filename = path_1.default.join(tempDir, path_1.default.basename(commandLineToolsURL));
168
- await this.downloadToPath(commandLineToolsURL, filename);
169
- const targetDir = path_1.default.join(ANDROID_HOME_TARGET_DIR, 'cmdline-tools');
170
- await (0, zipUtils_1.decompressTo)(filename, targetDir);
171
- const target = path_1.default.join(targetDir, 'latest');
172
- if (fs_1.default.existsSync(target)) {
173
- await fs_1.default.promises.rm(target, { recursive: true, force: true });
174
- }
175
- fs_1.default.renameSync(path_1.default.join(targetDir, 'cmdline-tools'), target);
176
- });
177
- process.env['ANDROID_HOME'] = ANDROID_HOME_TARGET_DIR;
178
- const androidHomeValue = process.platform === 'darwin'
179
- ? '"$HOME/Library/Android/sdk"'
180
- : '"$HOME/Android/Sdk"';
181
- await this.writeEnvVariablesToRcFile([{ name: 'ANDROID_HOME', value: androidHomeValue }]);
182
- }
183
- const androidHome = process.env['ANDROID_HOME'] ?? '';
184
- const sdkManagerBin = path_1.default.join(androidHome, 'cmdline-tools/latest/bin/sdkmanager');
185
- const sdkManagerEnvVariables = {};
186
- if (javaHomeOverride) {
187
- sdkManagerEnvVariables['JAVA_HOME'] = javaHomeOverride;
188
- }
189
- await this.runShell('Installing Android platform', [`${sdkManagerBin} --install 'platforms;${versions_1.ANDROID_PLATFORM_VERSION}'`], sdkManagerEnvVariables);
190
- await this.runShell('Installing Android NDK', [`${sdkManagerBin} --install 'ndk;${versions_1.ANDROID_NDK_VERSION}'`], sdkManagerEnvVariables);
191
- await this.runShell('Installing Android build-tools', [`${sdkManagerBin} --install 'build-tools;${versions_1.ANDROID_BUILD_TOOLS_VERSION}'`], sdkManagerEnvVariables);
192
- const ndkBundle = path_1.default.join(androidHome, 'ndk-bundle');
193
- if (!fs_1.default.existsSync(ndkBundle)) {
194
- fs_1.default.symlinkSync(`ndk/${versions_1.ANDROID_NDK_VERSION}`, ndkBundle);
195
- }
196
- await this.writeEnvVariablesToRcFile([
197
- { name: 'ANDROID_NDK_HOME', value: `"$ANDROID_HOME/ndk-bundle"` },
198
- { name: 'PATH', value: `"$ANDROID_HOME/platform-tools:$PATH"` },
199
- ]);
200
- }
201
150
  getRcFile() {
202
151
  const homeDir = process.env['HOME'] ?? '';
203
152
  const shell = process.env['SHELL'] ?? '';
@@ -11,7 +11,6 @@ const cliUtils_1 = require("../utils/cliUtils");
11
11
  const linuxDistro_1 = require("../utils/linuxDistro");
12
12
  const logUtils_1 = require("../utils/logUtils");
13
13
  const DevSetupHelper_1 = require("./DevSetupHelper");
14
- const versions_1 = require("./versions");
15
14
  const BAZELISK_URL = 'https://github.com/bazelbuild/bazelisk/releases/download/v1.26.0/bazelisk-linux-amd64';
16
15
  function getDebianArchitecture() {
17
16
  const nodeArch = os_1.default.arch();
@@ -164,6 +163,5 @@ async function linuxSetup() {
164
163
  fs_1.default.chmodSync(bazeliskTargetPath, stats.mode | 0o111);
165
164
  }
166
165
  await devSetup.writeEnvVariablesToRcFile([{ name: 'PATH', value: `"$HOME/.valdi/bin:$PATH"` }]);
167
- await devSetup.setupAndroidSDK(versions_1.ANDROID_LINUX_COMMANDLINE_TOOLS);
168
166
  devSetup.onComplete();
169
167
  }
@@ -6,7 +6,6 @@ const fs_1 = tslib_1.__importDefault(require("fs"));
6
6
  const errors_1 = require("../core/errors");
7
7
  const cliUtils_1 = require("../utils/cliUtils");
8
8
  const DevSetupHelper_1 = require("./DevSetupHelper");
9
- const versions_1 = require("./versions");
10
9
  async function macOSSetup() {
11
10
  const devSetup = new DevSetupHelper_1.DevSetupHelper();
12
11
  if (!(0, cliUtils_1.checkCommandExists)('xcode-select')) {
@@ -69,7 +68,7 @@ async function macOSSetup() {
69
68
  console.log('Note: Could not automatically configure Homebrew PATH in .zprofile');
70
69
  }
71
70
  }
72
- const packages = ['npm', 'bazelisk', 'openjdk@17', 'temurin', 'git-lfs', 'watchman', 'ios-webkit-debug-proxy'];
71
+ const packages = ['npm', 'bazelisk', 'openjdk@17', 'temurin', 'git-lfs', 'watchman', 'ios-webkit-debug-proxy', 'android-platform-tools'];
73
72
  const packagesToInstall = [];
74
73
  for (const pkg of packages) {
75
74
  try {
@@ -117,7 +116,5 @@ async function macOSSetup() {
117
116
  { name: 'PATH', value: '"/opt/homebrew/opt/openjdk@17/bin:$PATH"' },
118
117
  { name: 'JAVA_HOME', value: '`/usr/libexec/java_home -v 17`' },
119
118
  ]);
120
- const javaHome = await (0, cliUtils_1.runCliCommand)('/usr/libexec/java_home');
121
- await devSetup.setupAndroidSDK(versions_1.ANDROID_MACOS_COMMANDLINE_TOOLS, javaHome.stdout.trim());
122
119
  devSetup.onComplete();
123
120
  }
@@ -67,6 +67,12 @@ class BazelLabel {
67
67
  return new BazelLabel(repo, str, undefined);
68
68
  }
69
69
  }
70
+ get apparentRepo() {
71
+ if (!this.repo)
72
+ return undefined;
73
+ const tildeIndex = this.repo.indexOf('~');
74
+ return tildeIndex >= 0 ? this.repo.slice(0, tildeIndex) : this.repo;
75
+ }
70
76
  toString() {
71
77
  const repoPrefix = this.repo ? `@${this.repo}` : '';
72
78
  if (this.name) {
@@ -76,6 +82,15 @@ class BazelLabel {
76
82
  return repoPrefix + this.target;
77
83
  }
78
84
  }
85
+ toBuildableString() {
86
+ const repoPrefix = this.apparentRepo ? `@${this.apparentRepo}` : '';
87
+ if (this.name) {
88
+ return `${repoPrefix}${this.target}:${this.name}`;
89
+ }
90
+ else {
91
+ return repoPrefix + this.target;
92
+ }
93
+ }
79
94
  }
80
95
  exports.BazelLabel = BazelLabel;
81
96
  class BazelCommandCache {
@@ -0,0 +1,344 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DaemonConnection = exports.DaemonMsgType = exports.DEFAULT_PORT = exports.MOBILE_PORT = exports.STANDALONE_PORT = void 0;
4
+ exports.loadInspectConfig = loadInspectConfig;
5
+ exports.saveInspectConfig = saveInspectConfig;
6
+ exports.connectToDaemon = connectToDaemon;
7
+ exports.resolveContextId = resolveContextId;
8
+ exports.resolveClientId = resolveClientId;
9
+ const tslib_1 = require("tslib");
10
+ const net = tslib_1.__importStar(require("net"));
11
+ const os = tslib_1.__importStar(require("os"));
12
+ const path = tslib_1.__importStar(require("path"));
13
+ const fs = tslib_1.__importStar(require("fs"));
14
+ const errors_1 = require("../core/errors");
15
+ const cliUtils_1 = require("./cliUtils");
16
+ exports.STANDALONE_PORT = 13591;
17
+ exports.MOBILE_PORT = 13592;
18
+ exports.DEFAULT_PORT = exports.MOBILE_PORT;
19
+ var DaemonMsgType;
20
+ (function (DaemonMsgType) {
21
+ DaemonMsgType[DaemonMsgType["LIST_CONTEXTS_REQUEST"] = 2] = "LIST_CONTEXTS_REQUEST";
22
+ DaemonMsgType[DaemonMsgType["LIST_CONTEXTS_RESPONSE"] = -2] = "LIST_CONTEXTS_RESPONSE";
23
+ DaemonMsgType[DaemonMsgType["GET_CONTEXT_TREE_REQUEST"] = 3] = "GET_CONTEXT_TREE_REQUEST";
24
+ DaemonMsgType[DaemonMsgType["GET_CONTEXT_TREE_RESPONSE"] = -3] = "GET_CONTEXT_TREE_RESPONSE";
25
+ DaemonMsgType[DaemonMsgType["TAKE_ELEMENT_SNAPSHOT_REQUEST"] = 4] = "TAKE_ELEMENT_SNAPSHOT_REQUEST";
26
+ DaemonMsgType[DaemonMsgType["TAKE_ELEMENT_SNAPSHOT_RESPONSE"] = -4] = "TAKE_ELEMENT_SNAPSHOT_RESPONSE";
27
+ DaemonMsgType[DaemonMsgType["DUMP_HEAP_REQUEST"] = 5] = "DUMP_HEAP_REQUEST";
28
+ DaemonMsgType[DaemonMsgType["DUMP_HEAP_RESPONSE"] = -5] = "DUMP_HEAP_RESPONSE";
29
+ })(DaemonMsgType || (exports.DaemonMsgType = DaemonMsgType = {}));
30
+ const CONFIG_PATH = path.join(os.homedir(), '.valdi-inspect.json');
31
+ function loadInspectConfig() {
32
+ try {
33
+ return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
34
+ }
35
+ catch {
36
+ return {};
37
+ }
38
+ }
39
+ function saveInspectConfig(config) {
40
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
41
+ }
42
+ const MAGIC = Buffer.from([0x33, 0xc6, 0x00, 0x01]);
43
+ const HEADER_SIZE = 8;
44
+ function encodePacket(json) {
45
+ const payload = Buffer.from(JSON.stringify(json), 'utf8');
46
+ const header = Buffer.alloc(8);
47
+ MAGIC.copy(header, 0);
48
+ header.writeUInt32LE(payload.length, 4);
49
+ return Buffer.concat([header, payload]);
50
+ }
51
+ const DIRECT_CLIENT_ID = 1;
52
+ class DaemonConnection {
53
+ socket;
54
+ recvBuf = Buffer.alloc(0);
55
+ recvChunks = [];
56
+ recvLen = 0;
57
+ reqCounter = 0;
58
+ msgCounter = 0;
59
+ pendingRequests = new Map();
60
+ payloadListeners = new Map();
61
+ configureReady = null;
62
+ configureData = null;
63
+ constructor(socket) {
64
+ this.socket = socket;
65
+ socket.on('data', (data) => this.onData(data));
66
+ socket.on('close', () => this.rejectAllPending(new Error('Connection closed unexpectedly')));
67
+ socket.on('error', (err) => this.rejectAllPending(err));
68
+ }
69
+ rejectAllPending(err) {
70
+ this.configureReady?.reject(err);
71
+ this.configureReady = null;
72
+ for (const pending of this.pendingRequests.values())
73
+ pending.reject(err);
74
+ for (const listener of this.payloadListeners.values())
75
+ listener.reject(err);
76
+ this.pendingRequests.clear();
77
+ this.payloadListeners.clear();
78
+ }
79
+ onData(chunk) {
80
+ this.recvChunks.push(chunk);
81
+ this.recvLen += chunk.length;
82
+ this.drainBuffer();
83
+ }
84
+ drainBuffer() {
85
+ for (;;) {
86
+ if (this.recvLen < HEADER_SIZE)
87
+ break;
88
+ if (this.recvBuf.length < this.recvLen) {
89
+ this.recvBuf = Buffer.concat(this.recvChunks, this.recvLen);
90
+ this.recvChunks = [this.recvBuf];
91
+ }
92
+ if (this.recvBuf[0] !== 0x33 ||
93
+ this.recvBuf[1] !== 0xc6 ||
94
+ this.recvBuf[2] !== 0x00 ||
95
+ this.recvBuf[3] !== 0x01) {
96
+ this.socket.destroy(new Error('ValdiPacket: bad magic'));
97
+ break;
98
+ }
99
+ const payloadLen = this.recvBuf.readUInt32LE(4);
100
+ if (this.recvLen < HEADER_SIZE + payloadLen)
101
+ break;
102
+ const raw = this.recvBuf.subarray(HEADER_SIZE, HEADER_SIZE + payloadLen).toString('utf8');
103
+ const consumed = HEADER_SIZE + payloadLen;
104
+ this.recvBuf = this.recvBuf.subarray(consumed);
105
+ this.recvLen -= consumed;
106
+ this.recvChunks = this.recvLen > 0 ? [this.recvBuf] : [];
107
+ try {
108
+ this.dispatchMessage(JSON.parse(raw));
109
+ }
110
+ catch {
111
+ }
112
+ }
113
+ }
114
+ dispatchMessage(msg) {
115
+ if (msg['request']) {
116
+ const req = msg['request'];
117
+ const reqId = req['request_id'];
118
+ const respKey = Object.keys(req).find((k) => k !== 'request_id');
119
+ if (respKey) {
120
+ this.socket.write(encodePacket({ response: { [respKey]: {}, request_id: reqId } }));
121
+ if (respKey === 'configure') {
122
+ this.configureData = req['configure'];
123
+ if (this.configureReady) {
124
+ const waiter = this.configureReady;
125
+ this.configureReady = null;
126
+ waiter.resolve(req);
127
+ }
128
+ }
129
+ else if (respKey === 'forward_client_payload') {
130
+ const fcp = req['forward_client_payload'];
131
+ if (fcp) {
132
+ try {
133
+ const inner = JSON.parse(fcp['payload_string']);
134
+ const msgId = String(inner['requestId']);
135
+ const listener = this.payloadListeners.get(msgId);
136
+ if (listener) {
137
+ this.payloadListeners.delete(msgId);
138
+ listener.resolve(inner);
139
+ }
140
+ }
141
+ catch {
142
+ }
143
+ }
144
+ }
145
+ }
146
+ }
147
+ else if (msg['response']) {
148
+ const resp = msg['response'];
149
+ const reqId = resp['request_id'];
150
+ const pending = this.pendingRequests.get(reqId);
151
+ if (pending) {
152
+ this.pendingRequests.delete(reqId);
153
+ if (resp['error']) {
154
+ const errMsg = resp['error']['error_message'];
155
+ pending.reject(new Error(errMsg));
156
+ }
157
+ else {
158
+ pending.resolve(resp);
159
+ }
160
+ }
161
+ }
162
+ }
163
+ sendRequest(payload, timeoutMs = 5_000) {
164
+ const reqId = String(++this.reqCounter);
165
+ const envelope = { request: { ...payload, request_id: reqId } };
166
+ return new Promise((resolve, reject) => {
167
+ const timer = setTimeout(() => {
168
+ this.pendingRequests.delete(reqId);
169
+ reject(new errors_1.CliError(`Valdi daemon did not respond (port ${(this.socket.remotePort ?? '?')}).\n` +
170
+ `Is the hot-reloader actually running and connected?`));
171
+ }, timeoutMs);
172
+ this.pendingRequests.set(reqId, {
173
+ resolve: (v) => { clearTimeout(timer); resolve(v); },
174
+ reject: (e) => { clearTimeout(timer); reject(e); },
175
+ });
176
+ this.socket.write(encodePacket(envelope), (err) => {
177
+ if (err) {
178
+ clearTimeout(timer);
179
+ this.pendingRequests.delete(reqId);
180
+ reject(err);
181
+ }
182
+ });
183
+ });
184
+ }
185
+ nextMsgId() {
186
+ return String(++this.msgCounter);
187
+ }
188
+ configure() {
189
+ if (this.configureData)
190
+ return Promise.resolve();
191
+ return new Promise((resolve, reject) => {
192
+ const timer = setTimeout(() => {
193
+ this.configureReady = null;
194
+ reject(new errors_1.CliError(`Valdi daemon did not respond (port ${this.socket.remotePort ?? '?'}).\n` +
195
+ `Is the hot-reloader actually running and connected?`));
196
+ }, 5_000);
197
+ this.configureReady = {
198
+ resolve: () => { clearTimeout(timer); resolve(); },
199
+ reject: (e) => { clearTimeout(timer); reject(e); },
200
+ };
201
+ });
202
+ }
203
+ listConnectedClients() {
204
+ if (this.configureData) {
205
+ const client = {
206
+ client_id: String(DIRECT_CLIENT_ID),
207
+ platform: String(this.configureData['platform'] ?? 'unknown'),
208
+ application_id: String(this.configureData['application_id'] ?? 'unknown'),
209
+ };
210
+ return Promise.resolve([client]);
211
+ }
212
+ return Promise.resolve([]);
213
+ }
214
+ async forwardAndWait(_clientId, msgType, body, timeoutMs = 15_000) {
215
+ const msgId = this.nextMsgId();
216
+ const payloadString = JSON.stringify({ type: msgType, requestId: msgId, body });
217
+ const resultPromise = new Promise((resolve, reject) => {
218
+ const timer = setTimeout(() => {
219
+ this.payloadListeners.delete(msgId);
220
+ reject(new Error('Timeout waiting for device response. Is the app running?'));
221
+ }, timeoutMs);
222
+ this.payloadListeners.set(msgId, {
223
+ resolve: (v) => { clearTimeout(timer); resolve(v); },
224
+ reject: (e) => { clearTimeout(timer); reject(e); },
225
+ });
226
+ });
227
+ this.socket.write(encodePacket({
228
+ event: {
229
+ payload_from_client: {
230
+ sender_client_id: DIRECT_CLIENT_ID,
231
+ payload_string: payloadString,
232
+ },
233
+ },
234
+ }), (err) => {
235
+ if (err) {
236
+ const listener = this.payloadListeners.get(msgId);
237
+ if (listener) {
238
+ this.payloadListeners.delete(msgId);
239
+ listener.reject(err);
240
+ }
241
+ }
242
+ });
243
+ return resultPromise;
244
+ }
245
+ async listContexts(clientId) {
246
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.LIST_CONTEXTS_REQUEST, {});
247
+ return (resp['body'] ?? []);
248
+ }
249
+ async getContextTree(clientId, contextId) {
250
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.GET_CONTEXT_TREE_REQUEST, { id: contextId });
251
+ return resp['body'];
252
+ }
253
+ async takeSnapshot(clientId, elementId, contextId) {
254
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.TAKE_ELEMENT_SNAPSHOT_REQUEST, {
255
+ elementId: parseInt(elementId, 10),
256
+ contextId,
257
+ });
258
+ return resp['body'];
259
+ }
260
+ async dumpHeap(clientId, performGC = false) {
261
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.DUMP_HEAP_REQUEST, { performGC }, 60_000);
262
+ return resp['body'];
263
+ }
264
+ close() {
265
+ this.socket.destroy();
266
+ }
267
+ }
268
+ exports.DaemonConnection = DaemonConnection;
269
+ async function tryAdbForward(port) {
270
+ try {
271
+ await (0, cliUtils_1.runCliCommand)(`adb forward tcp:${port} tcp:${port}`);
272
+ }
273
+ catch {
274
+ }
275
+ }
276
+ async function connectToDaemon(port = exports.DEFAULT_PORT) {
277
+ if (port !== exports.STANDALONE_PORT) {
278
+ await tryAdbForward(port);
279
+ }
280
+ return new Promise((resolve, reject) => {
281
+ const socket = net.createConnection({ port, host: '127.0.0.1' });
282
+ const timer = setTimeout(() => {
283
+ socket.destroy();
284
+ reject(new Error(`Timeout connecting to Valdi daemon on port ${port}. Is the hot-reloader running?`));
285
+ }, 5_000);
286
+ socket.once('connect', () => {
287
+ clearTimeout(timer);
288
+ resolve(new DaemonConnection(socket));
289
+ });
290
+ socket.once('error', (err) => {
291
+ clearTimeout(timer);
292
+ if (err.code === 'ECONNREFUSED') {
293
+ reject(new errors_1.CliError(`Valdi daemon not running on port ${port}.\n` +
294
+ `Start the hot-reloader (valdi hotreload) or pass --port to use a different port.`));
295
+ }
296
+ else {
297
+ reject(err);
298
+ }
299
+ });
300
+ });
301
+ }
302
+ async function resolveContextId(conn, clientId, contextIdOverride) {
303
+ const contexts = await conn.listContexts(clientId);
304
+ if (contexts.length === 0) {
305
+ throw new errors_1.CliError('No contexts found on the connected device.');
306
+ }
307
+ if (contextIdOverride) {
308
+ if (!contexts.some((c) => c.id === contextIdOverride)) {
309
+ throw new errors_1.CliError(`Context "${contextIdOverride}" not found. Run "valdi inspect contexts" to see available contexts.`);
310
+ }
311
+ return contextIdOverride;
312
+ }
313
+ if (contexts.length === 1) {
314
+ return contexts[0].id;
315
+ }
316
+ return (0, cliUtils_1.getUserChoice)(contexts.map((c) => ({
317
+ name: `${c.rootComponentName} [${c.id}]`,
318
+ value: c.id,
319
+ })), 'Multiple contexts found. Select one:');
320
+ }
321
+ async function resolveClientId(conn, clientIdOverride) {
322
+ const clients = await conn.listConnectedClients();
323
+ if (clients.length === 0) {
324
+ throw new errors_1.CliError('No devices connected to the Valdi daemon.\n' +
325
+ 'Make sure the Valdi app is running and connected to the hot-reloader.');
326
+ }
327
+ if (clientIdOverride) {
328
+ if (!clients.some((c) => c.client_id === clientIdOverride)) {
329
+ throw new errors_1.CliError(`Client "${clientIdOverride}" not found. Run "valdi inspect devices" to see connected clients.`);
330
+ }
331
+ return clientIdOverride;
332
+ }
333
+ const config = loadInspectConfig();
334
+ if (config.selectedClientId && clients.some((c) => c.client_id === config.selectedClientId)) {
335
+ return config.selectedClientId;
336
+ }
337
+ if (clients.length === 1) {
338
+ return clients[0].client_id;
339
+ }
340
+ return (0, cliUtils_1.getUserChoice)(clients.map((c) => ({
341
+ name: `${c.application_id} (${c.platform}) [${c.client_id}]`,
342
+ value: c.client_id,
343
+ })), 'Multiple devices connected. Select one:');
344
+ }