@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,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.computeSimilarity = computeSimilarity;
4
+ exports.jaccardSimilarity = jaccardSimilarity;
5
+ exports.lcsRatio = lcsRatio;
6
+ const VM_WEIGHT = 0.4;
7
+ const RENDER_WEIGHT = 0.35;
8
+ const IMPORT_WEIGHT = 0.25;
9
+ function computeSimilarity(a, b) {
10
+ const vmSim = jaccardSimilarity(a.viewModelProps, b.viewModelProps);
11
+ const renderSim = lcsRatio(a.renderElements, b.renderElements);
12
+ const importSim = jaccardSimilarity(a.importPaths, b.importPaths);
13
+ return VM_WEIGHT * vmSim + RENDER_WEIGHT * renderSim + IMPORT_WEIGHT * importSim;
14
+ }
15
+ function jaccardSimilarity(a, b) {
16
+ if (a.length === 0 && b.length === 0)
17
+ return 1;
18
+ if (a.length === 0 || b.length === 0)
19
+ return 0;
20
+ const setA = new Set(a);
21
+ const setB = new Set(b);
22
+ let intersection = 0;
23
+ for (const item of setA) {
24
+ if (setB.has(item))
25
+ intersection++;
26
+ }
27
+ const union = setA.size + setB.size - intersection;
28
+ return union === 0 ? 0 : intersection / union;
29
+ }
30
+ function lcsRatio(a, b) {
31
+ if (a.length === 0 && b.length === 0)
32
+ return 1;
33
+ if (a.length === 0 || b.length === 0)
34
+ return 0;
35
+ const lcsLen = lcsLength(a, b);
36
+ return (2 * lcsLen) / (a.length + b.length);
37
+ }
38
+ function lcsLength(a, b) {
39
+ const m = a.length;
40
+ const n = b.length;
41
+ let prev = new Array(n + 1).fill(0);
42
+ let curr = new Array(n + 1).fill(0);
43
+ for (let i = 1; i <= m; i++) {
44
+ for (let j = 1; j <= n; j++) {
45
+ if (a[i - 1] === b[j - 1]) {
46
+ curr[j] = prev[j - 1] + 1;
47
+ }
48
+ else {
49
+ curr[j] = Math.max(prev[j], curr[j - 1]);
50
+ }
51
+ }
52
+ [prev, curr] = [curr, prev];
53
+ curr.fill(0);
54
+ }
55
+ return prev[n];
56
+ }
@@ -31,7 +31,7 @@ var Architecture;
31
31
  exports.ALL_ARCHITECTURES = [Architecture.ARMV7, Architecture.ARM64, Architecture.X86_64];
32
32
  var TEMPLATE_BASE_PATHS;
33
33
  (function (TEMPLATE_BASE_PATHS) {
34
- TEMPLATE_BASE_PATHS["WORKSPACE"] = "WORKSPACE.template";
34
+ TEMPLATE_BASE_PATHS["MODULE_BAZEL"] = "MODULE.bazel.template";
35
35
  TEMPLATE_BASE_PATHS["BAZEL_RC"] = ".bazelrc.template";
36
36
  TEMPLATE_BASE_PATHS["BAZEL_VERSION"] = ".bazelversion.template";
37
37
  TEMPLATE_BASE_PATHS["USER_CONFIG"] = "config.yaml.template";
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ require("jasmine");
5
+ const child_process_1 = require("child_process");
6
+ const path_1 = tslib_1.__importDefault(require("path"));
7
+ describe('npm package contents', () => {
8
+ let packedFiles;
9
+ beforeAll(() => {
10
+ const cliRoot = path_1.default.join(__dirname, '../..');
11
+ packedFiles = (0, child_process_1.execSync)('npm pack --dry-run 2>&1', {
12
+ cwd: cliRoot,
13
+ encoding: 'utf-8',
14
+ });
15
+ });
16
+ it('includes .metadata templates for bootstrap config', () => {
17
+ expect(packedFiles).toContain('.metadata/config.yaml.template');
18
+ expect(packedFiles).toContain('.metadata/MODULE.bazel.template');
19
+ });
20
+ it('includes .bootstrap templates for project scaffolding', () => {
21
+ expect(packedFiles).toContain('.bootstrap/');
22
+ });
23
+ it('includes dist output', () => {
24
+ expect(packedFiles).toContain('dist/');
25
+ });
26
+ it('includes bundled-skills', () => {
27
+ expect(packedFiles).toContain('bundled-skills/');
28
+ });
29
+ });
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPreviewDir = getPreviewDir;
4
+ exports.generatePreviewFiles = generatePreviewFiles;
5
+ exports.findModuleDir = findModuleDir;
6
+ exports.getModuleNameFromImport = getModuleNameFromImport;
7
+ exports.readModuleName = readModuleName;
8
+ exports.isValdiWorkspace = isValdiWorkspace;
9
+ exports.computeModuleLabel = computeModuleLabel;
10
+ const tslib_1 = require("tslib");
11
+ const fs_1 = tslib_1.__importDefault(require("fs"));
12
+ const path_1 = tslib_1.__importDefault(require("path"));
13
+ const viewModelParser_1 = require("./viewModelParser");
14
+ const PREVIEW_DIR = 'apps/preview';
15
+ function getPreviewDir(workspaceRoot) {
16
+ return path_1.default.join(workspaceRoot, PREVIEW_DIR);
17
+ }
18
+ function generatePreviewFiles(config) {
19
+ const previewDir = getPreviewDir(config.workspaceRoot);
20
+ fs_1.default.mkdirSync(previewDir, { recursive: true });
21
+ fs_1.default.writeFileSync(path_1.default.join(previewDir, 'PreviewRoot.tsx'), generatePreviewTsx(config));
22
+ fs_1.default.writeFileSync(path_1.default.join(previewDir, 'BUILD.bazel'), generateBuildBazel(config));
23
+ fs_1.default.writeFileSync(path_1.default.join(previewDir, 'tsconfig.json'), generateTsconfig(config));
24
+ }
25
+ function generatePreviewTsx(config) {
26
+ const { viewModel, importPath } = config;
27
+ const { componentName, props } = viewModel;
28
+ const interactiveState = (0, viewModelParser_1.detectInteractiveState)(props);
29
+ const hasState = interactiveState.length > 0;
30
+ const lines = [];
31
+ if (hasState) {
32
+ lines.push("import { StatefulComponent } from 'valdi_core/src/Component';");
33
+ }
34
+ else {
35
+ lines.push("import { Component } from 'valdi_core/src/Component';");
36
+ }
37
+ lines.push("import { Style } from 'valdi_core/src/Style';");
38
+ lines.push("import { View } from 'valdi_tsx/src/NativeTemplateElements';");
39
+ lines.push(`import { ${componentName} } from '${importPath}';`);
40
+ lines.push('');
41
+ lines.push('/**');
42
+ lines.push(' * @ViewModel');
43
+ lines.push(' * @ExportModel');
44
+ lines.push(' */');
45
+ lines.push('export interface ViewModel {}');
46
+ lines.push('');
47
+ lines.push('/**');
48
+ lines.push(' * @Context');
49
+ lines.push(' * @ExportModel');
50
+ lines.push(' */');
51
+ lines.push('export interface ComponentContext {}');
52
+ lines.push('');
53
+ if (hasState) {
54
+ lines.push('interface PreviewState {');
55
+ for (const s of interactiveState) {
56
+ lines.push(` ${s.stateName}: boolean;`);
57
+ }
58
+ lines.push('}');
59
+ lines.push('');
60
+ }
61
+ lines.push('/**');
62
+ lines.push(' * @Component');
63
+ lines.push(' * @ExportModel');
64
+ lines.push(' */');
65
+ if (hasState) {
66
+ lines.push('export class PreviewRoot extends StatefulComponent<ViewModel, PreviewState, ComponentContext> {');
67
+ lines.push(' state: PreviewState = {');
68
+ for (const s of interactiveState) {
69
+ lines.push(` ${s.stateName}: false,`);
70
+ }
71
+ lines.push(' };');
72
+ lines.push('');
73
+ for (const s of interactiveState) {
74
+ lines.push(` private ${s.callbackPropName}Handler = (val: boolean) => this.setState({ ${s.stateName}: val });`);
75
+ }
76
+ }
77
+ else {
78
+ lines.push('export class PreviewRoot extends Component<ViewModel, ComponentContext> {');
79
+ }
80
+ lines.push('');
81
+ lines.push(' onRender(): void {');
82
+ lines.push(' <view style={styles.container}>');
83
+ lines.push(` <label value="${componentName}" font="system-bold 20" color="#000000" marginBottom={24} />`);
84
+ lines.push(` ${generateComponentJsx(componentName, props, interactiveState)}`);
85
+ lines.push(' </view>;');
86
+ lines.push(' }');
87
+ lines.push('}');
88
+ lines.push('');
89
+ lines.push('const styles = {');
90
+ lines.push(' container: new Style<View>({');
91
+ lines.push(" backgroundColor: '#ffffff',");
92
+ lines.push(" width: '100%',");
93
+ lines.push(" height: '100%',");
94
+ lines.push(" alignItems: 'center',");
95
+ lines.push(" justifyContent: 'center',");
96
+ lines.push(' padding: 24,');
97
+ lines.push(' }),');
98
+ lines.push('};');
99
+ lines.push('');
100
+ return lines.join('\n');
101
+ }
102
+ function generateComponentJsx(componentName, props, interactiveState) {
103
+ const stateMap = new Map();
104
+ for (const s of interactiveState) {
105
+ stateMap.set(s.boolPropName, s);
106
+ stateMap.set(s.callbackPropName, s);
107
+ }
108
+ const requiredProps = props.filter(p => !p.optional);
109
+ if (requiredProps.length === 0) {
110
+ return `<${componentName} />`;
111
+ }
112
+ const propAssignments = [];
113
+ for (const prop of requiredProps) {
114
+ const state = stateMap.get(prop.name);
115
+ if (state && prop.isBoolean) {
116
+ propAssignments.push(`${prop.name}={this.state.${state.stateName}}`);
117
+ }
118
+ else if (state && prop.isCallback) {
119
+ propAssignments.push(`${prop.name}={this.${state.callbackPropName}Handler}`);
120
+ }
121
+ else {
122
+ propAssignments.push(`${prop.name}={${(0, viewModelParser_1.sampleValueForType)(prop.typeString)}}`);
123
+ }
124
+ }
125
+ if (propAssignments.length <= 2) {
126
+ return `<${componentName} ${propAssignments.join(' ')} />`;
127
+ }
128
+ const indentedProps = propAssignments.map(p => ` ${p}`).join('\n');
129
+ return `<${componentName}\n${indentedProps}\n />`;
130
+ }
131
+ function generateBuildBazel(config) {
132
+ const prefix = config.isValdiRepo ? '' : '@valdi';
133
+ return `load("${prefix}//bzl/valdi:valdi_application.bzl", "valdi_application")
134
+ load("${prefix}//bzl/valdi:valdi_module.bzl", "valdi_module")
135
+
136
+ valdi_module(
137
+ name = "preview",
138
+ srcs = glob([
139
+ "**/*.ts",
140
+ "**/*.tsx",
141
+ ]),
142
+ visibility = ["//visibility:public"],
143
+ deps = [
144
+ "${prefix}//src/valdi_modules/src/valdi/valdi_core",
145
+ "${prefix}//src/valdi_modules/src/valdi/valdi_tsx",
146
+ "${config.moduleLabel}",
147
+ ],
148
+ )
149
+
150
+ valdi_application(
151
+ name = "preview_app",
152
+ root_component_path = "PreviewRoot@preview/PreviewRoot",
153
+ title = "Valdi Preview",
154
+ deps = [":preview"],
155
+ )
156
+ `;
157
+ }
158
+ function generateTsconfig(config) {
159
+ const previewDir = getPreviewDir(config.workspaceRoot);
160
+ if (config.isValdiRepo) {
161
+ const valdiModulesDir = path_1.default.join(config.workspaceRoot, 'src/valdi_modules/src/valdi');
162
+ const relToValdiModules = path_1.default.relative(previewDir, valdiModulesDir);
163
+ const moduleDir = findModuleDir(config.componentFilePath);
164
+ const moduleName = getModuleNameFromImport(config.importPath);
165
+ const relToModule = path_1.default.relative(previewDir, moduleDir);
166
+ const paths = {
167
+ 'preview/*': ['./*'],
168
+ 'valdi_tsx/*': [`${relToValdiModules}/valdi_tsx/*`],
169
+ 'valdi_core/*': [`${relToValdiModules}/valdi_core/*`],
170
+ 'valdi_core': [`${relToValdiModules}/valdi_core/src/tslib.d.ts`],
171
+ };
172
+ paths[`${moduleName}/*`] = [`${relToModule}/*`];
173
+ return JSON.stringify({
174
+ extends: '../../modules/_configs/base.tsconfig.json',
175
+ compilerOptions: {
176
+ types: ['../../modules/types/Long', '../../modules/types/globals'],
177
+ paths,
178
+ },
179
+ }, null, 2) + '\n';
180
+ }
181
+ const baseConfigRel = findBaseConfigRelativePath(config.workspaceRoot, previewDir);
182
+ return JSON.stringify({
183
+ extends: baseConfigRel,
184
+ compilerOptions: {
185
+ paths: {
186
+ 'preview/*': ['./*'],
187
+ },
188
+ },
189
+ }, null, 2) + '\n';
190
+ }
191
+ function findModuleDir(componentFilePath) {
192
+ let dir = path_1.default.dirname(componentFilePath);
193
+ while (dir !== path_1.default.dirname(dir)) {
194
+ const buildFile = path_1.default.join(dir, 'BUILD.bazel');
195
+ if (fs_1.default.existsSync(buildFile)) {
196
+ const content = fs_1.default.readFileSync(buildFile, 'utf8');
197
+ if (/valdi_module\s*\(/.test(content)) {
198
+ return dir;
199
+ }
200
+ }
201
+ dir = path_1.default.dirname(dir);
202
+ }
203
+ throw new Error(`Could not find a BUILD.bazel with valdi_module() above ${componentFilePath}`);
204
+ }
205
+ function getModuleNameFromImport(importPath) {
206
+ return importPath.split('/')[0];
207
+ }
208
+ function readModuleName(moduleDir) {
209
+ const buildContent = fs_1.default.readFileSync(path_1.default.join(moduleDir, 'BUILD.bazel'), 'utf8');
210
+ const nameMatch = buildContent.match(/valdi_module\s*\([^)]*name\s*=\s*"(\w+)"/s);
211
+ if (!nameMatch) {
212
+ throw new Error(`Could not find valdi_module name in ${moduleDir}/BUILD.bazel`);
213
+ }
214
+ return nameMatch[1];
215
+ }
216
+ function isValdiWorkspace(workspaceRoot) {
217
+ const wsFile = path_1.default.join(workspaceRoot, 'WORKSPACE');
218
+ if (!fs_1.default.existsSync(wsFile))
219
+ return false;
220
+ const content = fs_1.default.readFileSync(wsFile, 'utf8');
221
+ return /workspace\s*\(\s*name\s*=\s*"valdi"\s*\)/.test(content);
222
+ }
223
+ function computeModuleLabel(moduleDir, workspaceRoot) {
224
+ const relPath = path_1.default.relative(workspaceRoot, moduleDir);
225
+ const moduleName = readModuleName(moduleDir);
226
+ return `//${relPath}:${moduleName}`;
227
+ }
228
+ function findBaseConfigRelativePath(workspaceRoot, fromDir) {
229
+ const candidates = [
230
+ 'valdi_modules/_configs/base.tsconfig.json',
231
+ 'modules/_configs/base.tsconfig.json',
232
+ ];
233
+ for (const candidate of candidates) {
234
+ const fullPath = path_1.default.join(workspaceRoot, candidate);
235
+ if (fs_1.default.existsSync(fullPath)) {
236
+ return path_1.default.relative(fromDir, fullPath);
237
+ }
238
+ }
239
+ return '../../valdi_modules/_configs/base.tsconfig.json';
240
+ }
@@ -0,0 +1,203 @@
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 previewGenerator_1 = require("./previewGenerator");
9
+ describe('previewGenerator', () => {
10
+ let tmpDir;
11
+ beforeEach(() => {
12
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pg-test-'));
13
+ });
14
+ afterEach(() => {
15
+ fs.rmSync(tmpDir, { recursive: true, force: true });
16
+ });
17
+ describe('getPreviewDir', () => {
18
+ it('returns apps/preview under workspace root', () => {
19
+ expect((0, previewGenerator_1.getPreviewDir)('/workspace')).toBe('/workspace/apps/preview');
20
+ });
21
+ });
22
+ describe('getModuleNameFromImport', () => {
23
+ it('extracts the first path segment', () => {
24
+ expect((0, previewGenerator_1.getModuleNameFromImport)('widgets/src/components/Button')).toBe('widgets');
25
+ expect((0, previewGenerator_1.getModuleNameFromImport)('coreui/src/Cell')).toBe('coreui');
26
+ expect((0, previewGenerator_1.getModuleNameFromImport)('mymod')).toBe('mymod');
27
+ });
28
+ });
29
+ describe('findModuleDir', () => {
30
+ it('walks up to find BUILD.bazel with valdi_module()', () => {
31
+ const modDir = path.join(tmpDir, 'mod');
32
+ const srcDir = path.join(modDir, 'src', 'components');
33
+ fs.mkdirSync(srcDir, { recursive: true });
34
+ fs.writeFileSync(path.join(modDir, 'BUILD.bazel'), `
35
+ valdi_module(
36
+ name = "mymod",
37
+ srcs = glob(["**/*.tsx"]),
38
+ )
39
+ `, 'utf8');
40
+ const componentFile = path.join(srcDir, 'Button.tsx');
41
+ fs.writeFileSync(componentFile, 'export class Button {}', 'utf8');
42
+ expect((0, previewGenerator_1.findModuleDir)(componentFile)).toBe(modDir);
43
+ });
44
+ it('skips BUILD.bazel files without valdi_module()', () => {
45
+ const parentDir = path.join(tmpDir, 'parent');
46
+ const childDir = path.join(parentDir, 'child');
47
+ fs.mkdirSync(childDir, { recursive: true });
48
+ fs.writeFileSync(path.join(childDir, 'BUILD.bazel'), 'cc_library(name = "lib")', 'utf8');
49
+ fs.writeFileSync(path.join(parentDir, 'BUILD.bazel'), 'valdi_module(name = "mod")', 'utf8');
50
+ const componentFile = path.join(childDir, 'Comp.tsx');
51
+ fs.writeFileSync(componentFile, '', 'utf8');
52
+ expect((0, previewGenerator_1.findModuleDir)(componentFile)).toBe(parentDir);
53
+ });
54
+ it('throws when no valdi_module BUILD is found', () => {
55
+ const isolatedDir = path.join(tmpDir, 'isolated');
56
+ fs.mkdirSync(isolatedDir, { recursive: true });
57
+ const componentFile = path.join(isolatedDir, 'Comp.tsx');
58
+ fs.writeFileSync(componentFile, '', 'utf8');
59
+ expect(() => (0, previewGenerator_1.findModuleDir)(componentFile)).toThrowError(/Could not find a BUILD.bazel/);
60
+ });
61
+ });
62
+ describe('readModuleName', () => {
63
+ it('extracts module name from BUILD.bazel', () => {
64
+ const modDir = path.join(tmpDir, 'mymod');
65
+ fs.mkdirSync(modDir, { recursive: true });
66
+ fs.writeFileSync(path.join(modDir, 'BUILD.bazel'), `
67
+ load("@valdi//bzl:valdi.bzl", "valdi_module")
68
+ valdi_module(
69
+ name = "widgets",
70
+ srcs = glob(["**/*.tsx"]),
71
+ )
72
+ `, 'utf8');
73
+ expect((0, previewGenerator_1.readModuleName)(modDir)).toBe('widgets');
74
+ });
75
+ it('throws when no valdi_module name found', () => {
76
+ const modDir = path.join(tmpDir, 'bad');
77
+ fs.mkdirSync(modDir, { recursive: true });
78
+ fs.writeFileSync(path.join(modDir, 'BUILD.bazel'), 'cc_library(name = "lib")', 'utf8');
79
+ expect(() => (0, previewGenerator_1.readModuleName)(modDir)).toThrowError(/Could not find valdi_module name/);
80
+ });
81
+ });
82
+ describe('isValdiWorkspace', () => {
83
+ it('returns true for workspace named "valdi"', () => {
84
+ fs.writeFileSync(path.join(tmpDir, 'WORKSPACE'), 'workspace(name = "valdi")\n', 'utf8');
85
+ expect((0, previewGenerator_1.isValdiWorkspace)(tmpDir)).toBe(true);
86
+ });
87
+ it('returns false for other workspace names', () => {
88
+ fs.writeFileSync(path.join(tmpDir, 'WORKSPACE'), 'workspace(name = "my_app")\n', 'utf8');
89
+ expect((0, previewGenerator_1.isValdiWorkspace)(tmpDir)).toBe(false);
90
+ });
91
+ it('returns false when no WORKSPACE file exists', () => {
92
+ expect((0, previewGenerator_1.isValdiWorkspace)(tmpDir)).toBe(false);
93
+ });
94
+ });
95
+ describe('computeModuleLabel', () => {
96
+ it('computes a Bazel label from module dir', () => {
97
+ const modDir = path.join(tmpDir, 'src', 'widgets');
98
+ fs.mkdirSync(modDir, { recursive: true });
99
+ fs.writeFileSync(path.join(modDir, 'BUILD.bazel'), 'valdi_module(name = "widgets")', 'utf8');
100
+ expect((0, previewGenerator_1.computeModuleLabel)(modDir, tmpDir)).toBe('//src/widgets:widgets');
101
+ });
102
+ });
103
+ describe('generatePreviewFiles', () => {
104
+ it('generates PreviewRoot.tsx, BUILD.bazel, and tsconfig.json', () => {
105
+ const modDir = path.join(tmpDir, 'src', 'widgets');
106
+ fs.mkdirSync(modDir, { recursive: true });
107
+ fs.writeFileSync(path.join(modDir, 'BUILD.bazel'), 'valdi_module(name = "widgets")', 'utf8');
108
+ fs.writeFileSync(path.join(tmpDir, 'WORKSPACE'), 'workspace(name = "my_app")', 'utf8');
109
+ const configDir = path.join(tmpDir, 'valdi_modules', '_configs');
110
+ fs.mkdirSync(configDir, { recursive: true });
111
+ fs.writeFileSync(path.join(configDir, 'base.tsconfig.json'), '{}', 'utf8');
112
+ const config = {
113
+ componentFilePath: path.join(modDir, 'src', 'Button.tsx'),
114
+ importPath: 'widgets/src/Button',
115
+ moduleLabel: '//src/widgets:widgets',
116
+ workspaceRoot: tmpDir,
117
+ isValdiRepo: false,
118
+ viewModel: {
119
+ componentName: 'Button',
120
+ viewModelName: 'ButtonViewModel',
121
+ props: [
122
+ { name: 'label', typeString: 'string', optional: false, isBoolean: false, isCallback: false, callbackParamType: undefined },
123
+ { name: 'onTap', typeString: '() => void', optional: false, isBoolean: false, isCallback: true, callbackParamType: undefined },
124
+ ],
125
+ extraImports: [],
126
+ },
127
+ };
128
+ (0, previewGenerator_1.generatePreviewFiles)(config);
129
+ const previewDir = (0, previewGenerator_1.getPreviewDir)(tmpDir);
130
+ expect(fs.existsSync(path.join(previewDir, 'PreviewRoot.tsx'))).toBe(true);
131
+ expect(fs.existsSync(path.join(previewDir, 'BUILD.bazel'))).toBe(true);
132
+ expect(fs.existsSync(path.join(previewDir, 'tsconfig.json'))).toBe(true);
133
+ const previewTsx = fs.readFileSync(path.join(previewDir, 'PreviewRoot.tsx'), 'utf8');
134
+ expect(previewTsx).toContain("import { Button } from 'widgets/src/Button'");
135
+ expect(previewTsx).toContain('<Button');
136
+ expect(previewTsx).toContain("label={'Sample'}");
137
+ expect(previewTsx).toContain('onTap={() => {}}');
138
+ const buildBazel = fs.readFileSync(path.join(previewDir, 'BUILD.bazel'), 'utf8');
139
+ expect(buildBazel).toContain('@valdi//bzl/valdi:valdi_application.bzl');
140
+ expect(buildBazel).toContain('//src/widgets:widgets');
141
+ expect(buildBazel).toContain('root_component_path = "PreviewRoot@preview/PreviewRoot"');
142
+ const tsconfig = JSON.parse(fs.readFileSync(path.join(previewDir, 'tsconfig.json'), 'utf8'));
143
+ expect(tsconfig.compilerOptions.paths['preview/*']).toEqual(['./*']);
144
+ });
145
+ it('generates StatefulComponent when interactive state is detected', () => {
146
+ const modDir = path.join(tmpDir, 'src', 'widgets');
147
+ fs.mkdirSync(modDir, { recursive: true });
148
+ fs.writeFileSync(path.join(modDir, 'BUILD.bazel'), 'valdi_module(name = "widgets")', 'utf8');
149
+ fs.writeFileSync(path.join(tmpDir, 'WORKSPACE'), 'workspace(name = "other")', 'utf8');
150
+ const configDir = path.join(tmpDir, 'valdi_modules', '_configs');
151
+ fs.mkdirSync(configDir, { recursive: true });
152
+ fs.writeFileSync(path.join(configDir, 'base.tsconfig.json'), '{}', 'utf8');
153
+ const config = {
154
+ componentFilePath: path.join(modDir, 'src', 'Toggle.tsx'),
155
+ importPath: 'widgets/src/Toggle',
156
+ moduleLabel: '//src/widgets:widgets',
157
+ workspaceRoot: tmpDir,
158
+ isValdiRepo: false,
159
+ viewModel: {
160
+ componentName: 'Toggle',
161
+ viewModelName: 'ToggleVM',
162
+ props: [
163
+ { name: 'checked', typeString: 'boolean', optional: false, isBoolean: true, isCallback: false, callbackParamType: undefined },
164
+ { name: 'onToggle', typeString: '(val: boolean) => void', optional: false, isBoolean: false, isCallback: true, callbackParamType: 'boolean' },
165
+ ],
166
+ extraImports: [],
167
+ },
168
+ };
169
+ (0, previewGenerator_1.generatePreviewFiles)(config);
170
+ const previewTsx = fs.readFileSync(path.join((0, previewGenerator_1.getPreviewDir)(tmpDir), 'PreviewRoot.tsx'), 'utf8');
171
+ expect(previewTsx).toContain('StatefulComponent');
172
+ expect(previewTsx).toContain('state: PreviewState');
173
+ expect(previewTsx).toContain('this.state.checked');
174
+ expect(previewTsx).toContain('this.setState');
175
+ });
176
+ it('uses // prefix for Valdi repo BUILD.bazel', () => {
177
+ const modDir = path.join(tmpDir, 'src', 'widgets');
178
+ fs.mkdirSync(modDir, { recursive: true });
179
+ fs.writeFileSync(path.join(modDir, 'BUILD.bazel'), 'valdi_module(name = "widgets")', 'utf8');
180
+ fs.writeFileSync(path.join(tmpDir, 'WORKSPACE'), 'workspace(name = "valdi")', 'utf8');
181
+ const configDir = path.join(tmpDir, 'modules', '_configs');
182
+ fs.mkdirSync(configDir, { recursive: true });
183
+ fs.writeFileSync(path.join(configDir, 'base.tsconfig.json'), '{}', 'utf8');
184
+ const config = {
185
+ componentFilePath: path.join(modDir, 'src', 'Button.tsx'),
186
+ importPath: 'widgets/src/Button',
187
+ moduleLabel: '//src/widgets:widgets',
188
+ workspaceRoot: tmpDir,
189
+ isValdiRepo: true,
190
+ viewModel: {
191
+ componentName: 'Button',
192
+ viewModelName: 'ButtonVM',
193
+ props: [],
194
+ extraImports: [],
195
+ },
196
+ };
197
+ (0, previewGenerator_1.generatePreviewFiles)(config);
198
+ const buildBazel = fs.readFileSync(path.join((0, previewGenerator_1.getPreviewDir)(tmpDir), 'BUILD.bazel'), 'utf8');
199
+ expect(buildBazel).toContain('load("//bzl/valdi:valdi_application.bzl"');
200
+ expect(buildBazel).not.toContain('@valdi');
201
+ });
202
+ });
203
+ });
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseComponentFile = parseComponentFile;
4
+ exports.detectInteractiveState = detectInteractiveState;
5
+ exports.sampleValueForType = sampleValueForType;
6
+ const tslib_1 = require("tslib");
7
+ const fs_1 = tslib_1.__importDefault(require("fs"));
8
+ function parseComponentFile(filePath) {
9
+ const source = fs_1.default.readFileSync(filePath, 'utf8');
10
+ const classMatch = source.match(/export\s+class\s+(\w+)\s+extends\s+(?:Stateful)?Component<(\w+)/);
11
+ if (!classMatch) {
12
+ throw new Error(`Could not find an exported Component class in ${filePath}`);
13
+ }
14
+ const componentName = classMatch[1];
15
+ const viewModelName = classMatch[2];
16
+ const ifaceRegex = new RegExp(`(?:export\\s+)?interface\\s+${escapeRegex(viewModelName)}\\s*\\{([^}]*)\\}`, 's');
17
+ const ifaceMatch = source.match(ifaceRegex);
18
+ if (!ifaceMatch) {
19
+ throw new Error(`Could not find interface ${viewModelName} in ${filePath}`);
20
+ }
21
+ const body = ifaceMatch[1];
22
+ const props = [];
23
+ const propRegex = /^\s*(\w+)(\??):\s*(.+?)\s*;/gm;
24
+ let m;
25
+ while ((m = propRegex.exec(body)) !== null) {
26
+ const name = m[1];
27
+ const optional = m[2] === '?';
28
+ const typeString = m[3].trim();
29
+ const isBoolean = typeString === 'boolean';
30
+ const isCallback = /=>/.test(typeString);
31
+ let callbackParamType;
32
+ if (isCallback) {
33
+ const cbMatch = typeString.match(/\(\s*\w+\s*:\s*(\w+)\s*\)\s*=>/);
34
+ if (cbMatch) {
35
+ callbackParamType = cbMatch[1];
36
+ }
37
+ }
38
+ props.push({ name: name, typeString: typeString, optional, isBoolean, isCallback, callbackParamType });
39
+ }
40
+ return { componentName: componentName, viewModelName: viewModelName, props, extraImports: [] };
41
+ }
42
+ function detectInteractiveState(props) {
43
+ const boolProps = props.filter(p => p.isBoolean && !p.optional);
44
+ const callbackProps = props.filter(p => p.isCallback && p.callbackParamType === 'boolean');
45
+ const pairs = [];
46
+ for (const bp of boolProps) {
47
+ const candidate = callbackProps.find(cp => {
48
+ const cpLower = cp.name.toLowerCase();
49
+ const bpLower = bp.name.toLowerCase();
50
+ if (['ontap', 'onpress', 'onchange', 'ontoggle'].includes(cpLower))
51
+ return true;
52
+ if (cpLower === `on${bpLower}`)
53
+ return true;
54
+ return false;
55
+ });
56
+ if (candidate) {
57
+ pairs.push({
58
+ stateName: bp.name,
59
+ boolPropName: bp.name,
60
+ callbackPropName: candidate.name,
61
+ });
62
+ }
63
+ }
64
+ return pairs;
65
+ }
66
+ function sampleValueForType(typeString) {
67
+ const t = typeString.trim();
68
+ if (t === 'boolean')
69
+ return 'false';
70
+ if (t === 'string')
71
+ return "'Sample'";
72
+ if (t === 'number')
73
+ return '42';
74
+ if (t === 'Date')
75
+ return 'new Date()';
76
+ if (/^\(\s*\)\s*=>/.test(t))
77
+ return '() => {}';
78
+ if (/=>/.test(t))
79
+ return '() => {}';
80
+ if (t.endsWith('[]') || t.startsWith('Array<'))
81
+ return '[]';
82
+ return 'undefined as any';
83
+ }
84
+ function escapeRegex(str) {
85
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
86
+ }