firebase-tools-with-isolate 15.31.0 → 15.33.0

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 (62) hide show
  1. package/lib/accountImporter.js +6 -3
  2. package/lib/api.js +3 -3
  3. package/lib/apphosting/secrets/index.js +7 -2
  4. package/lib/command.js +1 -1
  5. package/lib/commands/apps-create.js +34 -3
  6. package/lib/commands/auth-import.js +5 -6
  7. package/lib/commands/functions-kits-uninstall.js +43 -21
  8. package/lib/commands/functions-lifecycle-list.js +5 -6
  9. package/lib/commands/hosting-channel-deploy.js +3 -3
  10. package/lib/commands/hosting-clone.js +60 -29
  11. package/lib/commands/hosting-disable.js +5 -1
  12. package/lib/config.js +1 -0
  13. package/lib/crashlytics/alerts.js +122 -0
  14. package/lib/crashlytics/onboarding.js +71 -3
  15. package/lib/crashlytics/sourcemap.js +46 -11
  16. package/lib/crashlytics/types.js +6 -1
  17. package/lib/database/import.js +6 -7
  18. package/lib/deploy/functions/build.js +3 -0
  19. package/lib/deploy/functions/cel.js +89 -58
  20. package/lib/deploy/functions/functionsDeployHelper.js +10 -0
  21. package/lib/deploy/functions/params.js +7 -4
  22. package/lib/deploy/functions/prepare.js +25 -8
  23. package/lib/deploy/functions/release/fabricator.js +1 -5
  24. package/lib/deploy/functions/release/planner.js +3 -2
  25. package/lib/deploy/functions/validate.js +16 -0
  26. package/lib/deploy/hosting/prepare.js +1 -1
  27. package/lib/deploy/hosting/release.js +2 -2
  28. package/lib/emulator/auth/operations.js +8 -4
  29. package/lib/emulator/databaseEmulator.js +7 -3
  30. package/lib/emulator/downloadableEmulatorInfo.json +24 -24
  31. package/lib/emulator/emulatorLogger.js +2 -1
  32. package/lib/emulator/functionsEmulatorRuntime.js +2 -1
  33. package/lib/experiments.js +23 -6
  34. package/lib/extensions/warnings.js +48 -7
  35. package/lib/frameworks/next/constants.js +20 -12
  36. package/lib/frameworks/next/index.js +4 -25
  37. package/lib/frameworks/next/utils.js +28 -0
  38. package/lib/functions/env.js +4 -2
  39. package/lib/functions/kits/install.js +17 -1
  40. package/lib/gcp/artifactregistry.js +20 -0
  41. package/lib/gcp/cloudmonitoring.js +80 -3
  42. package/lib/gcp/cloudtasks.js +15 -1
  43. package/lib/gcp/cloudtrace.js +38 -0
  44. package/lib/gcp/resourceManager.js +1 -1
  45. package/lib/gcp/run.js +5 -0
  46. package/lib/gcp/runv2.js +32 -11
  47. package/lib/hosting/api.js +15 -15
  48. package/lib/hosting/runTags.js +1 -1
  49. package/lib/init/features/auth.js +46 -8
  50. package/lib/init/features/hosting/index.js +4 -2
  51. package/lib/management/apps.js +4 -2
  52. package/lib/management/projects.js +1 -1
  53. package/lib/mcp/tools/firestore/converter.js +2 -2
  54. package/lib/mcp/util.js +11 -10
  55. package/lib/profileReport.js +4 -4
  56. package/lib/scopes.js +1 -3
  57. package/lib/streamJson.js +37 -0
  58. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  59. package/lib/utils.js +0 -15
  60. package/package.json +11 -10
  61. package/schema/firebase-config.json +41 -0
  62. package/lib/firestore/checkDatabaseType.js +0 -24
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NOTIFICATION_CHANNELS_MASK_PATH = exports.EMAIL_CHANNEL_TYPE = exports.FIREBASE_EMAIL_CHANNEL_DISPLAY_NAME_SUFFIX = exports.FIREBASE_CHANNEL_LABEL = void 0;
4
+ exports.generateAlertPolicy = generateAlertPolicy;
5
+ exports.fetchFirebaseEmailChannel = fetchFirebaseEmailChannel;
6
+ exports.createEmailChannel = createEmailChannel;
7
+ exports.resolveEmailNotificationChannel = resolveEmailNotificationChannel;
8
+ exports.addChannelToPolicy = addChannelToPolicy;
9
+ exports.enableAlert = enableAlert;
10
+ exports.enableAlerts = enableAlerts;
11
+ const error_1 = require("../error");
12
+ const cloudmonitoring_1 = require("../gcp/cloudmonitoring");
13
+ const logger_1 = require("../logger");
14
+ const utils_1 = require("./utils");
15
+ exports.FIREBASE_CHANNEL_LABEL = "is_firebase_channel";
16
+ exports.FIREBASE_EMAIL_CHANNEL_DISPLAY_NAME_SUFFIX = " - for Firebase alerts";
17
+ exports.EMAIL_CHANNEL_TYPE = "email";
18
+ exports.NOTIFICATION_CHANNELS_MASK_PATH = "notification_channels";
19
+ async function generateAlertPolicy(projectId, appId, alertType) {
20
+ logger_1.logger.debug(`[crashlytics] generateAlertPolicy called with projectId: ${projectId}, appId: ${appId}, alertType: ${alertType}`);
21
+ try {
22
+ const response = await utils_1.CRASHLYTICS_API_CLIENT.request({
23
+ method: "POST",
24
+ headers: {
25
+ "Content-Type": "application/json",
26
+ },
27
+ path: `/projects/${projectId}/apps/${appId}:generateAlertPolicy`,
28
+ body: { alertType },
29
+ timeout: utils_1.TIMEOUT,
30
+ });
31
+ return response.body.alertPolicy;
32
+ }
33
+ catch (err) {
34
+ const status = (0, error_1.getErrStatus)(err);
35
+ const msg = (0, error_1.getErrMsg)(err);
36
+ throw new error_1.FirebaseError(`Failed to generate Crashlytics alert policy for ${alertType} on app ${appId} (status ${status}): ${msg}`, { original: (0, error_1.getError)(err), status });
37
+ }
38
+ }
39
+ async function fetchFirebaseEmailChannel(projectId, userEmail) {
40
+ const escapedEmail = userEmail.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
41
+ const filter = `type = "${exports.EMAIL_CHANNEL_TYPE}" AND ` +
42
+ `labels.email_address = "${escapedEmail}" AND ` +
43
+ `user_labels.${exports.FIREBASE_CHANNEL_LABEL} = "true"`;
44
+ const channels = await (0, cloudmonitoring_1.listNotificationChannels)(projectId, filter);
45
+ return channels[0];
46
+ }
47
+ async function createEmailChannel(projectId, userEmail) {
48
+ return await (0, cloudmonitoring_1.createNotificationChannel)(projectId, {
49
+ type: exports.EMAIL_CHANNEL_TYPE,
50
+ displayName: `${userEmail}${exports.FIREBASE_EMAIL_CHANNEL_DISPLAY_NAME_SUFFIX}`,
51
+ labels: {
52
+ email_address: userEmail,
53
+ },
54
+ userLabels: {
55
+ [exports.FIREBASE_CHANNEL_LABEL]: "true",
56
+ },
57
+ });
58
+ }
59
+ async function resolveEmailNotificationChannel(projectId, userEmail) {
60
+ const existingChannel = await fetchFirebaseEmailChannel(projectId, userEmail);
61
+ return existingChannel ?? (await createEmailChannel(projectId, userEmail));
62
+ }
63
+ function addChannelToPolicy(policy, channelName) {
64
+ const currentChannels = policy.notificationChannels ?? [];
65
+ if (currentChannels.includes(channelName)) {
66
+ return policy;
67
+ }
68
+ return {
69
+ ...policy,
70
+ notificationChannels: [...currentChannels, channelName],
71
+ };
72
+ }
73
+ async function enableAlert(projectId, appId, alertType, target) {
74
+ let channel;
75
+ if (!target.channelName && target.userEmail) {
76
+ channel = await resolveEmailNotificationChannel(projectId, target.userEmail);
77
+ }
78
+ else if (!target.channelName) {
79
+ throw new error_1.FirebaseError("Either channelName or userEmail must be specified to enable a Crashlytics alert.", { exit: 1 });
80
+ }
81
+ const channelName = target.channelName ?? channel?.name;
82
+ if (!channelName) {
83
+ throw new error_1.FirebaseError("Resolved notification channel is missing a resource name.", {
84
+ exit: 1,
85
+ });
86
+ }
87
+ const policyResourceName = await generateAlertPolicy(projectId, appId, alertType);
88
+ const targetPolicy = await (0, cloudmonitoring_1.getAlertPolicy)(policyResourceName);
89
+ const policyWithChannel = addChannelToPolicy(targetPolicy, channelName);
90
+ const updatedPolicy = policyWithChannel === targetPolicy
91
+ ? targetPolicy
92
+ : await (0, cloudmonitoring_1.updateAlertPolicy)(policyWithChannel, exports.NOTIFICATION_CHANNELS_MASK_PATH);
93
+ return { channel, policy: updatedPolicy };
94
+ }
95
+ async function enableAlerts(projectId, appId, alertTypes, userEmail) {
96
+ if (alertTypes.length === 0) {
97
+ return [];
98
+ }
99
+ const channel = await resolveEmailNotificationChannel(projectId, userEmail);
100
+ const channelName = channel.name;
101
+ if (!channelName) {
102
+ throw new error_1.FirebaseError("Notification channel for Crashlytics alerts is missing a name.", {
103
+ exit: 1,
104
+ });
105
+ }
106
+ const results = await Promise.allSettled(alertTypes.map(async (alertType) => {
107
+ const { policy } = await enableAlert(projectId, appId, alertType, {
108
+ channelName,
109
+ });
110
+ return policy;
111
+ }));
112
+ const policies = [];
113
+ for (const res of results) {
114
+ if (res.status === "fulfilled") {
115
+ policies.push(res.value);
116
+ }
117
+ else {
118
+ logger_1.logger.debug(`[crashlytics] Failed to enable alert: ${(0, error_1.getErrMsg)(res.reason)}`);
119
+ }
120
+ }
121
+ return policies;
122
+ }
@@ -4,16 +4,35 @@ exports.CRASHLYTICS_TELEMETRY_SERVICE = exports.CRASHLYTICS_TELEMETRY_RESOURCE_T
4
4
  exports.onboardCrashlyticsWeb = onboardCrashlyticsWeb;
5
5
  const ensureApiEnabled_1 = require("../ensureApiEnabled");
6
6
  const error_1 = require("../error");
7
+ const experiments = require("../experiments");
7
8
  const cloudbilling_1 = require("../gcp/cloudbilling");
8
9
  const cloudlogging_1 = require("../gcp/cloudlogging");
10
+ const alerts_1 = require("./alerts");
9
11
  const firebasetelemetry_1 = require("./firebasetelemetry");
12
+ const types_1 = require("./types");
10
13
  const utils_1 = require("../utils");
11
14
  const apikeys_1 = require("../gcp/apikeys");
15
+ const cloudtrace_1 = require("../gcp/cloudtrace");
12
16
  const apps_1 = require("../management/apps");
17
+ const logger_1 = require("../logger");
18
+ const prompt_1 = require("../prompt");
19
+ const requireAuth_1 = require("../requireAuth");
13
20
  exports.CRASHLYTICS_TELEMETRY_BUCKET_ID = "firebase-telemetry";
14
21
  exports.CRASHLYTICS_TELEMETRY_SINK_ID = "firebase-telemetry-routing";
15
22
  exports.CRASHLYTICS_TELEMETRY_RESOURCE_TYPE = "firebasetelemetry.googleapis.com/App";
16
23
  exports.CRASHLYTICS_TELEMETRY_SERVICE = "firebasetelemetry.googleapis.com";
24
+ async function resolveAuthenticatedUserEmail(options) {
25
+ if (options.user?.email) {
26
+ return options.user.email;
27
+ }
28
+ try {
29
+ return (await (0, requireAuth_1.requireAuth)(options)) ?? undefined;
30
+ }
31
+ catch (err) {
32
+ logger_1.logger.debug(`[crashlytics] Failed to resolve authenticated user email: ${(0, error_1.getErrMsg)(err)}`);
33
+ return undefined;
34
+ }
35
+ }
17
36
  async function onboardCrashlyticsWeb(projectId, appId, options = {}) {
18
37
  const billingEnabled = await (0, cloudbilling_1.checkBillingEnabled)(projectId);
19
38
  if (!billingEnabled && options.nonInteractive) {
@@ -24,10 +43,14 @@ async function onboardCrashlyticsWeb(projectId, appId, options = {}) {
24
43
  await (0, cloudbilling_1.enableBilling)(projectId, "Crashlytics");
25
44
  }
26
45
  (0, utils_1.logLabeledBullet)("crashlytics", "Enabling required telemetry APIs...");
27
- await Promise.all([
46
+ const requiredApis = [
28
47
  (0, ensureApiEnabled_1.ensure)(projectId, exports.CRASHLYTICS_TELEMETRY_SERVICE, "crashlytics", false),
29
48
  (0, ensureApiEnabled_1.ensure)(projectId, "firebasetelemetryadmin.googleapis.com", "crashlytics", false),
30
- ]);
49
+ ];
50
+ if (experiments.isEnabled("crashlyticsWebTrace")) {
51
+ requiredApis.push((0, ensureApiEnabled_1.ensure)(projectId, "cloudtrace.googleapis.com", "crashlytics", false));
52
+ }
53
+ await Promise.all(requiredApis);
31
54
  (0, utils_1.logLabeledSuccess)("crashlytics", "Telemetry APIs enabled.");
32
55
  const appConfig = await (0, apps_1.getAppConfig)(appId, apps_1.AppPlatform.WEB);
33
56
  if ("apiKey" in appConfig && appConfig.apiKey) {
@@ -55,8 +78,53 @@ async function onboardCrashlyticsWeb(projectId, appId, options = {}) {
55
78
  (0, utils_1.logLabeledBullet)("crashlytics", `Setting up Cloud Logging routing sink '${exports.CRASHLYTICS_TELEMETRY_SINK_ID}'...`);
56
79
  const sink = await (0, cloudlogging_1.createOrUpdateLogSink)(projectId, exports.CRASHLYTICS_TELEMETRY_SINK_ID, destination, filter);
57
80
  (0, utils_1.logLabeledSuccess)("crashlytics", "Cloud Logging routing sink configured.");
81
+ if (experiments.isEnabled("crashlyticsWebTrace")) {
82
+ (0, utils_1.logLabeledBullet)("crashlytics", "Provisioning Cloud Trace storage...");
83
+ try {
84
+ await (0, cloudtrace_1.provisionTraceStorage)(projectId);
85
+ (0, utils_1.logLabeledSuccess)("crashlytics", "Cloud Trace storage provisioned.");
86
+ }
87
+ catch (err) {
88
+ (0, utils_1.logLabeledWarning)("crashlytics", (0, error_1.getErrMsg)(err));
89
+ }
90
+ }
58
91
  (0, utils_1.logLabeledBullet)("crashlytics", "Configuring Crashlytics telemetry for web app...");
59
92
  const config = await (0, firebasetelemetry_1.createOrUpdateTelemetryConfig)(projectId, appId, `projects/${projectId}/locations/global/buckets/${exports.CRASHLYTICS_TELEMETRY_BUCKET_ID}`, 1);
60
93
  (0, utils_1.logLabeledSuccess)("crashlytics", "Crashlytics telemetry configured successfully.");
61
- return { bucket, sink, config };
94
+ if (!experiments.isEnabled("crashlyticsWebAlerts") || options.nonInteractive) {
95
+ return { bucket, sink, config };
96
+ }
97
+ const userEmail = await resolveAuthenticatedUserEmail(options);
98
+ if (!userEmail) {
99
+ (0, utils_1.logLabeledWarning)("crashlytics", "Unable to determine authenticated user email for alert setup. You can configure alerts later in the Firebase Console.");
100
+ return { bucket, sink, config };
101
+ }
102
+ const selectedAlerts = await (0, prompt_1.checkbox)({
103
+ message: "Which email alerts would you like to enable? (Optional)",
104
+ choices: [
105
+ {
106
+ name: "New issues (Notify when a new issue is detected)",
107
+ value: types_1.AlertType.ALERT_TYPE_NEW_ISSUE,
108
+ checked: true,
109
+ },
110
+ {
111
+ name: "Regressed issues (Notify when a closed issue reoccurs)",
112
+ value: types_1.AlertType.ALERT_TYPE_REGRESSED_ISSUE,
113
+ checked: true,
114
+ },
115
+ ],
116
+ });
117
+ if (selectedAlerts.length === 0) {
118
+ return { bucket, sink, config };
119
+ }
120
+ (0, utils_1.logLabeledBullet)("crashlytics", `Setting up Crashlytics email alerts for ${userEmail}...`);
121
+ try {
122
+ const alertPolicies = await (0, alerts_1.enableAlerts)(projectId, appId, selectedAlerts, userEmail);
123
+ (0, utils_1.logLabeledSuccess)("crashlytics", "Crashlytics email alerts configured successfully.");
124
+ return { bucket, sink, config, alertPolicies };
125
+ }
126
+ catch (err) {
127
+ (0, utils_1.logLabeledWarning)("crashlytics", (0, error_1.getErrMsg)(err));
128
+ return { bucket, sink, config };
129
+ }
62
130
  }
@@ -304,7 +304,7 @@ async function uploadMap(request, attemptsRemaining = 0) {
304
304
  const tmpArchive = await (0, archiveFile_1.archiveFile)(filePath, { archivedFileName: "mapping.js.map" });
305
305
  const appId = options.app || "";
306
306
  const gcsFile = `${appId}-${appVersion}-${normalizeFileName(obfuscatedPath)}.zip`;
307
- const uid = (0, utils_1.murmurHashV3)(`${appId}-${appVersion}-${obfuscatedPath}`);
307
+ const uid = (0, utils_1.murmurHashV3)(obfuscatedPath);
308
308
  const name = `projects/${projectId}/locations/global/mappingFiles/${uid}`;
309
309
  const stream = fs.createReadStream(tmpArchive);
310
310
  stream.on("error", (err) => {
@@ -316,15 +316,15 @@ async function uploadMap(request, attemptsRemaining = 0) {
316
316
  stream,
317
317
  }, bucketName);
318
318
  const fileUri = `gs://${bucket}/${object}`;
319
- logger_1.logger.debug(`Uploaded mapping file ${filePath} to ${fileUri}`);
319
+ logger_1.logger.debug(`Uploaded mapping file ${filePath} to GCS: ${fileUri}`);
320
320
  await registerSourceMap({
321
321
  name,
322
322
  appId,
323
323
  version: appVersion,
324
324
  obfuscatedFilePath: `/${obfuscatedPath}`,
325
325
  fileUri,
326
- });
327
- logger_1.logger.debug(`Registered mapping file ${filePath}`);
326
+ }, options);
327
+ logger_1.logger.debug(`Successfully registered source map in Firebase Telemetry for /${obfuscatedPath}`);
328
328
  return true;
329
329
  }
330
330
  catch (e) {
@@ -351,10 +351,45 @@ function isAlreadyExistsError(e) {
351
351
  return false;
352
352
  }
353
353
  const message = e.message.toLowerCase();
354
- const bodyMessage = (e.context?.body?.error?.message ?? "").toLowerCase();
354
+ const context = e.context;
355
+ const bodyMessage = (context?.body?.error?.message ?? "").toLowerCase();
355
356
  return message.includes("already exists") || bodyMessage.includes("already exists");
356
357
  }
357
- async function registerSourceMap(sourceMap) {
358
+ async function listAllMappingFiles(client, collectionPath) {
359
+ const cache = new Map();
360
+ let pageToken;
361
+ do {
362
+ const queryParams = {};
363
+ if (pageToken) {
364
+ queryParams.pageToken = pageToken;
365
+ }
366
+ const listResponse = await client.get(collectionPath, { queryParams });
367
+ for (const mappingFile of listResponse.body?.mappingFiles ?? []) {
368
+ if (mappingFile.obfuscatedFilePath && mappingFile.name) {
369
+ cache.set(mappingFile.obfuscatedFilePath, mappingFile.name);
370
+ }
371
+ }
372
+ pageToken = listResponse.body?.nextPageToken;
373
+ } while (pageToken);
374
+ return cache;
375
+ }
376
+ function getOrListAllMappingFiles(client, collectionPath, options) {
377
+ if (options) {
378
+ options.__mappingFilesCache ?? (options.__mappingFilesCache = listAllMappingFiles(client, collectionPath).catch((err) => {
379
+ delete options.__mappingFilesCache;
380
+ throw err;
381
+ }));
382
+ return options.__mappingFilesCache;
383
+ }
384
+ return listAllMappingFiles(client, collectionPath);
385
+ }
386
+ async function findExistingSourceMapName(client, sourceMap, options) {
387
+ const lastSlashIndex = sourceMap.name.lastIndexOf("/");
388
+ const collectionPath = lastSlashIndex === -1 ? sourceMap.name : sourceMap.name.slice(0, lastSlashIndex);
389
+ const cache = await getOrListAllMappingFiles(client, collectionPath, options);
390
+ return cache.get(sourceMap.obfuscatedFilePath);
391
+ }
392
+ async function registerSourceMap(sourceMap, options) {
358
393
  const client = new apiv2_1.Client({
359
394
  urlPrefix: "https://firebasetelemetryadmin.googleapis.com",
360
395
  auth: true,
@@ -362,7 +397,6 @@ async function registerSourceMap(sourceMap) {
362
397
  });
363
398
  const patchSourceMap = async () => {
364
399
  await client.patch(sourceMap.name, sourceMap, { queryParams: { allowMissing: "true" } });
365
- logger_1.logger.debug(`Registered source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry service`);
366
400
  };
367
401
  try {
368
402
  await patchSourceMap();
@@ -374,16 +408,17 @@ async function registerSourceMap(sourceMap) {
374
408
  }
375
409
  if (isAlreadyExistsError(e)) {
376
410
  try {
377
- logger_1.logger.debug(`Source map ${sourceMap.obfuscatedFilePath} already exists, deleting and re-registering`);
378
- await client.delete(sourceMap.name);
411
+ logger_1.logger.debug(`Source map ${sourceMap.obfuscatedFilePath} already exists, deleting and re-registering...`);
412
+ const existingName = (await findExistingSourceMapName(client, sourceMap, options)) ?? sourceMap.name;
413
+ await client.delete(existingName);
379
414
  await patchSourceMap();
380
415
  return;
381
416
  }
382
417
  catch (retryErr) {
383
- throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry service:\n${retryErr instanceof Error ? retryErr.message : String(retryErr)}`, { original: retryErr instanceof Error ? retryErr : undefined });
418
+ throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry:\n${retryErr instanceof Error ? retryErr.message : String(retryErr)}`, { original: retryErr instanceof Error ? retryErr : undefined });
384
419
  }
385
420
  }
386
421
  }
387
- throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry service:\n${e instanceof Error ? e.message : String(e)}`, { original: e instanceof Error ? e : undefined });
422
+ throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry:\n${e instanceof Error ? e.message : String(e)}`, { original: e instanceof Error ? e : undefined });
388
423
  }
389
424
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TimeGranularity = exports.ThreadState = exports.Signal = exports.State = exports.SessionEventType = exports.FormFactor = exports.TrackType = exports.ErrorType = void 0;
3
+ exports.AlertType = exports.TimeGranularity = exports.ThreadState = exports.Signal = exports.State = exports.SessionEventType = exports.FormFactor = exports.TrackType = exports.ErrorType = void 0;
4
4
  var ErrorType;
5
5
  (function (ErrorType) {
6
6
  ErrorType["ERROR_TYPE_UNSPECIFIED"] = "ERROR_TYPE_UNSPECIFIED";
@@ -65,3 +65,8 @@ var TimeGranularity;
65
65
  TimeGranularity["TIME_GRANULARITY_HOUR"] = "TIME_GRANULARITY_HOUR";
66
66
  TimeGranularity["TIME_GRANULARITY_DAY"] = "TIME_GRANULARITY_DAY";
67
67
  })(TimeGranularity || (exports.TimeGranularity = TimeGranularity = {}));
68
+ exports.AlertType = {
69
+ ALERT_TYPE_UNSPECIFIED: "ALERT_TYPE_UNSPECIFIED",
70
+ ALERT_TYPE_NEW_ISSUE: "ALERT_TYPE_NEW_ISSUE",
71
+ ALERT_TYPE_REGRESSED_ISSUE: "ALERT_TYPE_REGRESSED_ISSUE",
72
+ };
@@ -1,12 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const stream_chain_1 = require("stream-chain");
4
3
  const clc = require("colorette");
5
- const filter_js_1 = require("stream-json/filters/filter.js");
6
4
  const stream = require("stream");
7
- const stream_object_js_1 = require("stream-json/streamers/stream-object.js");
8
5
  const apiv2_1 = require("../apiv2");
9
6
  const error_1 = require("../error");
7
+ const streamJson_1 = require("../streamJson");
10
8
  const utils_1 = require("../utils");
11
9
  class BatchChunks extends stream.Transform {
12
10
  constructor(maxSize, opts) {
@@ -109,7 +107,8 @@ class DatabaseImporter {
109
107
  ", then rerun this command.", { exit: 2 });
110
108
  }
111
109
  }
112
- readAndWriteChunks() {
110
+ async readAndWriteChunks() {
111
+ const { chain, filter, streamObject } = await (0, streamJson_1.loadStreamJson)();
113
112
  const { dbUrl, payloadSize } = this;
114
113
  const chunkData = this.chunkData.bind(this);
115
114
  const doWriteBatch = this.doWriteBatch.bind(this);
@@ -132,13 +131,13 @@ class DatabaseImporter {
132
131
  };
133
132
  return new Promise((resolve, reject) => {
134
133
  const responses = [];
135
- const pipeline = (0, stream_chain_1.chain)([
134
+ const pipeline = chain([
136
135
  this.inStream,
137
- filter_js_1.filter.withParser({
136
+ filter.withParser({
138
137
  filter: this.computeFilterString(this.dataPath) || (() => true),
139
138
  pathSeparator: "/",
140
139
  }),
141
- (0, stream_object_js_1.streamObject)(),
140
+ streamObject(),
142
141
  ]);
143
142
  pipeline
144
143
  .on("error", (err) => reject(new error_1.FirebaseError(`Invalid data; couldn't parse JSON object, array, or value. ${err.message}`, {
@@ -94,6 +94,9 @@ async function resolveBackend(opts) {
94
94
  nonInteractive: opts.nonInteractive,
95
95
  isEmulator: opts.isEmulator,
96
96
  });
97
+ if (opts.resolveRegions) {
98
+ await opts.resolveRegions(opts.build, paramValues);
99
+ }
97
100
  return { backend: toBackend(opts.build, paramValues), envs: paramValues, secretRefs: secretRefs };
98
101
  }
99
102
  function envWithTypes(definedParams, rawEnvs) {
@@ -10,9 +10,10 @@ const CMP = /((?:!=)|(?:==)|(?:>=)|(?:<=)|>|<)/.source;
10
10
  const identityRegexp = /{{ params\.(\S+) }}/;
11
11
  const dualComparisonRegexp = new RegExp(/{{ params\.(\S+) CMP params\.(\S+) }}/.source.replace("CMP", CMP));
12
12
  const comparisonRegexp = new RegExp(/{{ params\.(\S+) CMP (.+) }}/.source.replace("CMP", CMP));
13
- const dualTernaryRegexp = new RegExp(/{{ params\.(\S+) CMP params\.(\S+) \? (.+) : (.+) }/.source.replace("CMP", CMP));
14
- const ternaryRegexp = new RegExp(/{{ params\.(\S+) CMP (.+) \? (.+) : (.+) }/.source.replace("CMP", CMP));
15
- const literalTernaryRegexp = /{{ params\.(\S+) \? (.+) : (.+) }/;
13
+ const EXPR_PREFIX = "{{ ";
14
+ const EXPR_SUFFIX = " }}";
15
+ const QUESTION_TOKEN = " ? ";
16
+ const COLON_TOKEN = " : ";
16
17
  function listEquals(a, b) {
17
18
  return a.every((item) => b.includes(item)) && b.every((item) => a.includes(item));
18
19
  }
@@ -28,36 +29,74 @@ function isComparisonExpression(value) {
28
29
  function isDualComparisonExpression(value) {
29
30
  return dualComparisonRegexp.test(value);
30
31
  }
31
- function isTernaryExpression(value) {
32
- return ternaryRegexp.test(value);
33
- }
34
- function isLiteralTernaryExpression(value) {
35
- return literalTernaryRegexp.test(value);
36
- }
37
- function isDualTernaryExpression(value) {
38
- return dualTernaryRegexp.test(value);
39
- }
40
32
  class ExprParseError extends error_1.FirebaseError {
41
33
  }
42
34
  exports.ExprParseError = ExprParseError;
35
+ function parseTernary(expr) {
36
+ if (!expr.startsWith(EXPR_PREFIX) || !expr.endsWith(EXPR_SUFFIX)) {
37
+ return undefined;
38
+ }
39
+ const body = expr.slice(EXPR_PREFIX.length, -EXPR_SUFFIX.length);
40
+ let inQuotes = false;
41
+ let depth = 0;
42
+ let question = -1;
43
+ let colon = -1;
44
+ for (let i = 0; i < body.length; i++) {
45
+ if (inQuotes && body[i] === "\\") {
46
+ i++;
47
+ continue;
48
+ }
49
+ if (body[i] === '"') {
50
+ inQuotes = !inQuotes;
51
+ continue;
52
+ }
53
+ if (inQuotes)
54
+ continue;
55
+ if (body.startsWith(QUESTION_TOKEN, i)) {
56
+ if (depth === 0) {
57
+ question = i;
58
+ }
59
+ depth++;
60
+ i += QUESTION_TOKEN.length - 1;
61
+ }
62
+ else if (body.startsWith(COLON_TOKEN, i)) {
63
+ if (depth > 0) {
64
+ depth--;
65
+ if (depth === 0) {
66
+ colon = i;
67
+ break;
68
+ }
69
+ }
70
+ i += COLON_TOKEN.length - 1;
71
+ }
72
+ }
73
+ if (question === -1) {
74
+ return undefined;
75
+ }
76
+ if (colon === -1) {
77
+ throw new ExprParseError(`Malformed CEL ternary expression '${expr}'`);
78
+ }
79
+ const condition = body.slice(0, question).trim();
80
+ const ifTrue = body.slice(question + QUESTION_TOKEN.length, colon).trim();
81
+ const ifFalse = body.slice(colon + COLON_TOKEN.length).trim();
82
+ if (!condition || !ifTrue || !ifFalse) {
83
+ throw new ExprParseError(`Malformed CEL ternary expression '${expr}'`);
84
+ }
85
+ return { condition, ifTrue, ifFalse };
86
+ }
43
87
  function resolveExpression(wantType, expr, params) {
44
88
  expr = preprocessLists(wantType, expr, params);
45
89
  if (isIdentityExpression(expr)) {
46
90
  return resolveIdentity(wantType, expr, params);
47
91
  }
48
- else if (isDualTernaryExpression(expr)) {
49
- return resolveDualTernary(wantType, expr, params);
50
- }
51
- else if (isLiteralTernaryExpression(expr)) {
52
- return resolveLiteralTernary(wantType, expr, params);
92
+ const ternary = parseTernary(expr);
93
+ if (ternary) {
94
+ return resolveTernary({ wantType, expr, parts: ternary, params });
53
95
  }
54
- else if (isTernaryExpression(expr)) {
55
- return resolveTernary(wantType, expr, params);
56
- }
57
- else if (isDualComparisonExpression(expr)) {
96
+ else if (wantType === "boolean" && isDualComparisonExpression(expr)) {
58
97
  return resolveDualComparison(expr, params);
59
98
  }
60
- else if (isComparisonExpression(expr)) {
99
+ else if (wantType === "boolean" && isComparisonExpression(expr)) {
61
100
  return resolveComparison(expr, params);
62
101
  }
63
102
  else {
@@ -261,53 +300,45 @@ function resolveDualComparison(expr, params) {
261
300
  throw new ExprParseError(`could not infer type of param ${lhsName} used in comparison operation`);
262
301
  }
263
302
  }
264
- function resolveTernary(wantType, expr, params) {
265
- const match = ternaryRegexp.exec(expr);
266
- if (!match) {
267
- throw new ExprParseError("malformed CEL ternary expression '" + expr + "'");
268
- }
269
- const comparisonExpr = `{{ params.${match[1]} ${match[2]} ${match[3]} }}`;
270
- const isTrue = resolveComparison(comparisonExpr, params);
271
- if (isTrue) {
272
- return resolveParamListOrLiteral(wantType, match[4], params);
273
- }
274
- else {
275
- return resolveParamListOrLiteral(wantType, match[5], params);
276
- }
303
+ function resolveTernary(options) {
304
+ const { wantType, expr, parts, params } = options;
305
+ const isTrue = resolveTernaryCondition(expr, parts.condition, params);
306
+ return resolveTernaryBranch({
307
+ wantType,
308
+ expr,
309
+ branch: isTrue ? parts.ifTrue : parts.ifFalse,
310
+ params,
311
+ });
277
312
  }
278
- function resolveDualTernary(wantType, expr, params) {
279
- const match = dualTernaryRegexp.exec(expr);
280
- if (!match) {
281
- throw new ExprParseError("Malformed CEL ternary expression '" + expr + "'");
313
+ function resolveTernaryCondition(expr, condition, params) {
314
+ const conditionExpr = `${EXPR_PREFIX}${condition}${EXPR_SUFFIX}`;
315
+ if (isDualComparisonExpression(conditionExpr)) {
316
+ return resolveDualComparison(conditionExpr, params);
282
317
  }
283
- const comparisonExpr = `{{ params.${match[1]} ${match[2]} params.${match[3]} }}`;
284
- const isTrue = resolveDualComparison(comparisonExpr, params);
285
- if (isTrue) {
286
- return resolveParamListOrLiteral(wantType, match[4], params);
318
+ else if (isComparisonExpression(conditionExpr)) {
319
+ return resolveComparison(conditionExpr, params);
287
320
  }
288
- else {
289
- return resolveParamListOrLiteral(wantType, match[5], params);
290
- }
291
- }
292
- function resolveLiteralTernary(wantType, expr, params) {
293
- const match = literalTernaryRegexp.exec(expr);
321
+ const match = identityRegexp.exec(conditionExpr);
294
322
  if (!match) {
295
- throw new ExprParseError("Malformed CEL ternary expression '" + expr + "'");
323
+ throw new ExprParseError(`CEL ternary expression '${expr}' is conditioned on an unsupported form`);
296
324
  }
297
325
  const paramName = match[1];
298
- const paramValue = params[match[1]];
326
+ const paramValue = params[paramName];
299
327
  if (!paramValue) {
300
- throw new ExprParseError("CEL ternary expression '" + expr + "' references missing param " + paramName);
328
+ throw new ExprParseError(`CEL ternary expression '${expr}' references missing param ${paramName}`);
301
329
  }
302
330
  if (!paramValue.legalBoolean) {
303
- throw new ExprParseError("CEL ternary expression '" + expr + "' is conditional on non-boolean param " + paramName);
331
+ throw new ExprParseError(`CEL ternary expression '${expr}' is conditional on non-boolean param ${paramName}`);
304
332
  }
305
- if (paramValue.asBoolean()) {
306
- return resolveParamListOrLiteral(wantType, match[2], params);
307
- }
308
- else {
309
- return resolveParamListOrLiteral(wantType, match[3], params);
333
+ return paramValue.asBoolean();
334
+ }
335
+ function resolveTernaryBranch(options) {
336
+ const { wantType, expr, branch, params } = options;
337
+ const nested = parseTernary(`${EXPR_PREFIX}${branch}${EXPR_SUFFIX}`);
338
+ if (nested) {
339
+ return resolveTernary({ wantType, expr, parts: nested, params });
310
340
  }
341
+ return resolveParamListOrLiteral(wantType, branch, params);
311
342
  }
312
343
  function resolveParamListOrLiteral(wantType, field, params) {
313
344
  const match = paramRegexp.exec(field);
@@ -7,6 +7,7 @@ exports.parseFunctionSelector = parseFunctionSelector;
7
7
  exports.getEndpointFilters = getEndpointFilters;
8
8
  exports.getHumanFriendlyPlatformName = getHumanFriendlyPlatformName;
9
9
  exports.getFunctionLabel = getFunctionLabel;
10
+ exports.generationDowngradeMessage = generationDowngradeMessage;
10
11
  exports.targetCodebases = targetCodebases;
11
12
  exports.groupEndpointsByCodebase = groupEndpointsByCodebase;
12
13
  exports.isCodebaseFiltered = isCodebaseFiltered;
@@ -101,6 +102,15 @@ function getFunctionLabel(fn) {
101
102
  }
102
103
  return id;
103
104
  }
105
+ function generationDowngradeMessage(want, have) {
106
+ if (want.platform !== "gcfv1" || have.platform === "gcfv1") {
107
+ return undefined;
108
+ }
109
+ const from = have.platform === "gcfv2" ? "GCFv2" : "Cloud Run";
110
+ return (`[${getFunctionLabel(want)}] Functions cannot be downgraded from ${from} to GCFv1. ` +
111
+ `To recreate it as GCFv1, delete the existing function first: ` +
112
+ `firebase functions:delete ${want.id} --region ${want.region}`);
113
+ }
104
114
  function targetCodebases(config, filters) {
105
115
  const codebasesFromConfig = getCodebasesFromConfig(config);
106
116
  if (!filters) {