@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
@@ -1,103 +0,0 @@
1
- const wordSplitRegex = /[\W_]/;
2
-
3
- // Bazel and common programming language reserved words that should not be used as project names
4
- const RESERVED_PROJECT_NAMES = new Set([
5
- // Bazel reserved words
6
- 'test',
7
- 'tests',
8
- 'build',
9
- 'workspace',
10
- 'native',
11
- 'rule',
12
- 'package',
13
- 'glob',
14
- 'select',
15
- 'repository',
16
- 'external',
17
- 'bazel',
18
- // Common programming language keywords that might cause issues
19
- 'class',
20
- 'function',
21
- 'var',
22
- 'let',
23
- 'const',
24
- 'if',
25
- 'else',
26
- 'for',
27
- 'while',
28
- 'return',
29
- 'import',
30
- 'export',
31
- 'module',
32
- 'require',
33
- // Other problematic names
34
- 'main',
35
- 'lib',
36
- 'src',
37
- 'bin',
38
- 'data',
39
- 'config',
40
- ]);
41
-
42
- /**
43
- * Sanitizes a project name to be safe for use in Bazel rules and generated code.
44
- * - Replaces dashes with underscores
45
- * - Removes any characters that are not alphanumeric or underscore
46
- * - Ensures the name starts with a letter or underscore
47
- * - Preserves original case (Bazel target names are case-sensitive)
48
- */
49
- export function sanitizeProjectName(name: string): string {
50
- // Replace dashes with underscores
51
- let sanitized = name.replace(/-/g, '_');
52
-
53
- // Remove any characters that are not alphanumeric or underscore
54
- sanitized = sanitized.replace(/[^a-zA-Z0-9_]/g, '');
55
-
56
- // Ensure it starts with a letter or underscore
57
- if (sanitized.length > 0 && /^[0-9]/.test(sanitized)) {
58
- sanitized = '_' + sanitized;
59
- }
60
-
61
- return sanitized;
62
- }
63
-
64
- /**
65
- * Validates a project name and returns an error message if invalid, or null if valid.
66
- */
67
- export function validateProjectName(name: string): string | null {
68
- if (!name || name.trim().length === 0) {
69
- return 'Project name cannot be empty.';
70
- }
71
-
72
- const sanitized = sanitizeProjectName(name);
73
-
74
- if (sanitized.length === 0) {
75
- return 'Project name must contain at least one alphanumeric character.';
76
- }
77
-
78
- // Check if the sanitized name (case-insensitive) is a reserved word
79
- if (RESERVED_PROJECT_NAMES.has(sanitized.toLowerCase())) {
80
- return `Project name "${name}" (sanitized to "${sanitized}") is a reserved word and cannot be used. Please choose a different name.`;
81
- }
82
-
83
- // Warn if the name was significantly changed during sanitization
84
- if (sanitized !== name.replace(/-/g, '_')) {
85
- return `Project name "${name}" contains invalid characters. It will be sanitized to "${sanitized}". Please use only letters, numbers, underscores, and dashes.`;
86
- }
87
-
88
- return null;
89
- }
90
-
91
- export function toPascalCase(str: string): string {
92
- const words = str.trim().toLowerCase().split(wordSplitRegex);
93
- return words.reduce((acc, curr) => {
94
- const [firstChar, ...rest] = curr;
95
- const pascalCaseWord = firstChar?.toUpperCase()?.concat(rest.join('')) ?? '';
96
- return acc + pascalCaseWord;
97
- }, '');
98
- }
99
-
100
- export function toSnakeCase(str: string): string {
101
- const words = str.trim().toLowerCase().split(wordSplitRegex);
102
- return words.join('_');
103
- }
@@ -1,24 +0,0 @@
1
- import crypto from 'crypto';
2
- import * as fs from 'node:fs';
3
- import os from 'os';
4
- import path from 'path';
5
-
6
- export function makeTempDir(): string {
7
- return path.join(os.tmpdir(), crypto.randomUUID());
8
- }
9
-
10
- export async function withTempDir<T>(receiveTempDir: (tempDir: string) => Promise<T>): Promise<T> {
11
- const tempDir = makeTempDir();
12
-
13
- fs.mkdirSync(tempDir);
14
-
15
- try {
16
- return await receiveTempDir(tempDir);
17
- } finally {
18
- try {
19
- fs.rmdirSync(tempDir);
20
- } catch {
21
- // no-op
22
- }
23
- }
24
- }
@@ -1,14 +0,0 @@
1
- import path from 'node:path';
2
-
3
- import extract from 'extract-zip';
4
-
5
- export async function decompressTo(inputFilePath: string, outputFilePath: string): Promise<void> {
6
- const archive = path.resolve(inputFilePath);
7
- const destination = path.resolve(outputFilePath);
8
-
9
- try {
10
- await extract(archive, { dir: destination });
11
- } catch (error: unknown) {
12
- throw new Error(`Failed to extract “${archive}” → “${destination}”: ${(error as Error).message}`);
13
- }
14
- }
@@ -1,279 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
2
- import assert from 'node:assert';
3
- import { mkdir, rm } from 'node:fs/promises';
4
- import { basename, join } from 'node:path';
5
- import { afterEach, beforeEach, describe, it } from 'node:test';
6
- import { lookForOutput } from './helpers/AsyncHelpers';
7
- import { run } from './helpers/CommandHelpers';
8
- import {
9
- atBeginning,
10
- createProject,
11
- findDefinitionForTokenInFile,
12
- insertLineAfter,
13
- insertLineBefore,
14
- lineMatches,
15
- } from './helpers/ProjectHelpers';
16
- import { type ProjectConfig } from './helpers/ProjectHelpers';
17
- import { type TSServerClient, createClient, lineAndOffset } from './helpers/TypeScriptClient';
18
- import { error } from 'node:console';
19
-
20
-
21
- const PROJECT_ROOT = process.env['PROJECT_ROOT']!;
22
- const PROJECT_NAME = process.env['PROJECT_NAME'] ?? basename(PROJECT_ROOT);
23
-
24
- // eslint-disable-next-line unicorn/prefer-module
25
- const runtimeDir = __dirname;
26
-
27
- const OPEN_SOURCE_DIR = process.env['OPEN_SOURCE_DIR']!;
28
-
29
- void describe('valdi ui app', () => {
30
- let client: TSServerClient;
31
- let project: ProjectConfig;
32
-
33
- beforeEach(async () => {
34
- await bootstrap(PROJECT_ROOT, PROJECT_NAME, 'ui_application');
35
- // Create a tsserver client to interact with tsserver
36
- client = createClient(runtimeDir);
37
- // Create the project instance which is a wrapper to find and modify files in valdi modules
38
- project = createProject(PROJECT_NAME, PROJECT_ROOT);
39
- });
40
-
41
- afterEach(async () => {
42
- // Shuts down the tsserver instance for this test
43
- await client.disconnect();
44
- });
45
-
46
- void describe('cli', () => {
47
- void it('build ios', async () => {
48
- const task = run('valdi', ['build', 'ios']);
49
- await lookForOutput({ stderr: [/Build completed successfully, \d+ total actions?/] }, task);
50
- });
51
-
52
- void it('build macos', async () => {
53
- const task = run('valdi', ['build', 'macos']);
54
- await lookForOutput({ stderr: [/Build completed successfully, \d+ total actions?/] }, task);
55
- });
56
-
57
- void it('build android', { skip: true }, async () => {
58
- const task = run('valdi', ['build', 'android']);
59
- await lookForOutput({ stderr: [/Build completed successfully, \d+ total actions?/] }, task);
60
- });
61
-
62
- void it('valdi doctor', async () => {
63
- const task = run('valdi', ['doctor']);
64
- await lookForOutput({ stdout: [
65
- 'Valdi Doctor Report',
66
- 'Node.js installation',
67
- 'Bazel installation',
68
- 'Android installation',
69
- 'iOS development',
70
- 'Java installation',
71
- 'Development tools'
72
- ]}, task)
73
- });
74
-
75
- /**
76
- * Runs `valdi new_module`
77
- * Updates `App.tsx` to import the module and use it
78
- * Checks that the tsserver discovers the reference can be found
79
- */
80
- void it('new_module ui_component', async () => {
81
- const moduleName = 'testNewModule';
82
- const task = run('valdi', ['new_module', '--skip-checks', '--template', 'ui_component', moduleName]);
83
-
84
- await lookForOutput({ stdout: ['Success! New module directory:'] }, task);
85
-
86
- // Add testNewModule bazel dependency for valdi_app
87
- await project.updateFile(
88
- 'BUILD.bazel',
89
- 'valdi_app',
90
- insertLineAfter(lineMatches('deps = ['), `\t\t"//modules/${moduleName}",\n`),
91
- );
92
-
93
- // Insert new import statement for the new module at the top of the file
94
- await project.updateFile(
95
- 'App.tsx',
96
- 'valdi_app',
97
- insertLineBefore(() => true, `import { NewModuleComponent } from '${moduleName}/src/NewModuleComponent';\n`),
98
- );
99
- // Try to use the component in onRender
100
- await project.updateFile(
101
- 'App.tsx',
102
- 'valdi_app',
103
- insertLineBefore(lineMatches('</view>;'), '<NewModuleComponent />\n'),
104
- );
105
-
106
- await run('valdi', ['projectsync'], { pipeOutput: true }).wait();
107
-
108
- // We updated the file on the filesystem, the ts client needs to know to refresh the file
109
- const file = await project.findFile('App.tsx', 'valdi_app');
110
- await client.command('open', { file });
111
-
112
- // Throws if it cannot find a valid TypeScript code reference
113
- await findDefinitionForTokenInFile({ project, client }, 'NewModuleComponent />', 'App.tsx', 'valdi_app');
114
-
115
- await client.command('close', { file });
116
- });
117
- });
118
-
119
- void describe('typescript', () => {
120
- void it('finds project references', async () => {
121
- await client.command('open', { file: await project.findFile('App.tsx', 'valdi_app') });
122
-
123
- await Promise.all(
124
- ['StatefulComponent', 'Label', 'Device', 'view>', 'style='].map(token =>
125
- findDefinitionForTokenInFile({ client, project }, token, 'App.tsx', 'valdi_app'),
126
- ),
127
- );
128
-
129
- await client.command('close', { file: await project.findFile('App.tsx', 'valdi_app') });
130
- });
131
-
132
- /**
133
- * Check for VSCode completions when typing "<l" inside the App `onRender` method.
134
- *
135
- * It should offer `<label` and `<layout`.
136
- */
137
- void it('finds code completions', async () => {
138
- const file = await project.findFile('App.tsx', 'valdi_app');
139
- await client.command('open', { file });
140
- await client.command('reload', { file });
141
-
142
- const appSource = await project.findFile('App.tsx');
143
-
144
- // Look for the whole definition block of onRender by asking tsserver for the definition
145
- const view = await lineAndOffset('onRender', appSource);
146
- const onRenderDef = (await client.command('definition', { file: appSource, ...view })) as {
147
- body?: { contextEnd: { line: number; offset: number } }[];
148
- };
149
-
150
- const defInfo = onRenderDef.body![0]!;
151
-
152
- // Insert the '<' character before the ending "}" of onRender
153
- const insertionLocation = {
154
- file: appSource,
155
- line: defInfo.contextEnd.line,
156
- endLine: defInfo.contextEnd.line,
157
- offset: defInfo.contextEnd.offset - 2,
158
- endOffset: defInfo.contextEnd.offset,
159
- };
160
-
161
- // Tell tsserver to update its representatin of the file
162
- await client.command('change', { insertString: '<l', ...insertionLocation });
163
-
164
- // Ask for the completion info at the place the '<l' was inserted
165
- const info = (await client.command('completionInfo', {
166
- file: appSource,
167
- ...defInfo.contextEnd,
168
- offset: defInfo.contextEnd.offset,
169
- prefix: 'l',
170
- })) as { body?: { entries: { name: string }[] } };
171
-
172
- // We expect certain items to be available as completions
173
- const completionsExpected = ['label', 'layout'];
174
- const missing = completionsExpected.filter(
175
- item => info.body!.entries.some(({ name }) => name === item) === undefined,
176
- );
177
-
178
- if (missing.length > 0) {
179
- throw new Error('missing completions: ' + missing.join(', '));
180
- }
181
-
182
- await client.command('close', { file });
183
- });
184
-
185
- void it('has localized strings', async () => {
186
- await project.updateFile(
187
- 'BUILD.bazel',
188
- 'valdi_app',
189
- insertLineBefore(lineMatches('visibility = ["//visibility:public"],'), ' strings_dir = "strings",\n'),
190
- );
191
-
192
- const strings = {
193
- l10nsvc: 'sourcefile',
194
- welcome: {
195
- defaultMessage: 'Hello World',
196
- },
197
- };
198
-
199
- await project.createFile('strings/strings-en.json', 'valdi_app', JSON.stringify(strings, null, ' '));
200
- await run('valdi', ['projectsync'], { pipeOutput: true }).wait();
201
-
202
- await project.updateFile(
203
- 'App.tsx',
204
- 'valdi_app',
205
- insertLineBefore(atBeginning, "import strings from './Strings'\n"),
206
- );
207
-
208
- const appFile = await project.findFile('App.tsx', 'valdi_app');
209
- await client.command('open', { file: appFile });
210
- const [pathDescriptor] = await findDefinitionForTokenInFile(
211
- { project, client },
212
- 'strings',
213
- 'App.tsx',
214
- 'valdi_app',
215
- );
216
-
217
- assert.match(pathDescriptor, /\/generated_ts\/valdi_app\/src\/Strings\.d\.ts:\d+:\d+/);
218
-
219
- await client.command('close', { file: appFile });
220
- });
221
- });
222
- });
223
-
224
- void describe('valdi cli app', () => {
225
- const CLI_PROJECT_ROOT = join(PROJECT_ROOT, 'valdi_cli_app');
226
- const CLI_PROJECT_NAME = basename(CLI_PROJECT_ROOT);
227
-
228
- beforeEach(async () => {
229
- await bootstrap(CLI_PROJECT_ROOT, CLI_PROJECT_NAME, 'cli_application');
230
- });
231
-
232
- void it('install cli', async () => {
233
- const task = run('valdi', ['install', 'cli'], { pipeOutput: true });
234
- await lookForOutput(
235
- {
236
- // means the bazel build was succesful
237
- stderr: [/Build completed successfully, \d+ total actions?/],
238
- // The default bootstrapped app logs "Hello world!"
239
- stdout: ['Hello world!'],
240
- },
241
- task,
242
- );
243
- });
244
- });
245
-
246
- /**
247
- * Sets up a valdi project for tests
248
- *
249
- * - Delete's the existing directory (if any)
250
- * - Re-creates the directory
251
- * - Changes the currenty working directory to the new directory
252
- * - Runs `valdi bootstrap` linked to the OPEN_SOURCE_DIR for `@@valdi`
253
- * - Runs `valdi projectsync`
254
- */
255
- async function bootstrap(
256
- projectRootPath: string,
257
- projectName: string,
258
- applicationType: 'ui_application' | 'cli_application',
259
- ) {
260
- // Delete and recreate the bootstrapped project
261
- await rm(projectRootPath, { recursive: true, force: true }).catch((error) => {
262
- // Logging the failure; if it doesn't exist the force flag will handle it
263
- console.error('Failed to remove', projectRootPath, ':', error);
264
- });
265
- await mkdir(projectRootPath, { recursive: true });
266
-
267
- // Run all commands from within the projectRootPath
268
- process.chdir(projectRootPath);
269
-
270
- await run(
271
- 'valdi',
272
- ['bootstrap', '-y', `-n=${projectName}`, `-t=${applicationType}`, `-l=${OPEN_SOURCE_DIR}`, '-p', '--with-cleanup'],
273
- {
274
- pipeOutput: true,
275
- },
276
- ).wait();
277
-
278
- await run('valdi', ['projectsync'], { pipeOutput: true }).wait();
279
- }
@@ -1,113 +0,0 @@
1
- import type { SubCommand } from './CommandHelpers';
2
- import { onEachLine } from './StreamHelpers';
3
-
4
- /**
5
- * Create a Promise that rejects after ms milliseconds from the last time it is "touched".
6
- *
7
- * Returns a promise, a function to reset the timeout, and a function to clear the timeout.
8
- *
9
- * The returned promise will never resolve.
10
- */
11
- export function timeoutOnIdle(ms = 30_000): [timeout: Promise<never>, touch: () => void, clear: () => void] {
12
- let timer: NodeJS.Timeout;
13
- let resetTimer: () => void;
14
- let clearTimer: () => void;
15
- let complete = false;
16
-
17
- const timeout = new Promise<never>((_resolve, reject) => {
18
- clearTimer = () => {
19
- complete = true;
20
- clearTimeout(timer);
21
- };
22
-
23
- resetTimer = () => {
24
- clearTimeout(timer);
25
- if (complete) {
26
- return;
27
- }
28
- timer = setTimeout(() => {
29
- complete = true;
30
- reject(new Error('timeout'));
31
- }, ms);
32
- };
33
-
34
- resetTimer();
35
- });
36
-
37
- return [timeout, () => resetTimer(), () => clearTimer()];
38
- }
39
-
40
- /**
41
- * Given a task created with CommandHelpers.run, watches the STDOUT and/or STDERR
42
- * for the given strings or expressions.
43
- *
44
- * Will timeeout if there's no output after 30 seconds.
45
- *
46
- * Rejects if there are queries remaning after the
47
- */
48
- export function lookForOutput(
49
- { stdout = [], stderr = [] }: { stdout?: (string | RegExp)[]; stderr?: (string | RegExp)[] },
50
- subcommand: SubCommand,
51
- ): Promise<true> {
52
- const [idleTimer, touch, complete] = timeoutOnIdle();
53
-
54
- const monitor = (requiredQueries: (string | RegExp)[]) => {
55
- let queries = requiredQueries.slice();
56
- let onDone: (value: true) => void, onError: (error: Error) => void;
57
-
58
- const promise = new Promise((resolve, reject) => {
59
- onDone = resolve;
60
- onError = reject;
61
-
62
- // If queries are empty to start with resolve immediately
63
- if (queries.length === 0) {
64
- resolve(true);
65
- }
66
- });
67
-
68
- const isDone = () => queries.length === 0;
69
-
70
- return {
71
- promise,
72
- isDone,
73
- onEachLine: onEachLine(line => {
74
- touch();
75
- queries = queries.filter((query): boolean => {
76
- if (typeof query === 'string') {
77
- return !line.toString().includes(query);
78
- }
79
- if (query instanceof RegExp) {
80
- return !query.test(line.toString('utf8'));
81
- }
82
- onError(new Error('invalid query'));
83
- return false;
84
- });
85
-
86
- if (isDone()) {
87
- onDone(true);
88
- return;
89
- }
90
- }),
91
- };
92
- };
93
-
94
- const stdoutMonitor = monitor(stdout);
95
- const stderrMonitor = monitor(stderr);
96
-
97
- subcommand.process.stdout.compose(stdoutMonitor.onEachLine).pipe(process.stdout);
98
- subcommand.process.stderr.compose(stderrMonitor.onEachLine).pipe(process.stderr);
99
-
100
- return Promise.race([
101
- idleTimer,
102
- subcommand
103
- .wait()
104
- .then((): true => {
105
- const allFound = [stderrMonitor, stderrMonitor].every(monitor => monitor.isDone());
106
- if (allFound) {
107
- return true;
108
- }
109
- throw new Error('Not all queries found: ' + [stdout, stderr].map(q => q.toString()).join('\n - '));
110
- })
111
- .finally(() => complete()),
112
- ]);
113
- }
@@ -1,37 +0,0 @@
1
- import { type ChildProcessWithoutNullStreams, spawn } from 'child_process';
2
-
3
- export interface SubCommand {
4
- process: ChildProcessWithoutNullStreams;
5
- /**
6
- * Resolvess when the command exits
7
- */
8
- wait: () => Promise<number>;
9
- }
10
-
11
- export const run = (
12
- command: string,
13
- args: string[] = [],
14
- { pipeOutput = false, cwd }: { pipeOutput?: boolean; cwd?: string } = {},
15
- ): SubCommand => {
16
- const child = spawn(command, args, { detached: true, stdio: 'pipe', cwd });
17
-
18
- if (pipeOutput) {
19
- child.stderr.pipe(process.stderr);
20
- child.stdout.pipe(process.stdout);
21
- }
22
-
23
- const complete = new Promise<number>((resolve, reject) => {
24
- child.on('close', exitCode => {
25
- if (exitCode !== null && exitCode !== 0) {
26
- reject(new Error(command + ' ' + args.join(' ') + ' failed with code ' + exitCode.toString()));
27
- return;
28
- }
29
- resolve(exitCode ?? 0);
30
- });
31
- });
32
-
33
- return {
34
- process: child,
35
- wait: () => complete,
36
- };
37
- };