@snap/valdi 1.0.1

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 (143) hide show
  1. package/.bazelignore +2 -0
  2. package/.bootstrap/apps/cli_application/AGENTS.md.template +215 -0
  3. package/.bootstrap/apps/cli_application/BUILD.bazel.template +7 -0
  4. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +11 -0
  5. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +1 -0
  6. package/.bootstrap/apps/ui_application/.eslint.rc +27 -0
  7. package/.bootstrap/apps/ui_application/AGENTS.md.template +202 -0
  8. package/.bootstrap/apps/ui_application/BUILD.bazel.template +19 -0
  9. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +21 -0
  10. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  11. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +133 -0
  12. package/.bootstrap/apps/ui_application/package.json +24 -0
  13. package/.bootstrap/modules/cpp_bridge_module/BUILD.bazel.template +21 -0
  14. package/.bootstrap/modules/cpp_bridge_module/cpp/CalculatorModuleFactory.cpp.template +29 -0
  15. package/.bootstrap/modules/cpp_bridge_module/src/Calculator.d.ts +1 -0
  16. package/.bootstrap/modules/ios_android_bridge_module/BUILD.bazel.template +39 -0
  17. package/.bootstrap/modules/ios_android_bridge_module/android/CalculatorModuleFactory.kt.template +18 -0
  18. package/.bootstrap/modules/ios_android_bridge_module/ios/SCCCalculatorModuleFactory.m.template +31 -0
  19. package/.bootstrap/modules/ios_android_bridge_module/src/Calculator.d.ts +4 -0
  20. package/.bootstrap/modules/ios_android_view_module/BUILD.bazel.template +41 -0
  21. package/.bootstrap/modules/ios_android_view_module/android/CircleView.kt.template +42 -0
  22. package/.bootstrap/modules/ios_android_view_module/android/CircleViewAttributesBinder.kt.template +60 -0
  23. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.h +6 -0
  24. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.m +82 -0
  25. package/.bootstrap/modules/ios_android_view_module/src/Circle.tsx.template +15 -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/.config/copyconfig.json +10 -0
  29. package/.editorconfig +21 -0
  30. package/.eslintignore +1 -0
  31. package/.eslintrc.js +72 -0
  32. package/.metadata/.bazelrc.template +91 -0
  33. package/.metadata/.bazelversion.template +1 -0
  34. package/.metadata/.eslintrc.js.template +27 -0
  35. package/.metadata/.gitignore.template +4 -0
  36. package/.metadata/.prettierrc.json.template +7 -0
  37. package/.metadata/.watchmanconfig.template +8 -0
  38. package/.metadata/README.md.template +31 -0
  39. package/.metadata/WORKSPACE.template +57 -0
  40. package/.metadata/config.yaml.template +1 -0
  41. package/.metadata/package.json.template +23 -0
  42. package/.prettierignore +2 -0
  43. package/.prettierrc.json +7 -0
  44. package/README.md +123 -0
  45. package/dist/commands/bootstrap.js +233 -0
  46. package/dist/commands/build.js +67 -0
  47. package/dist/commands/devSetup.js +18 -0
  48. package/dist/commands/doctor.js +892 -0
  49. package/dist/commands/export.js +84 -0
  50. package/dist/commands/hotreload.js +89 -0
  51. package/dist/commands/install.js +71 -0
  52. package/dist/commands/lint.js +18 -0
  53. package/dist/commands/lint_commands/lintCheck.js +31 -0
  54. package/dist/commands/lint_commands/lintFormat.js +31 -0
  55. package/dist/commands/log.js +84 -0
  56. package/dist/commands/newModule.js +208 -0
  57. package/dist/commands/package.js +66 -0
  58. package/dist/commands/projectsync.js +316 -0
  59. package/dist/commands/test.js +54 -0
  60. package/dist/core/constants.js +76 -0
  61. package/dist/core/errors.js +12 -0
  62. package/dist/index.js +22 -0
  63. package/dist/setup/DevSetupHelper.js +146 -0
  64. package/dist/setup/linuxSetup.js +31 -0
  65. package/dist/setup/macOSSetup.js +35 -0
  66. package/dist/setup/setupEntryPoint.js +56 -0
  67. package/dist/setup/versions.js +8 -0
  68. package/dist/utils/ArgumentsResolver.js +23 -0
  69. package/dist/utils/BazelClient.js +219 -0
  70. package/dist/utils/Digraph.js +71 -0
  71. package/dist/utils/LoadingIndicator.js +38 -0
  72. package/dist/utils/applicationUtils.js +201 -0
  73. package/dist/utils/buildInfo.js +60 -0
  74. package/dist/utils/byString.js +6 -0
  75. package/dist/utils/cliUtils.js +93 -0
  76. package/dist/utils/copyBootstrapFiles.js +26 -0
  77. package/dist/utils/deviceUtils.js +72 -0
  78. package/dist/utils/errorUtils.js +55 -0
  79. package/dist/utils/fileUtils.js +204 -0
  80. package/dist/utils/githubUtils.js +8 -0
  81. package/dist/utils/jsonUtils.js +28 -0
  82. package/dist/utils/lintUtils.js +149 -0
  83. package/dist/utils/logUtils.js +8 -0
  84. package/dist/utils/pathUtils.js +12 -0
  85. package/dist/utils/stringUtils.js +17 -0
  86. package/dist/utils/stringUtils.spec.js +18 -0
  87. package/dist/utils/tempDir.js +26 -0
  88. package/dist/utils/zipUtils.js +16 -0
  89. package/package.json +51 -0
  90. package/prettier.config.js +4 -0
  91. package/spec/support/jasmine.json +6 -0
  92. package/src/commands/bootstrap.ts +317 -0
  93. package/src/commands/build.ts +89 -0
  94. package/src/commands/devSetup.ts +17 -0
  95. package/src/commands/doctor.ts +1422 -0
  96. package/src/commands/export.ts +131 -0
  97. package/src/commands/hotreload.ts +108 -0
  98. package/src/commands/install.ts +93 -0
  99. package/src/commands/lint.ts +15 -0
  100. package/src/commands/lint_commands/lintCheck.ts +53 -0
  101. package/src/commands/lint_commands/lintFormat.ts +49 -0
  102. package/src/commands/log.ts +108 -0
  103. package/src/commands/newModule.ts +287 -0
  104. package/src/commands/package.ts +102 -0
  105. package/src/commands/projectsync.ts +488 -0
  106. package/src/commands/test.ts +68 -0
  107. package/src/core/constants.ts +95 -0
  108. package/src/core/errors.ts +10 -0
  109. package/src/index.ts +22 -0
  110. package/src/setup/DevSetupHelper.ts +188 -0
  111. package/src/setup/linuxSetup.ts +38 -0
  112. package/src/setup/macOSSetup.ts +42 -0
  113. package/src/setup/setupEntryPoint.ts +64 -0
  114. package/src/setup/versions.ts +8 -0
  115. package/src/utils/ArgumentsResolver.ts +23 -0
  116. package/src/utils/BazelClient.ts +285 -0
  117. package/src/utils/Digraph.ts +81 -0
  118. package/src/utils/LoadingIndicator.ts +43 -0
  119. package/src/utils/applicationUtils.ts +276 -0
  120. package/src/utils/buildInfo.ts +99 -0
  121. package/src/utils/byString.ts +3 -0
  122. package/src/utils/cliUtils.ts +112 -0
  123. package/src/utils/copyBootstrapFiles.ts +30 -0
  124. package/src/utils/deviceUtils.ts +76 -0
  125. package/src/utils/errorUtils.ts +63 -0
  126. package/src/utils/fileUtils.ts +257 -0
  127. package/src/utils/githubUtils.ts +6 -0
  128. package/src/utils/jsonUtils.ts +30 -0
  129. package/src/utils/lintUtils.ts +190 -0
  130. package/src/utils/logUtils.ts +9 -0
  131. package/src/utils/pathUtils.ts +12 -0
  132. package/src/utils/stringUtils.spec.ts +19 -0
  133. package/src/utils/stringUtils.ts +15 -0
  134. package/src/utils/tempDir.ts +24 -0
  135. package/src/utils/zipUtils.ts +14 -0
  136. package/test/ValdiSmokeTest.ts +278 -0
  137. package/test/helpers/AsyncHelpers.ts +113 -0
  138. package/test/helpers/CommandHelpers.ts +37 -0
  139. package/test/helpers/ProjectHelpers.ts +153 -0
  140. package/test/helpers/StreamHelpers.ts +37 -0
  141. package/test/helpers/TypeScriptClient.ts +217 -0
  142. package/tsconfig.dist.json +8 -0
  143. package/tsconfig.json +42 -0
@@ -0,0 +1,81 @@
1
+ export interface DigraphNode {
2
+ name: string;
3
+ edges: DigraphNode[];
4
+ }
5
+
6
+ function unquote(str: string): string {
7
+ return str.slice(1, -1);
8
+ }
9
+
10
+ export class Digraph {
11
+ private nodeByName = new Map<string, DigraphNode>();
12
+ private _allNodes: DigraphNode[] = [];
13
+
14
+ constructor() {}
15
+
16
+ get nodes(): readonly DigraphNode[] {
17
+ return this._allNodes;
18
+ }
19
+
20
+ static parse(str: string): Digraph {
21
+ const lines = str.split('\n');
22
+ const graph = new Digraph();
23
+
24
+ let index = 0;
25
+ for (const line of lines) {
26
+ const trimmedLine = line.trim();
27
+ if (trimmedLine.startsWith('digraph ')) {
28
+ if (index !== 0) {
29
+ this.throwInvalidGraph();
30
+ }
31
+ } else if (trimmedLine === '}') {
32
+ if (index !== lines.length - 1) {
33
+ this.throwInvalidGraph();
34
+ }
35
+ } else if (trimmedLine.startsWith('node ')) {
36
+ // no-op
37
+ } else if (trimmedLine.startsWith('"')) {
38
+ const edgeIndex = trimmedLine.indexOf('->');
39
+ if (edgeIndex >= 0) {
40
+ const fromEdge = unquote(trimmedLine.slice(0, edgeIndex).trim());
41
+ const toEdge = unquote(trimmedLine.slice(edgeIndex + 2).trim());
42
+ graph.addEdge(fromEdge, toEdge);
43
+ } else {
44
+ graph.getOrCreateNode(unquote(trimmedLine))
45
+ }
46
+ } else {
47
+ this.throwInvalidGraph();
48
+ }
49
+
50
+ index++;
51
+ }
52
+
53
+ return graph;
54
+ }
55
+
56
+ private static throwInvalidGraph(): never {
57
+ throw new Error('Could not parse digraph');
58
+ }
59
+
60
+ getNode(name: string): DigraphNode | undefined {
61
+ return this.nodeByName.get(name);
62
+ }
63
+
64
+ getOrCreateNode(name: string): DigraphNode {
65
+ let node = this.nodeByName.get(name);
66
+ if (!node) {
67
+ node = { name, edges: [] };
68
+ this.nodeByName.set(name, node);
69
+ this._allNodes.push(node);
70
+ }
71
+
72
+ return node;
73
+ }
74
+
75
+ addEdge(from: string, to: string): void {
76
+ const fromNode = this.getOrCreateNode(from);
77
+ const toNode = this.getOrCreateNode(to);
78
+
79
+ fromNode.edges.push(toNode);
80
+ }
81
+ }
@@ -0,0 +1,43 @@
1
+ // We use dynamic imports here because ora uses
2
+ // the ES6 import syntax, which cannot be fixed
3
+ // with require() style imports on older node js versions.
4
+
5
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports, @typescript-eslint/no-implied-eval
6
+ const ora = new Function("return import('ora')") as () => Promise<typeof import('ora')>;
7
+
8
+ export class LoadingIndicator<T> {
9
+ private text = '';
10
+ private successText: string | undefined;
11
+ private failureText: string | undefined;
12
+
13
+ constructor(private readonly runnable: () => PromiseLike<T>) {}
14
+
15
+ static fromTask<T>(task: PromiseLike<T>): LoadingIndicator<T> {
16
+ return new LoadingIndicator<T>(() => task);
17
+ }
18
+
19
+ setText(text: string): LoadingIndicator<T> {
20
+ this.text = text;
21
+ return this;
22
+ }
23
+
24
+ setSuccessText(successText: string): LoadingIndicator<T> {
25
+ this.successText = successText;
26
+ return this;
27
+ }
28
+
29
+ setFailureText(failureText: string): LoadingIndicator<T> {
30
+ this.failureText = failureText;
31
+ return this;
32
+ }
33
+
34
+ show(): Promise<T> {
35
+ return ora().then(ora => {
36
+ return ora.oraPromise(this.runnable(), {
37
+ text: this.text,
38
+ successText: this.successText,
39
+ failText: this.failureText,
40
+ });
41
+ });
42
+ }
43
+ }
@@ -0,0 +1,276 @@
1
+ import path from 'path';
2
+ import type { Argv } from 'yargs';
3
+ import {
4
+ ANDROID_ARM64_BUILD_FLAGS,
5
+ ANDROID_ARMV7_BUILD_FLAGS,
6
+ ANDROID_BAZEL_APPLICATION_TAG,
7
+ ANDROID_BUILD_FLAGS,
8
+ ANDROID_EXPORTED_LIBRARY_TAG,
9
+ ANDROID_X86_64_BUILD_FLAGS,
10
+ ANSI_COLORS,
11
+ Architecture,
12
+ CLI_BAZEL_APPLICATION_TAG,
13
+ CLI_BUILD_FLAGS,
14
+ DEBUG_BUILD_FLAGS,
15
+ ENABLE_RUNTIME_LOGS_BUILD_FLAGS,
16
+ ENABLE_RUNTIME_TRACES_BUILD_FLAGS,
17
+ IOS_BAZEL_APPLICATION_TAG,
18
+ IOS_BUILD_FLAGS,
19
+ IOS_DEVICE_BUILD_FLAGS,
20
+ IOS_EXPORTED_LIBRARY_TAG,
21
+ MACOS_BAZEL_APPLICATION_TAG,
22
+ MACOS_BUILD_FLAGS,
23
+ PLATFORM,
24
+ RELEASE_BUILD_FLAGS,
25
+ VALID_PLATFORMS,
26
+ } from '../core/constants';
27
+ import { CliError } from '../core/errors';
28
+ import type { BazelClient } from './BazelClient';
29
+ import type { CliChoice } from './cliUtils';
30
+ import { getUserChoice } from './cliUtils';
31
+ import { wrapInColor } from './logUtils';
32
+
33
+ export interface SharedCommandParameters {
34
+ platform: string | undefined;
35
+ bazel_args: string | undefined;
36
+ build_config: 'debug' | 'release';
37
+ enable_runtime_logs: boolean | undefined;
38
+ enable_runtime_traces: boolean | undefined;
39
+ }
40
+
41
+ export function makeArgsBuilder<T extends SharedCommandParameters>(
42
+ nestedBuilder: (yargs: Argv<T>) => void,
43
+ ): (yargs: Argv<T>) => void {
44
+ return yargs => {
45
+ yargs
46
+ .positional('platform', {
47
+ describe: 'Platform to build the library or application for: <ios|android>',
48
+ type: 'string',
49
+ choices: VALID_PLATFORMS,
50
+ coerce: arg => {
51
+ return arg === undefined ? undefined : String(arg).toLowerCase();
52
+ },
53
+ })
54
+ .option('build_config', {
55
+ describe: 'Specifiy whether the application or library should be built in release or debug mode',
56
+ type: 'string',
57
+ choices: ['debug', 'release'],
58
+ default: 'debug',
59
+ requiresArg: true,
60
+ })
61
+ .option('enable_runtime_logs', {
62
+ describe: 'Specifiy Valdi runtime logs should be enabled',
63
+ type: 'boolean',
64
+ default: false,
65
+ })
66
+ .option('enable_runtime_traces', {
67
+ describe: 'Specifiy Valdi runtime traces should be enabled',
68
+ type: 'boolean',
69
+ default: false,
70
+ })
71
+ .option('bazel_args', {
72
+ describe: `Additional arguments to pass to bazel build. Use format ${wrapInColor('--bazel_args="<args>"', ANSI_COLORS.YELLOW_COLOR)}.`,
73
+ type: 'string',
74
+ requiresArg: true,
75
+ });
76
+
77
+ nestedBuilder(yargs);
78
+ };
79
+ }
80
+
81
+ export async function selectBazelTarget(
82
+ bazel: BazelClient,
83
+ tag: string,
84
+ targetTypeName: string,
85
+ promptText: string,
86
+ ): Promise<string> {
87
+ const unfilteredAvailableTargets = await bazel.queryTargetsForTag(tag);
88
+ const availableTargets = unfilteredAvailableTargets.filter(c => !c.endsWith('_DO_NOT_USE'));
89
+
90
+ if (availableTargets.length === 0) {
91
+ throw new CliError(`No ${targetTypeName} targets found...`);
92
+ } else if (availableTargets.length === 1) {
93
+ console.log(
94
+ `Only one ${targetTypeName} target found, using it:`,
95
+ wrapInColor(availableTargets[0], ANSI_COLORS.GREEN_COLOR),
96
+ );
97
+
98
+ return availableTargets[0] ?? '';
99
+ }
100
+
101
+ // Prompt user to select an application target
102
+ const choices: Array<CliChoice<string>> = availableTargets.map((target, index) => ({
103
+ name: `${index + 1}. ${target}`,
104
+ value: target,
105
+ }));
106
+
107
+ return await getUserChoice(choices, promptText);
108
+ }
109
+
110
+ export function getApplicationTargetTagForPlatform(platform: PLATFORM): string {
111
+ switch (platform) {
112
+ case PLATFORM.IOS: {
113
+ return IOS_BAZEL_APPLICATION_TAG;
114
+ }
115
+ case PLATFORM.ANDROID: {
116
+ return ANDROID_BAZEL_APPLICATION_TAG;
117
+ }
118
+ case PLATFORM.MACOS: {
119
+ return MACOS_BAZEL_APPLICATION_TAG;
120
+ }
121
+ case PLATFORM.CLI: {
122
+ return CLI_BAZEL_APPLICATION_TAG;
123
+ }
124
+ }
125
+ }
126
+
127
+ export function getExportedLibraryTargetTagForPlatform(platform: PLATFORM): string {
128
+ switch (platform) {
129
+ case PLATFORM.IOS: {
130
+ return IOS_EXPORTED_LIBRARY_TAG;
131
+ }
132
+ case PLATFORM.ANDROID: {
133
+ return ANDROID_EXPORTED_LIBRARY_TAG;
134
+ }
135
+ case PLATFORM.MACOS: {
136
+ throw new CliError('Exported library is not yet supported for macOS platform');
137
+ }
138
+ case PLATFORM.CLI: {
139
+ throw new CliError('Exported library is not supported for CLI platform');
140
+ }
141
+ }
142
+ }
143
+
144
+ export function applicationExtensionForPlatform(platform: PLATFORM): string {
145
+ switch (platform) {
146
+ case PLATFORM.IOS: {
147
+ return '.ipa';
148
+ }
149
+ case PLATFORM.ANDROID: {
150
+ return '.apk';
151
+ }
152
+ case PLATFORM.MACOS: {
153
+ return '.zip';
154
+ }
155
+ case PLATFORM.CLI: {
156
+ return '';
157
+ }
158
+ }
159
+ }
160
+
161
+ export function exportedLibraryExtensionForPlatform(platform: PLATFORM): string {
162
+ switch (platform) {
163
+ case PLATFORM.IOS: {
164
+ return '.xcframework';
165
+ }
166
+ case PLATFORM.ANDROID: {
167
+ return '.aar';
168
+ }
169
+ case PLATFORM.MACOS: {
170
+ return '.zip';
171
+ }
172
+ case PLATFORM.CLI: {
173
+ return '.zip';
174
+ }
175
+ }
176
+ }
177
+
178
+ // Reads and selects the output path for the build & install
179
+ export async function getOutputFilePath(
180
+ bazel: BazelClient,
181
+ expectedExtension: string,
182
+ target: string,
183
+ bazelArgs: string = '',
184
+ ): Promise<string> {
185
+ const workspaceRootResult = await bazel.getWorkspaceRoot();
186
+ const buildOutputsResult = await bazel.queryBuildOutputs([target], bazelArgs);
187
+
188
+ // TODO(yhuang6): Have a way to prompt for selection and memorize it and/or
189
+ // add an option to specify name of apk.
190
+ let appChoices = buildOutputsResult;
191
+ if (expectedExtension.length > 0) {
192
+ appChoices = buildOutputsResult.filter(
193
+ output => output.endsWith(expectedExtension) && !output.includes('_unsigned'),
194
+ );
195
+ }
196
+
197
+ let outputPath;
198
+ if (appChoices.length === 0) {
199
+ throw new CliError('No outputs are found...');
200
+ } else if (appChoices.length === 1) {
201
+ outputPath = appChoices[0];
202
+ } else {
203
+ outputPath = await getUserChoice(
204
+ appChoices.map((output, index) => ({ name: `${index + 1}. ${output}`, value: output })),
205
+ 'Please select the app to install:',
206
+ );
207
+ }
208
+
209
+ return outputPath === undefined ? '' : path.join(workspaceRootResult, outputPath);
210
+ }
211
+
212
+ function androidBuildFlagsForArchitecture(architecture: Architecture): readonly string[] {
213
+ switch (architecture) {
214
+ case Architecture.ARM64: {
215
+ return ANDROID_ARM64_BUILD_FLAGS;
216
+ }
217
+ case Architecture.ARMV7: {
218
+ return ANDROID_ARMV7_BUILD_FLAGS;
219
+ }
220
+ case Architecture.X86_64: {
221
+ return ANDROID_X86_64_BUILD_FLAGS;
222
+ }
223
+ }
224
+ }
225
+
226
+ export function resolveBazelBuildArgs(
227
+ platform: PLATFORM,
228
+ buildConfig: 'debug' | 'release' | undefined,
229
+ architectures: Architecture[],
230
+ forDevice: boolean,
231
+ enableRuntimeLogs: boolean | undefined,
232
+ enableRuntimeTracing: boolean | undefined,
233
+ additionalBazelArgs: string | undefined,
234
+ ): string {
235
+ const allArgs: string[] = [];
236
+
237
+ if (buildConfig === 'release') {
238
+ allArgs.push(...RELEASE_BUILD_FLAGS);
239
+ } else {
240
+ allArgs.push(...DEBUG_BUILD_FLAGS);
241
+ }
242
+
243
+ if (enableRuntimeLogs) {
244
+ allArgs.push(...ENABLE_RUNTIME_LOGS_BUILD_FLAGS);
245
+ }
246
+ if (enableRuntimeTracing) {
247
+ allArgs.push(...ENABLE_RUNTIME_TRACES_BUILD_FLAGS);
248
+ }
249
+
250
+ if (platform === PLATFORM.IOS) {
251
+ allArgs.push(IOS_BUILD_FLAGS);
252
+
253
+ if (forDevice) {
254
+ allArgs.push(IOS_DEVICE_BUILD_FLAGS);
255
+ }
256
+ }
257
+
258
+ if (platform === PLATFORM.CLI) {
259
+ allArgs.push(...CLI_BUILD_FLAGS);
260
+ } else if (platform === PLATFORM.MACOS) {
261
+ allArgs.push(...MACOS_BUILD_FLAGS);
262
+ }
263
+
264
+ if (platform === PLATFORM.ANDROID) {
265
+ allArgs.push(...ANDROID_BUILD_FLAGS);
266
+
267
+ for (const architecture of architectures) {
268
+ allArgs.push(...androidBuildFlagsForArchitecture(architecture));
269
+ }
270
+ }
271
+
272
+ if (additionalBazelArgs) {
273
+ allArgs.push(additionalBazelArgs);
274
+ }
275
+ return allArgs.join(' ');
276
+ }
@@ -0,0 +1,99 @@
1
+ import Separator from "inquirer/lib/objects/separator";
2
+ import { ALL_ARCHITECTURES, ANSI_COLORS, Architecture, PLATFORM } from "../core/constants";
3
+ import { CliError } from "../core/errors";
4
+ import { getApplicationTargetTagForPlatform, resolveBazelBuildArgs, selectBazelTarget, SharedCommandParameters } from "./applicationUtils";
5
+ import { ArgumentsResolver } from "./ArgumentsResolver";
6
+ import { CliChoice, getUserChoice } from "./cliUtils";
7
+ import { getAllArchitecturesForAndroid, getArchitectureForAndroidDevice, getConnectedDevices } from "./deviceUtils";
8
+ import { wrapInColor } from "./logUtils";
9
+ import { BazelClient } from "./BazelClient";
10
+
11
+ export interface BuildInfo {
12
+ platform: PLATFORM;
13
+ application: string;
14
+ bazelArgs: string;
15
+ selectedDevice: string | undefined
16
+ }
17
+
18
+ export interface CommandParameters extends SharedCommandParameters {
19
+ application: string | undefined;
20
+ device_id: string | undefined;
21
+ target_output_path: string | undefined;
22
+ simulator: boolean | undefined;
23
+ }
24
+
25
+ // Prompts User to choose from the list of available devices
26
+ // No prompt if only one device is available
27
+ async function getDeviceChoice(platform: string): Promise<string> {
28
+ const availableDevices = await getConnectedDevices(platform);
29
+
30
+ if (availableDevices.length === 0) {
31
+ throw new CliError('No devices connected...');
32
+ } else if (availableDevices.length === 1) {
33
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
34
+ const selectedDevice: string = availableDevices[0]!;
35
+ console.log('Only one device connected, using it:', wrapInColor(selectedDevice, ANSI_COLORS.GREEN_COLOR));
36
+ return selectedDevice;
37
+ }
38
+
39
+ // Prompt user to select a device
40
+ const choices: Array<CliChoice<string> | Separator> = [];
41
+
42
+ if (platform === PLATFORM.ANDROID) {
43
+ choices.push(new Separator('-----Android Devices-----'));
44
+ } else if (platform === PLATFORM.IOS) {
45
+ choices.push(new Separator('-----iOS Devices-----'));
46
+ }
47
+ choices.push(...availableDevices.map(device => ({ name: device, value: device })));
48
+
49
+ return await getUserChoice(choices, 'Please select a device to perform the install:');
50
+ }
51
+
52
+ export async function getBuildInfo(argv: ArgumentsResolver<CommandParameters>, bazel: BazelClient, checkDevice: boolean): Promise<BuildInfo> {
53
+ const platform = argv.getArgument('platform') as PLATFORM;
54
+ const forDevice = !!argv.getArgument('simulator');
55
+
56
+ let selectedDevice: string | undefined;
57
+ let architectures: Architecture[] = ALL_ARCHITECTURES;
58
+
59
+ if (platform === PLATFORM.ANDROID) {
60
+ if (checkDevice) {
61
+ selectedDevice = await argv.getArgumentOrResolve('device_id', () => {
62
+ console.log('Detecting Connected Devices...');
63
+ return getDeviceChoice(platform);
64
+ });
65
+ architectures = [await getArchitectureForAndroidDevice(selectedDevice)];
66
+ } else {
67
+ architectures = getAllArchitecturesForAndroid();
68
+ }
69
+ }
70
+
71
+ const bazelArgs = resolveBazelBuildArgs(
72
+ platform,
73
+ argv.getArgument('build_config'),
74
+ architectures,
75
+ forDevice,
76
+ argv.getArgument('enable_runtime_logs'),
77
+ argv.getArgument('enable_runtime_traces'),
78
+ argv.getArgument('bazel_args'),
79
+ );
80
+
81
+ // Application Selection
82
+ // ---------------------
83
+ const application = await argv.getArgumentOrResolve('application', () => {
84
+ console.log('No application specified querying available targets...');
85
+ return selectBazelTarget(
86
+ bazel,
87
+ getApplicationTargetTagForPlatform(platform),
88
+ 'valdi_application',
89
+ 'Please select an application target to install:',
90
+ );
91
+ });
92
+
93
+ return {
94
+ platform: platform,
95
+ application: application,
96
+ bazelArgs: bazelArgs,
97
+ selectedDevice: selectedDevice,
98
+ };
99
+ }
@@ -0,0 +1,3 @@
1
+ export function byString<T>(selector: (v: T) => string): (l: T, r: T) => number {
2
+ return (l, r) => selector(l).localeCompare(selector(r));
3
+ }
@@ -0,0 +1,112 @@
1
+ import type { StdioOptions } from 'child_process';
2
+ import { exec, execSync, spawn } from 'child_process';
3
+ import inquirer from 'inquirer';
4
+ import type Separator from 'inquirer/lib/objects/separator';
5
+
6
+ export type CommandResult = { returnCode: number; stdout: string; stderr: string };
7
+ export type CliChoice<T> = { name: string; value: T };
8
+
9
+ export function runCliCommand(command: string, cwd?: string, rejectOnFailure?: boolean): Promise<CommandResult> {
10
+ return new Promise((resolve, reject) => {
11
+ exec(command, { cwd: cwd, shell: getShell() }, (error, stdout, stderr) => {
12
+ const returnCode = error ? (error.code ?? 1) : 0;
13
+ if (returnCode !== 0 && rejectOnFailure) {
14
+ reject(new Error(stderr.trim()));
15
+ } else {
16
+ resolve({ returnCode, stdout, stderr });
17
+ }
18
+ });
19
+ });
20
+ }
21
+
22
+ export function spawnCliCommand(
23
+ command: string,
24
+ cwd: string | undefined,
25
+ stdioMode: StdioOptions,
26
+ quiet: boolean,
27
+ rejectOnFailure: boolean,
28
+ ): Promise<CommandResult> {
29
+ return new Promise((resolve, reject) => {
30
+ const child = spawn(command, {
31
+ stdio: stdioMode,
32
+ shell: getShell(),
33
+ cwd: cwd,
34
+ env: { ...process.env, FORCE_COLOR: '1' },
35
+ });
36
+
37
+ // When using mode = 'inherit', the following output and error capture is a no-op
38
+
39
+ let stdout = '';
40
+ let stderr = '';
41
+
42
+ child.stdout?.on('data', (data: Buffer) => {
43
+ stdout += data.toString();
44
+ if (!quiet) {
45
+ process.stdout.write(stdout);
46
+ }
47
+ });
48
+
49
+ child.stderr?.on('data', (data: Buffer) => {
50
+ stderr += data.toString();
51
+ if (!quiet) {
52
+ process.stderr.write(stderr);
53
+ }
54
+ });
55
+
56
+ child.on('close', code => {
57
+ if (code !== 0 && rejectOnFailure) {
58
+ reject(new Error(stderr.trim()));
59
+ } else {
60
+ resolve({ returnCode: code ?? 0, stdout, stderr });
61
+ }
62
+ });
63
+
64
+ child.on('error', err => {
65
+ reject(err);
66
+ });
67
+ });
68
+ }
69
+
70
+ export async function getUserChoice<T>(
71
+ choices: Array<CliChoice<T> | Separator>,
72
+ promptMessage?: string,
73
+ maxChoices?: number,
74
+ ): Promise<T> {
75
+ const answers = await inquirer.prompt<{ selectedChoice: T }>([
76
+ {
77
+ type: 'list',
78
+ name: 'selectedChoice',
79
+ message: promptMessage ?? 'Please select an option:',
80
+ choices: choices,
81
+ loop: false,
82
+ pageSize: maxChoices ?? 10,
83
+ },
84
+ ]);
85
+
86
+ return answers.selectedChoice;
87
+ }
88
+
89
+ export async function getUserConfirmation(promptMessage?: string, defaultConfirm: boolean = false): Promise<boolean> {
90
+ const answer = await inquirer.prompt<{ confirm: boolean }>([
91
+ { type: 'confirm', name: 'confirm', message: promptMessage ?? 'Are you sure?', default: defaultConfirm },
92
+ ]);
93
+
94
+ return answer.confirm;
95
+ }
96
+
97
+ export function getScriptDirectory(): string {
98
+ return '';
99
+ }
100
+
101
+ function getShell(): string {
102
+ return process.env['SHELL'] ?? '/bin/bash';
103
+ }
104
+
105
+ export function checkCommandExists(command: string): boolean {
106
+ try {
107
+ execSync(`command -v ${command}`, { stdio: 'ignore' });
108
+ return true;
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
@@ -0,0 +1,30 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { globSync } from 'glob';
4
+ import { ANSI_COLORS } from '../core/constants';
5
+ import type { Replacements } from './fileUtils';
6
+ import { copyFileWithReplacement, copyFiles, processReplacements } from './fileUtils';
7
+ import { wrapInColor } from './logUtils';
8
+
9
+ export function copyBootstrapFiles(from: string, to: string, replacements: Replacements) {
10
+ copyFiles(from, to);
11
+
12
+ const keys = Object.keys(replacements);
13
+
14
+ const filenamesToReplace = globSync(keys.map(key => `**/{{${key}}}`));
15
+
16
+ for (const filename of filenamesToReplace) {
17
+ fs.renameSync(filename, processReplacements(filename, replacements));
18
+ }
19
+
20
+ const templateFiles = globSync(`${to}/**/*.template`);
21
+ templateFiles.forEach(templateFile => {
22
+ const parsedPath = path.parse(templateFile);
23
+ console.log(
24
+ wrapInColor(`Updating template file ${parsedPath.name} in ${parsedPath.dir}...`, ANSI_COLORS.YELLOW_COLOR),
25
+ );
26
+ const templateFileWithoutSuffix = templateFile.replace(/.template$/, '');
27
+ fs.renameSync(templateFile, templateFileWithoutSuffix);
28
+ copyFileWithReplacement(templateFileWithoutSuffix, templateFileWithoutSuffix, replacements);
29
+ });
30
+ }