forked from firebase/firebase-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk.ts
More file actions
494 lines (467 loc) · 16.3 KB
/
sdk.ts
File metadata and controls
494 lines (467 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import * as yaml from "yaml";
import * as clc from "colorette";
import * as path from "path";
const cwd = process.cwd();
import { checkbox, select } from "../../../prompt";
import { Config } from "../../../config";
import { Setup } from "../..";
import { loadAll } from "../../../dataconnect/load";
import {
AdminNodeSDK,
ConnectorInfo,
ConnectorYaml,
DartSDK,
JavascriptSDK,
KotlinSDK,
SwiftSDK,
} from "../../../dataconnect/types";
import * as experiments from "../../../experiments";
import { FirebaseError } from "../../../error";
import { isArray } from "lodash";
import {
logBullet,
envOverride,
logWarning,
logLabeledSuccess,
logLabeledWarning,
logLabeledBullet,
newUniqueId,
logLabeledError,
commandExistsSync,
} from "../../../utils";
import { detectApps, appDescription, Platform, App, Framework } from "../../../appUtils";
import { DataConnectEmulator } from "../../../emulator/dataconnectEmulator";
import { getGlobalDefaultAccount } from "../../../auth";
import { createFlutterApp, createNextApp, createReactApp } from "./create_app";
import { trackGA4 } from "../../../track";
import { dirExistsSync, listFiles } from "../../../fsutils";
import { isBillingEnabled } from "../../../gcp/cloudbilling";
import { Source } from ".";
export const FDC_APP_FOLDER = "FDC_APP_FOLDER";
export const FDC_SDK_FRAMEWORKS_ENV = "FDC_SDK_FRAMEWORKS";
export const FDC_SDK_PLATFORM_ENV = "FDC_SDK_PLATFORM";
export interface SdkRequiredInfo {
apps: App[];
}
export type SDKInfo = {
connectorYamlContents: string;
connectorInfo: ConnectorInfo;
displayIOSWarning: boolean;
};
export async function askQuestions(setup: Setup): Promise<void> {
const info: SdkRequiredInfo = {
apps: [],
};
info.apps = await chooseApp();
if (!info.apps.length) {
const npxMissingWarning = commandExistsSync("npx")
? ""
: clc.yellow(" (you need to install Node.js first)");
const flutterMissingWarning = commandExistsSync("flutter")
? ""
: clc.yellow(" (you need to install Flutter first)");
const choice = await select({
message: `Do you want to create an app template?`,
choices: [
// TODO: Create template tailored to FDC.
{ name: `React${npxMissingWarning}`, value: "react" },
{ name: `Next.JS${npxMissingWarning}`, value: "next" },
{ name: `Flutter${flutterMissingWarning}`, value: "flutter" },
{ name: "skip", value: "skip" },
],
});
try {
switch (choice) {
case "react":
await createReactApp(newUniqueId("web-app", listFiles(cwd)));
break;
case "next":
await createNextApp(newUniqueId("web-app", listFiles(cwd)));
break;
case "flutter":
await createFlutterApp(newUniqueId("flutter_app", listFiles(cwd)));
break;
case "skip":
break;
}
} catch (err: unknown) {
// The detailed error message are already piped into stderr. No need to repeat here.
logLabeledError("dataconnect", `Failed to create a ${choice} app template`);
}
}
setup.featureInfo = setup.featureInfo || {};
setup.featureInfo.dataconnectSdk = info;
}
export async function chooseApp(): Promise<App[]> {
let apps = dedupeAppsByPlatformAndDirectory(await detectApps(cwd));
if (apps.length) {
logLabeledSuccess(
"dataconnect",
`Detected existing apps ${apps.map((a) => appDescription(a)).join(", ")}`,
);
} else {
logLabeledWarning("dataconnect", "Cannot detect an existing app in the current directory.");
}
// Check for environment variables override.
const envAppFolder = envOverride(FDC_APP_FOLDER, "");
const envPlatform: Platform = envOverride(FDC_SDK_PLATFORM_ENV, "") as Platform;
const envFrameworks: Framework[] = envOverride(FDC_SDK_FRAMEWORKS_ENV, "")
.split(",")
.filter((f) => !!f)
.map((f) => f as Framework);
if (envAppFolder && envPlatform) {
// Resolve the relative path to the app directory
const envAppRelDir = path.relative(cwd, path.resolve(cwd, envAppFolder));
const matchedApps = apps.filter(
(app) => app.directory === envAppRelDir && (!app.platform || app.platform === envPlatform),
);
if (matchedApps.length) {
for (const a of matchedApps) {
a.frameworks = [...(a.frameworks || []), ...envFrameworks];
}
return matchedApps;
}
return [
{
platform: envPlatform,
directory: envAppRelDir,
frameworks: envFrameworks,
},
];
}
if (apps.length >= 2) {
const choices = apps.map((a) => {
return {
name: appDescription(a),
value: a,
checked: a.directory === ".",
};
});
const pickedApps = await checkbox<App>({
message: "Which apps do you want to set up Data Connect SDKs in?",
choices,
validate: (choices) => {
if (choices.length === 0) {
return "Please choose at least one app.";
}
return true;
},
});
if (!pickedApps || !pickedApps.length) {
throw new FirebaseError("Command Aborted. Please choose at least one app.");
}
apps = pickedApps;
}
return apps;
}
export async function actuate(setup: Setup, config: Config) {
const sdkInfo = setup.featureInfo?.dataconnectSdk;
if (!sdkInfo) {
throw new Error("Data Connect SDK feature RequiredInfo is not provided");
}
const startTime = Date.now();
try {
await actuateWithInfo(setup, config, sdkInfo);
} finally {
// If `firebase init dataconnect:sdk` is run alone, emit GA stats.
// Otherwise, `firebase init dataconnect` will emit those stats.
const fdcInfo = setup.featureInfo?.dataconnect;
if (!fdcInfo) {
const source: Source = setup.featureInfo?.dataconnectSource || "init_sdk";
void trackGA4(
"dataconnect_init",
{
source,
project_status: setup.projectId
? (await isBillingEnabled(setup))
? "blaze"
: "spark"
: "missing",
...initAppCounters(sdkInfo),
},
Date.now() - startTime,
);
}
}
}
export function initAppCounters(info: SdkRequiredInfo): { [key: string]: number } {
const counts = {
num_web_apps: 0,
num_android_apps: 0,
num_ios_apps: 0,
num_flutter_apps: 0,
num_admin_node_apps: 0,
};
for (const app of info.apps ?? []) {
switch (app.platform) {
case Platform.ADMIN_NODE:
counts.num_admin_node_apps++;
break;
case Platform.WEB:
counts.num_web_apps++;
break;
case Platform.ANDROID:
counts.num_android_apps++;
break;
case Platform.IOS:
counts.num_ios_apps++;
break;
case Platform.FLUTTER:
counts.num_flutter_apps++;
break;
}
}
return counts;
}
async function actuateWithInfo(setup: Setup, config: Config, info: SdkRequiredInfo) {
if (!info.apps.length) {
// If no apps is specified, try to detect it again.
// In `firebase init dataconnect:sdk`, customer may create the app while the command is running.
// The `firebase_init` MCP tool always pass an empty `apps` list, it should setup all apps detected.
info.apps = await detectApps(cwd);
if (!info.apps.length) {
logLabeledBullet("dataconnect", "No apps to setup Data Connect Generated SDKs");
return;
}
}
// detectApps creates unique apps by appId and bundleId, but this method operates
// on platform, directory, and frameworks alone. Deduping here to retain the
// same behavior
const apps = dedupeAppsByPlatformAndDirectory(info.apps);
const connectorInfo = await chooseExistingConnector(setup, config);
const connectorYaml = JSON.parse(JSON.stringify(connectorInfo.connectorYaml)) as ConnectorYaml;
for (const app of apps) {
if (!dirExistsSync(app.directory)) {
logLabeledWarning("dataconnect", `App directory ${app.directory} does not exist`);
}
addSdkGenerateToConnectorYaml(connectorInfo, connectorYaml, app);
}
// TODO: Prompt user about adding generated paths to .gitignore
const connectorYamlContents = yaml.stringify(connectorYaml);
connectorInfo.connectorYaml = connectorYaml;
const connectorYamlPath = `${connectorInfo.directory}/connector.yaml`;
config.writeProjectFile(
path.relative(config.projectDir, connectorYamlPath),
connectorYamlContents,
);
logLabeledBullet("dataconnect", `Installing the generated SDKs ...`);
const account = getGlobalDefaultAccount();
try {
await DataConnectEmulator.generate({
configDir: connectorInfo.directory,
account,
});
} catch (e: any) {
logLabeledError("dataconnect", `Failed to generate Data Connect SDKs\n${e?.message}`);
}
logLabeledSuccess(
"dataconnect",
`Installed generated SDKs for ${clc.bold(apps.map((a) => appDescription(a)).join(", "))}`,
);
if (apps.some((a) => a.platform === Platform.IOS)) {
logBullet(
clc.bold(
"Please follow the instructions here to add your generated sdk to your XCode project:\n\thttps://firebase.google.com/docs/data-connect/ios-sdk#set-client",
),
);
}
if (apps.some((a) => a.frameworks?.includes(Framework.REACT))) {
logBullet(
"Visit https://firebase.google.com/docs/data-connect/web-sdk#react for more information on how to set up React Generated SDKs for Firebase Data Connect",
);
}
if (apps.some((a) => a.frameworks?.includes(Framework.ANGULAR))) {
logBullet(
"Run `ng add @angular/fire` to install angular sdk dependencies.\nVisit https://github.com/invertase/tanstack-query-firebase/tree/main/packages/angular for more information on how to set up Angular Generated SDKs for Firebase Data Connect",
);
}
}
interface connectorChoice {
name: string; // {location}/{serviceId}/{connectorId}
value: ConnectorInfo;
}
/**
* Picks an existing connector from those present in the local workspace.
*
* Firebase Console can provide `FDC_CONNECTOR` environment variable.
* If its is present, chooseExistingConnector try to match it with any existing connectors
* and short-circuit the prompt.
*
* `FDC_CONNECTOR` should have the same `<location>/<serviceId>/<connectorId>`.
* @param choices
*/
async function chooseExistingConnector(setup: Setup, config: Config): Promise<ConnectorInfo> {
const serviceInfos = await loadAll(setup.projectId || "", config);
const choices: connectorChoice[] = serviceInfos
.map((si) => {
return si.connectorInfo.map((ci) => {
return {
name: `${si.dataConnectYaml.location}/${si.dataConnectYaml.serviceId}/${ci.connectorYaml.connectorId}`,
value: ci,
};
});
})
.flat();
if (!choices.length) {
throw new FirebaseError(
`No Firebase Data Connect workspace found. Run ${clc.bold("firebase init dataconnect")} to set up a service and connector.`,
);
}
if (choices.length === 1) {
// Only one connector available, use it.
return choices[0].value;
}
const connectorEnvVar = envOverride("FDC_CONNECTOR", "");
if (connectorEnvVar) {
const existingConnector = choices.find((c) => c.name === connectorEnvVar);
if (existingConnector) {
logBullet(`Picking up the existing connector ${clc.bold(connectorEnvVar)}.`);
return existingConnector.value;
}
logWarning(
`Unable to pick up an existing connector based on FDC_CONNECTOR=${connectorEnvVar}.`,
);
}
logWarning(
`Pick up the first connector ${clc.bold(connectorEnvVar)}. Use FDC_CONNECTOR to override it`,
);
return choices[0].value;
}
/** add SDK generation configuration to connector.yaml in place */
export function addSdkGenerateToConnectorYaml(
connectorInfo: ConnectorInfo,
connectorYaml: ConnectorYaml,
app: App,
): void {
const connectorDir = connectorInfo.directory;
const appDir = app.directory;
if (!connectorYaml.generate) {
connectorYaml.generate = {};
}
const generate = connectorYaml.generate;
switch (app.platform) {
case Platform.ADMIN_NODE: {
const adminNodeSdk: AdminNodeSDK = {
outputDir: path.relative(
connectorDir,
path.join(appDir, `src/dataconnect-admin-generated`),
),
package: `@dataconnect/admin-generated`,
packageJsonDir: path.relative(connectorDir, appDir),
};
if (!isArray(generate?.adminNodeSdk)) {
generate.adminNodeSdk = generate.adminNodeSdk ? [generate.adminNodeSdk] : [];
}
if (!generate.adminNodeSdk.some((s) => s.outputDir === adminNodeSdk.outputDir)) {
generate.adminNodeSdk.push(adminNodeSdk);
}
break;
}
case Platform.WEB: {
const javascriptSdk: JavascriptSDK = {
outputDir: path.relative(
connectorDir,
path.join(app.directory, "src/dataconnect-generated"),
),
package: "@dataconnect/generated",
packageJsonDir: path.relative(connectorDir, app.directory),
react: app.frameworks?.includes(Framework.REACT) ?? false,
angular: app.frameworks?.includes(Framework.ANGULAR) ?? false,
};
if (experiments.isEnabled("fdcrealtime")) {
javascriptSdk.clientCache = {};
}
if (!isArray(generate?.javascriptSdk)) {
generate.javascriptSdk = generate.javascriptSdk ? [generate.javascriptSdk] : [];
}
const existing = generate.javascriptSdk.find((s) => s.outputDir === javascriptSdk.outputDir);
if (!existing) {
generate.javascriptSdk.push(javascriptSdk);
}
break;
}
case Platform.FLUTTER: {
const dartSdk: DartSDK = {
outputDir: path.relative(connectorDir, path.join(appDir, `lib/dataconnect_generated`)),
package: "dataconnect_generated/generated.dart",
};
if (experiments.isEnabled("fdcrealtime")) {
dartSdk.clientCache = {};
}
if (!isArray(generate?.dartSdk)) {
generate.dartSdk = generate.dartSdk ? [generate.dartSdk] : [];
}
const existing = generate.dartSdk.find((s) => s.outputDir === dartSdk.outputDir);
if (!existing) {
generate.dartSdk.push(dartSdk);
}
break;
}
case Platform.ANDROID: {
const kotlinSdk: KotlinSDK = {
outputDir: path.relative(connectorDir, path.join(app.directory, "src/main/kotlin")),
package: `com.google.firebase.dataconnect.generated`,
};
if (experiments.isEnabled("fdcrealtime")) {
kotlinSdk.clientCache = {};
}
if (!isArray(generate?.kotlinSdk)) {
generate.kotlinSdk = generate.kotlinSdk ? [generate.kotlinSdk] : [];
}
const existing = generate.kotlinSdk.find((s) => s.outputDir === kotlinSdk.outputDir);
if (!existing) {
generate.kotlinSdk.push(kotlinSdk);
}
break;
}
case Platform.IOS: {
const swiftSdk: SwiftSDK = {
outputDir: path.relative(
connectorDir,
path.join(app.directory, `../FirebaseDataConnectGenerated`),
),
package: "DataConnectGenerated",
};
if (experiments.isEnabled("fdcrealtime")) {
swiftSdk.clientCache = {};
}
if (!isArray(generate?.swiftSdk)) {
generate.swiftSdk = generate.swiftSdk ? [generate.swiftSdk] : [];
}
const existing = generate.swiftSdk.find((s) => s.outputDir === swiftSdk.outputDir);
if (!existing) {
generate.swiftSdk.push(swiftSdk);
}
break;
}
default:
throw new FirebaseError(
`Unsupported platform ${app.platform} for Data Connect SDK generation. Supported platforms are: ${Object.values(
Platform,
).join(", ")}\n${JSON.stringify(app)}`,
);
}
}
function dedupeAppsByPlatformAndDirectory(apps: App[]): App[] {
// detectApps creates unique apps by appId and bundleId, but this method operates
// on platform, directory, and frameworks alone. Deduping here to retain the
// same behavior
const uniqueApps = new Map<string, App>();
for (const app of apps) {
// Sorting frameworks for consistent key generation
const frameworkKey = app.frameworks ? [...app.frameworks].sort().join(",") : "";
const key = `${app.platform}:${app.directory}:${frameworkKey}`;
if (!uniqueApps.has(key)) {
const minifiedApp: App = {
platform: app.platform,
directory: app.directory,
};
if (app.frameworks?.length) {
minifiedApp.frameworks = [...app.frameworks];
}
// Create a new object with only the desired properties to avoid carrying over others like appId
uniqueApps.set(key, minifiedApp);
}
}
return Array.from(uniqueApps.values());
}