firebase-tools-with-isolate 13.0.2 → 13.3.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 (76) hide show
  1. package/README.md +6 -2
  2. package/lib/appdistribution/client.js +36 -28
  3. package/lib/appdistribution/options-parser-util.js +80 -1
  4. package/lib/appdistribution/types.js +31 -0
  5. package/lib/auth.js +11 -2
  6. package/lib/commands/appdistribution-distribute.js +70 -10
  7. package/lib/commands/apphosting-backends-create.js +6 -3
  8. package/lib/commands/apphosting-backends-delete.js +3 -5
  9. package/lib/commands/apphosting-backends-get.js +2 -2
  10. package/lib/commands/apphosting-backends-list.js +21 -37
  11. package/lib/commands/apphosting-builds-create.js +8 -8
  12. package/lib/commands/apphosting-builds-get.js +2 -2
  13. package/lib/commands/apphosting-rollouts-create.js +5 -5
  14. package/lib/commands/apphosting-rollouts-list.js +6 -3
  15. package/lib/commands/firestore-backups-delete.js +44 -0
  16. package/lib/commands/firestore-backups-get.js +25 -0
  17. package/lib/commands/firestore-backups-list.js +33 -0
  18. package/lib/commands/firestore-backups-schedules-create.js +67 -0
  19. package/lib/commands/firestore-backups-schedules-delete.js +46 -0
  20. package/lib/commands/firestore-backups-schedules-list.js +27 -0
  21. package/lib/commands/firestore-backups-schedules-update.js +33 -0
  22. package/lib/commands/firestore-databases-create.js +4 -2
  23. package/lib/commands/firestore-databases-delete.js +4 -2
  24. package/lib/commands/firestore-databases-get.js +3 -1
  25. package/lib/commands/firestore-databases-list.js +3 -1
  26. package/lib/commands/firestore-databases-restore.js +42 -0
  27. package/lib/commands/firestore-databases-update.js +4 -2
  28. package/lib/commands/firestore-indexes-list.js +5 -3
  29. package/lib/commands/firestore-locations.js +3 -1
  30. package/lib/commands/functions-config-export.js +4 -2
  31. package/lib/commands/index.js +11 -1
  32. package/lib/commands/init.js +3 -3
  33. package/lib/commands/use.js +4 -1
  34. package/lib/deploy/functions/runtimes/index.js +2 -0
  35. package/lib/deploy/functions/runtimes/python/index.js +4 -1
  36. package/lib/deploy/functions/services/firestore.js +1 -1
  37. package/lib/deploy/hosting/convertConfig.js +5 -0
  38. package/lib/deploy/hosting/prepare.js +2 -1
  39. package/lib/emulator/auth/handlers.js +1 -1
  40. package/lib/emulator/auth/operations.js +42 -13
  41. package/lib/emulator/auth/state.js +14 -0
  42. package/lib/emulator/downloadableEmulators.js +3 -3
  43. package/lib/emulator/storage/metadata.js +1 -1
  44. package/lib/emulator/storage/rules/runtime.js +1 -1
  45. package/lib/experiments.js +2 -2
  46. package/lib/firestore/api-sort.js +23 -1
  47. package/lib/firestore/api-types.js +6 -1
  48. package/lib/firestore/api.js +18 -115
  49. package/lib/firestore/backupUtils.js +30 -0
  50. package/lib/firestore/delete.js +3 -3
  51. package/lib/firestore/pretty-print.js +184 -0
  52. package/lib/frameworks/angular/index.js +2 -2
  53. package/lib/frameworks/angular/utils.js +14 -10
  54. package/lib/frameworks/astro/index.js +1 -2
  55. package/lib/frameworks/flutter/index.js +1 -1
  56. package/lib/frameworks/index.js +2 -3
  57. package/lib/frameworks/next/index.js +5 -3
  58. package/lib/frameworks/nuxt/index.js +2 -2
  59. package/lib/frameworks/nuxt2/index.js +1 -2
  60. package/lib/frameworks/sveltekit/index.js +2 -2
  61. package/lib/frameworks/utils.js +11 -2
  62. package/lib/frameworks/vite/index.js +8 -4
  63. package/lib/functions/env.js +2 -0
  64. package/lib/gcp/apphosting.js +103 -17
  65. package/lib/gcp/cloudbuild.js +7 -2
  66. package/lib/gcp/cloudfunctionsv2.js +2 -4
  67. package/lib/gcp/firestore.js +89 -6
  68. package/lib/hosting/api.js +3 -9
  69. package/lib/hosting/options.js +2 -1
  70. package/lib/init/features/apphosting/index.js +150 -68
  71. package/lib/init/features/apphosting/repo.js +80 -32
  72. package/lib/init/features/hosting/github.js +6 -1
  73. package/lib/metaprogramming.js +3 -0
  74. package/lib/prompt.js +1 -0
  75. package/lib/utils.js +1 -12
  76. package/package.json +15 -10
@@ -95,7 +95,7 @@ async function createFunction(cloudFunction) {
95
95
  };
96
96
  cloudFunction.serviceConfig.environmentVariables = {
97
97
  ...cloudFunction.serviceConfig.environmentVariables,
98
- FUNCTION_TARGET: functionId.replaceAll("-", "."),
98
+ FUNCTION_TARGET: cloudFunction.buildConfig.entryPoint.replaceAll("-", "."),
99
99
  };
100
100
  try {
101
101
  const res = await client.post(components.join("/"), cloudFunction, { queryParams: { functionId } });
@@ -149,8 +149,6 @@ async function listFunctionsInternal(projectId, region) {
149
149
  }
150
150
  }
151
151
  async function updateFunction(cloudFunction) {
152
- const components = cloudFunction.name.split("/");
153
- const functionId = components.splice(-1, 1)[0];
154
152
  const fieldMasks = proto.fieldMasks(cloudFunction, "labels", "serviceConfig.environmentVariables", "serviceConfig.secretEnvironmentVariables");
155
153
  cloudFunction.buildConfig.environmentVariables = {
156
154
  ...cloudFunction.buildConfig.environmentVariables,
@@ -159,7 +157,7 @@ async function updateFunction(cloudFunction) {
159
157
  fieldMasks.push("buildConfig.buildEnvironmentVariables");
160
158
  cloudFunction.serviceConfig.environmentVariables = {
161
159
  ...cloudFunction.serviceConfig.environmentVariables,
162
- FUNCTION_TARGET: functionId.replaceAll("-", "."),
160
+ FUNCTION_TARGET: cloudFunction.buildConfig.entryPoint.replaceAll("-", "."),
163
161
  };
164
162
  try {
165
163
  const queryParams = {
@@ -1,15 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteDocuments = exports.deleteDocument = exports.listCollectionIds = exports.getDatabase = void 0;
3
+ exports.getBackupSchedule = exports.listBackupSchedules = exports.getBackup = exports.listBackups = exports.deleteBackupSchedule = exports.deleteBackup = exports.updateBackupSchedule = exports.createBackupSchedule = exports.deleteDocuments = exports.deleteDocument = exports.listCollectionIds = exports.getDatabase = exports.DayOfWeek = void 0;
4
4
  const api_1 = require("../api");
5
5
  const apiv2_1 = require("../apiv2");
6
6
  const logger_1 = require("../logger");
7
- const apiClient = new apiv2_1.Client({
7
+ const proto_1 = require("./proto");
8
+ const error_1 = require("../error");
9
+ const prodOnlyClient = new apiv2_1.Client({
8
10
  auth: true,
9
11
  apiVersion: "v1",
10
12
  urlPrefix: api_1.firestoreOrigin,
11
13
  });
12
- async function getDatabase(project, database) {
14
+ const emuOrProdClient = new apiv2_1.Client({
15
+ auth: true,
16
+ apiVersion: "v1",
17
+ urlPrefix: api_1.firestoreOriginOrEmulator,
18
+ });
19
+ var DayOfWeek;
20
+ (function (DayOfWeek) {
21
+ DayOfWeek["MONDAY"] = "MONDAY";
22
+ DayOfWeek["TUEDAY"] = "TUESDAY";
23
+ DayOfWeek["WEDNESDAY"] = "WEDNESDAY";
24
+ DayOfWeek["THURSDAY"] = "THURSDAY";
25
+ DayOfWeek["FRIDAY"] = "FRIDAY";
26
+ DayOfWeek["SATURDAY"] = "SATURDAY";
27
+ DayOfWeek["SUNDAY"] = "SUNDAY";
28
+ })(DayOfWeek = exports.DayOfWeek || (exports.DayOfWeek = {}));
29
+ async function getDatabase(project, database, allowEmulator = false) {
30
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
13
31
  const url = `projects/${project}/databases/${database}`;
14
32
  try {
15
33
  const resp = await apiClient.get(url);
@@ -21,7 +39,8 @@ async function getDatabase(project, database) {
21
39
  }
22
40
  }
23
41
  exports.getDatabase = getDatabase;
24
- function listCollectionIds(project) {
42
+ function listCollectionIds(project, allowEmulator = false) {
43
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
25
44
  const url = "projects/" + project + "/databases/(default)/documents:listCollectionIds";
26
45
  const data = {
27
46
  pageSize: 2147483647,
@@ -31,11 +50,13 @@ function listCollectionIds(project) {
31
50
  });
32
51
  }
33
52
  exports.listCollectionIds = listCollectionIds;
34
- async function deleteDocument(doc) {
53
+ async function deleteDocument(doc, allowEmulator = false) {
54
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
35
55
  return apiClient.delete(doc.name);
36
56
  }
37
57
  exports.deleteDocument = deleteDocument;
38
- async function deleteDocuments(project, docs) {
58
+ async function deleteDocuments(project, docs, allowEmulator = false) {
59
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
39
60
  const url = "projects/" + project + "/databases/(default)/documents:commit";
40
61
  const writes = docs.map((doc) => {
41
62
  return { delete: doc.name };
@@ -45,3 +66,65 @@ async function deleteDocuments(project, docs) {
45
66
  return res.body.writeResults.length;
46
67
  }
47
68
  exports.deleteDocuments = deleteDocuments;
69
+ async function createBackupSchedule(project, databaseId, retention, dailyRecurrence, weeklyRecurrence) {
70
+ const url = `projects/${project}/databases/${databaseId}/backupSchedules`;
71
+ const data = {
72
+ retention: (0, proto_1.durationFromSeconds)(retention),
73
+ dailyRecurrence,
74
+ weeklyRecurrence,
75
+ };
76
+ (0, proto_1.assertOneOf)("BackupSchedule", data, "recurrence", "dailyRecurrence", "weeklyRecurrence");
77
+ const res = await prodOnlyClient.post(url, data);
78
+ return res.body;
79
+ }
80
+ exports.createBackupSchedule = createBackupSchedule;
81
+ async function updateBackupSchedule(backupScheduleName, retention) {
82
+ const data = {
83
+ retention: (0, proto_1.durationFromSeconds)(retention),
84
+ };
85
+ const res = await prodOnlyClient.patch(backupScheduleName, data);
86
+ return res.body;
87
+ }
88
+ exports.updateBackupSchedule = updateBackupSchedule;
89
+ async function deleteBackup(backupName) {
90
+ await prodOnlyClient.delete(backupName);
91
+ }
92
+ exports.deleteBackup = deleteBackup;
93
+ async function deleteBackupSchedule(backupScheduleName) {
94
+ await prodOnlyClient.delete(backupScheduleName);
95
+ }
96
+ exports.deleteBackupSchedule = deleteBackupSchedule;
97
+ async function listBackups(project, location) {
98
+ const url = `/projects/${project}/locations/${location}/backups`;
99
+ const res = await prodOnlyClient.get(url);
100
+ return res.body;
101
+ }
102
+ exports.listBackups = listBackups;
103
+ async function getBackup(backupName) {
104
+ const res = await prodOnlyClient.get(backupName);
105
+ const backup = res.body;
106
+ if (!backup) {
107
+ throw new error_1.FirebaseError("Not found");
108
+ }
109
+ return backup;
110
+ }
111
+ exports.getBackup = getBackup;
112
+ async function listBackupSchedules(project, database) {
113
+ const url = `/projects/${project}/databases/${database}/backupSchedules`;
114
+ const res = await prodOnlyClient.get(url);
115
+ const backupSchedules = res.body.backupSchedules;
116
+ if (!backupSchedules) {
117
+ return [];
118
+ }
119
+ return backupSchedules;
120
+ }
121
+ exports.listBackupSchedules = listBackupSchedules;
122
+ async function getBackupSchedule(backupScheduleName) {
123
+ const res = await prodOnlyClient.get(backupScheduleName);
124
+ const backupSchedule = res.body;
125
+ if (!backupSchedule) {
126
+ throw new error_1.FirebaseError("Not found");
127
+ }
128
+ return backupSchedule;
129
+ }
130
+ exports.getBackupSchedule = getBackupSchedule;
@@ -51,10 +51,7 @@ async function listChannels(project = "-", site) {
51
51
  for (;;) {
52
52
  try {
53
53
  const res = await apiClient.get(`/projects/${project}/sites/${site}/channels`, { queryParams: { pageToken: nextPageToken, pageSize: 10 } });
54
- const c = res.body.channels;
55
- if (c) {
56
- channels.push(...c);
57
- }
54
+ channels.push(...(res.body.channels ?? []));
58
55
  nextPageToken = res.body.nextPageToken || "";
59
56
  if (!nextPageToken) {
60
57
  return channels;
@@ -110,7 +107,7 @@ async function listVersions(site) {
110
107
  const res = await apiClient.get(`projects/-/sites/${site}/versions`, {
111
108
  queryParams,
112
109
  });
113
- versions.push(...res.body.versions);
110
+ versions.push(...(res.body.versions ?? []));
114
111
  pageToken = res.body.nextPageToken;
115
112
  } while (pageToken);
116
113
  return versions;
@@ -142,10 +139,7 @@ async function listSites(project) {
142
139
  for (;;) {
143
140
  try {
144
141
  const res = await apiClient.get(`/projects/${project}/sites`, { queryParams: { pageToken: nextPageToken, pageSize: 10 } });
145
- const c = res.body.sites;
146
- if (c) {
147
- sites.push(...c);
148
- }
142
+ sites.push(...(res.body.sites ?? []));
149
143
  nextPageToken = res.body.nextPageToken || "";
150
144
  if (!nextPageToken) {
151
145
  return sites;
@@ -1,3 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const optionsAreHostingOptions = true;
3
+ const metaprogramming_1 = require("../metaprogramming");
4
+ (0, metaprogramming_1.assertImplements)();
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.onboardRollout = exports.createBackend = exports.onboardBackend = exports.doSetup = void 0;
3
+ exports.orchestrateRollout = exports.setDefaultTrafficPolicy = exports.createBackend = exports.doSetup = void 0;
4
4
  const clc = require("colorette");
5
5
  const repo = require("./repo");
6
6
  const poller = require("../../../operation-poller");
@@ -8,17 +8,21 @@ const apphosting = require("../../../gcp/apphosting");
8
8
  const utils_1 = require("../../../utils");
9
9
  const api_1 = require("../../../api");
10
10
  const apphosting_1 = require("../../../gcp/apphosting");
11
+ const resourceManager_1 = require("../../../gcp/resourceManager");
12
+ const iam_1 = require("../../../gcp/iam");
11
13
  const error_1 = require("../../../error");
12
14
  const prompt_1 = require("../../../prompt");
13
15
  const constants_1 = require("./constants");
14
16
  const ensureApiEnabled_1 = require("../../../ensureApiEnabled");
17
+ const deploymentTool = require("../../../deploymentTool");
18
+ const DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME = "firebase-app-hosting-compute";
15
19
  const apphostingPollerOptions = {
16
20
  apiOrigin: api_1.apphostingOrigin,
17
21
  apiVersion: apphosting_1.API_VERSION,
18
22
  masterTimeout: 25 * 60 * 1000,
19
23
  maxBackoff: 10000,
20
24
  };
21
- async function doSetup(setup, projectId) {
25
+ async function doSetup(projectId, location, serviceAccount) {
22
26
  await Promise.all([
23
27
  (0, ensureApiEnabled_1.ensure)(projectId, "cloudbuild.googleapis.com", "apphosting", true),
24
28
  (0, ensureApiEnabled_1.ensure)(projectId, "secretmanager.googleapis.com", "apphosting", true),
@@ -26,34 +30,38 @@ async function doSetup(setup, projectId) {
26
30
  (0, ensureApiEnabled_1.ensure)(projectId, "artifactregistry.googleapis.com", "apphosting", true),
27
31
  ]);
28
32
  const allowedLocations = (await apphosting.listLocations(projectId)).map((loc) => loc.locationId);
29
- if (setup.location) {
30
- if (!allowedLocations.includes(setup.location)) {
31
- throw new error_1.FirebaseError(`Invalid location ${setup.location}. Valid choices are ${allowedLocations.join(", ")}`);
33
+ if (location) {
34
+ if (!allowedLocations.includes(location)) {
35
+ throw new error_1.FirebaseError(`Invalid location ${location}. Valid choices are ${allowedLocations.join(", ")}`);
32
36
  }
33
37
  }
34
38
  (0, utils_1.logBullet)("First we need a few details to create your backend.");
35
- const location = setup.location || (await promptLocation(projectId, allowedLocations));
39
+ location =
40
+ location ||
41
+ (await (0, prompt_1.promptOnce)({
42
+ name: "region",
43
+ type: "list",
44
+ default: constants_1.DEFAULT_REGION,
45
+ message: "Please select a region " +
46
+ `(${clc.yellow("info")}: Your region determines where your backend is located):\n`,
47
+ choices: allowedLocations.map((loc) => ({ value: loc })),
48
+ }));
36
49
  (0, utils_1.logSuccess)(`Region set to ${location}.\n`);
37
- let backendId;
38
- while (true) {
39
- backendId = await (0, prompt_1.promptOnce)({
40
- name: "backendId",
41
- type: "input",
42
- default: "my-web-app",
43
- message: "Create a name for your backend [1-30 characters]",
44
- });
45
- try {
46
- await apphosting.getBackend(projectId, location, backendId);
47
- }
48
- catch (err) {
49
- if (err.status === 404) {
50
- break;
51
- }
52
- throw new error_1.FirebaseError(`Failed to check if backend with id ${backendId} already exists in ${location}`, { original: err });
53
- }
54
- (0, utils_1.logWarning)(`Backend with id ${backendId} already exists in ${location}`);
55
- }
56
- const backend = await onboardBackend(projectId, location, backendId);
50
+ const backendId = await promptNewBackendId(projectId, location, {
51
+ name: "backendId",
52
+ type: "input",
53
+ default: "my-web-app",
54
+ message: "Create a name for your backend [1-30 characters]",
55
+ });
56
+ const cloudBuildConnRepo = await repo.linkGitHubRepository(projectId, location);
57
+ const backend = await createBackend(projectId, location, backendId, cloudBuildConnRepo, serviceAccount);
58
+ const branch = await (0, prompt_1.promptOnce)({
59
+ name: "branch",
60
+ type: "input",
61
+ default: "main",
62
+ message: "Pick a branch for continuous deployment",
63
+ });
64
+ await setDefaultTrafficPolicy(projectId, location, backendId, branch);
57
65
  const confirmRollout = await (0, prompt_1.promptOnce)({
58
66
  type: "confirm",
59
67
  name: "rollout",
@@ -65,74 +73,141 @@ async function doSetup(setup, projectId) {
65
73
  (0, utils_1.logSuccess)(`Your site will be deployed at:\n\thttps://${backend.uri}`);
66
74
  return;
67
75
  }
68
- const branch = await (0, prompt_1.promptOnce)({
69
- name: "branch",
70
- type: "input",
71
- default: "main",
72
- message: "Which branch do you want to deploy?",
73
- });
74
- const { build } = await onboardRollout(projectId, location, backendId, {
76
+ await orchestrateRollout(projectId, location, backendId, {
75
77
  source: {
76
78
  codebase: {
77
79
  branch,
78
80
  },
79
81
  },
80
82
  });
81
- if (build.state !== "READY") {
82
- throw new error_1.FirebaseError(`Failed to build your app. Please inspect the build logs at ${build.buildLogsUri}.`, { children: [build.error] });
83
- }
84
83
  (0, utils_1.logSuccess)(`Successfully created backend:\n\t${backend.name}`);
85
84
  (0, utils_1.logSuccess)(`Your site is now deployed at:\n\thttps://${backend.uri}`);
86
- (0, utils_1.logSuccess)(`View the rollout status by running:\n\tfirebase apphosting:backends:get ${backendId} --project ${projectId}`);
87
85
  }
88
86
  exports.doSetup = doSetup;
89
- async function promptLocation(projectId, locations) {
90
- return (await (0, prompt_1.promptOnce)({
91
- name: "region",
92
- type: "list",
93
- default: constants_1.DEFAULT_REGION,
94
- message: "Please select a region " +
95
- `(${clc.yellow("info")}: Your region determines where your backend is located):\n`,
96
- choices: locations.map((loc) => ({ value: loc })),
97
- }));
87
+ async function promptNewBackendId(projectId, location, prompt) {
88
+ while (true) {
89
+ const backendId = await (0, prompt_1.promptOnce)(prompt);
90
+ try {
91
+ await apphosting.getBackend(projectId, location, backendId);
92
+ }
93
+ catch (err) {
94
+ if (err.status === 404) {
95
+ return backendId;
96
+ }
97
+ throw new error_1.FirebaseError(`Failed to check if backend with id ${backendId} already exists in ${location}`, { original: err });
98
+ }
99
+ (0, utils_1.logWarning)(`Backend with id ${backendId} already exists in ${location}`);
100
+ }
98
101
  }
99
- function toBackend(cloudBuildConnRepo) {
100
- return {
102
+ function defaultComputeServiceAccountEmail(projectId) {
103
+ return `${DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME}@${projectId}.iam.gserviceaccount.com`;
104
+ }
105
+ async function createBackend(projectId, location, backendId, repository, serviceAccount) {
106
+ const defaultServiceAccount = defaultComputeServiceAccountEmail(projectId);
107
+ const backendReqBody = {
101
108
  servingLocality: "GLOBAL_ACCESS",
102
109
  codebase: {
103
- repository: `${cloudBuildConnRepo.name}`,
110
+ repository: `${repository.name}`,
104
111
  rootDirectory: "/",
105
112
  },
106
- labels: {},
113
+ labels: deploymentTool.labels(),
114
+ computeServiceAccount: serviceAccount || defaultServiceAccount,
107
115
  };
116
+ delete backendReqBody.computeServiceAccount;
117
+ async function createBackendAndPoll() {
118
+ const op = await apphosting.createBackend(projectId, location, backendReqBody, backendId);
119
+ return await poller.pollOperation({
120
+ ...apphostingPollerOptions,
121
+ pollerName: `create-${projectId}-${location}-${backendId}`,
122
+ operationResourceName: op.name,
123
+ });
124
+ }
125
+ try {
126
+ return await createBackendAndPoll();
127
+ }
128
+ catch (err) {
129
+ if (err.status === 403) {
130
+ if (err.message.includes(defaultServiceAccount)) {
131
+ await provisionDefaultComputeServiceAccount(projectId);
132
+ return await createBackendAndPoll();
133
+ }
134
+ else if (serviceAccount && err.message.includes(serviceAccount)) {
135
+ throw new error_1.FirebaseError(`Failed to create backend due to missing delegation permissions for ${serviceAccount}. Make sure you have the iam.serviceAccounts.actAs permission.`, { children: [err] });
136
+ }
137
+ }
138
+ throw err;
139
+ }
108
140
  }
109
- async function onboardBackend(projectId, location, backendId) {
110
- const cloudBuildConnRepo = await repo.linkGitHubRepository(projectId, location);
111
- const backendDetails = toBackend(cloudBuildConnRepo);
112
- return await createBackend(projectId, location, backendDetails, backendId);
141
+ exports.createBackend = createBackend;
142
+ async function provisionDefaultComputeServiceAccount(projectId) {
143
+ try {
144
+ await (0, iam_1.createServiceAccount)(projectId, DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME, "Firebase App Hosting compute service account", "Default service account used to run builds and deploys for Firebase App Hosting");
145
+ }
146
+ catch (err) {
147
+ if (err.status !== 409) {
148
+ throw err;
149
+ }
150
+ }
151
+ await (0, resourceManager_1.addServiceAccountToRoles)(projectId, defaultComputeServiceAccountEmail(projectId), [
152
+ "roles/firebaseapphosting.viewer",
153
+ "roles/artifactregistry.createOnPushWriter",
154
+ "roles/logging.logWriter",
155
+ "roles/storage.objectAdmin",
156
+ "roles/firebase.sdkAdminServiceAgent",
157
+ ], true);
113
158
  }
114
- exports.onboardBackend = onboardBackend;
115
- async function createBackend(projectId, location, backendReqBoby, backendId) {
116
- const op = await apphosting.createBackend(projectId, location, backendReqBoby, backendId);
117
- const backend = await poller.pollOperation({
159
+ async function setDefaultTrafficPolicy(projectId, location, backendId, codebaseBranch) {
160
+ const traffic = {
161
+ rolloutPolicy: {
162
+ codebaseBranch: codebaseBranch,
163
+ stages: [
164
+ {
165
+ progression: "IMMEDIATE",
166
+ targetPercent: 100,
167
+ },
168
+ ],
169
+ },
170
+ };
171
+ const op = await apphosting.updateTraffic(projectId, location, backendId, traffic);
172
+ await poller.pollOperation({
118
173
  ...apphostingPollerOptions,
119
- pollerName: `create-${projectId}-${location}-${backendId}`,
174
+ pollerName: `updateTraffic-${projectId}-${location}-${backendId}`,
120
175
  operationResourceName: op.name,
121
176
  });
122
- return backend;
123
177
  }
124
- exports.createBackend = createBackend;
125
- async function onboardRollout(projectId, location, backendId, buildInput) {
178
+ exports.setDefaultTrafficPolicy = setDefaultTrafficPolicy;
179
+ async function orchestrateRollout(projectId, location, backendId, buildInput) {
126
180
  (0, utils_1.logBullet)("Starting a new rollout... this may take a few minutes.");
127
- const buildId = (0, utils_1.generateId)();
181
+ const buildId = await apphosting.getNextRolloutId(projectId, location, backendId, 1);
128
182
  const buildOp = await apphosting.createBuild(projectId, location, backendId, buildId, buildInput);
129
- const rolloutId = (0, utils_1.generateId)();
130
- const rolloutOp = await apphosting.createRollout(projectId, location, backendId, rolloutId, {
183
+ const rolloutBody = {
131
184
  build: `projects/${projectId}/locations/${location}/backends/${backendId}/builds/${buildId}`,
132
- });
185
+ };
186
+ let tries = 0;
187
+ let done = false;
188
+ while (!done) {
189
+ tries++;
190
+ try {
191
+ const validateOnly = true;
192
+ await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody, validateOnly);
193
+ done = true;
194
+ }
195
+ catch (err) {
196
+ if (err instanceof error_1.FirebaseError && err.status === 400) {
197
+ if (tries >= 5) {
198
+ throw err;
199
+ }
200
+ await new Promise((resolve) => setTimeout(resolve, 1000));
201
+ }
202
+ else {
203
+ throw err;
204
+ }
205
+ }
206
+ }
207
+ const rolloutOp = await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody);
133
208
  const rolloutPoll = poller.pollOperation({
134
209
  ...apphostingPollerOptions,
135
- pollerName: `create-${projectId}-${location}-backend-${backendId}-rollout-${rolloutId}`,
210
+ pollerName: `create-${projectId}-${location}-backend-${backendId}-rollout-${buildId}`,
136
211
  operationResourceName: rolloutOp.name,
137
212
  });
138
213
  const buildPoll = poller.pollOperation({
@@ -142,6 +217,13 @@ async function onboardRollout(projectId, location, backendId, buildInput) {
142
217
  });
143
218
  const [rollout, build] = await Promise.all([rolloutPoll, buildPoll]);
144
219
  (0, utils_1.logSuccess)("Rollout completed.");
220
+ if (build.state !== "READY") {
221
+ if (!build.buildLogsUri) {
222
+ throw new error_1.FirebaseError("Failed to build your app, but failed to get build logs as well. " +
223
+ "This is an internal error and should be reported");
224
+ }
225
+ throw new error_1.FirebaseError(`Failed to build your app. Please inspect the build logs at ${build.buildLogsUri}.`, { children: [build.error] });
226
+ }
145
227
  return { rollout, build };
146
228
  }
147
- exports.onboardRollout = onboardRollout;
229
+ exports.orchestrateRollout = orchestrateRollout;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.linkGitHubRepository = exports.parseConnectionName = void 0;
3
+ exports.fetchAllRepositories = exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.linkGitHubRepository = exports.parseConnectionName = void 0;
4
4
  const clc = require("colorette");
5
5
  const gcb = require("../../../gcp/cloudbuild");
6
6
  const rm = require("../../../gcp/resourceManager");
@@ -10,11 +10,13 @@ const api_1 = require("../../../api");
10
10
  const error_1 = require("../../../error");
11
11
  const prompt_1 = require("../../../prompt");
12
12
  const getProjectNumber_1 = require("../../../getProjectNumber");
13
+ const fuzzy = require("fuzzy");
14
+ const inquirer = require("inquirer");
13
15
  const APPHOSTING_CONN_PATTERN = /.+\/apphosting-github-conn-.+$/;
14
16
  const APPHOSTING_OAUTH_CONN_NAME = "apphosting-github-oauth";
15
17
  const CONNECTION_NAME_REGEX = /^projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/connections\/(?<id>[^\/]+)$/;
16
18
  function parseConnectionName(name) {
17
- const match = name.match(CONNECTION_NAME_REGEX);
19
+ const match = CONNECTION_NAME_REGEX.exec(name);
18
20
  if (!match || typeof match.groups === undefined) {
19
21
  return;
20
22
  }
@@ -46,18 +48,21 @@ function generateConnectionId() {
46
48
  const randomHash = Math.random().toString(36).slice(6);
47
49
  return `apphosting-github-conn-${randomHash}`;
48
50
  }
51
+ const ADD_REPO_CHOICE = "@ADD_REPO";
52
+ const ADD_CONN_CHOICE = "@ADD_CONN";
53
+ const CONFIGURE_REMOTE_URI_CHOICES = [ADD_REPO_CHOICE, ADD_CONN_CHOICE];
49
54
  async function linkGitHubRepository(projectId, location) {
50
55
  utils.logBullet(clc.bold(`${clc.yellow("===")} Set up a GitHub connection`));
56
+ let oauthConn = await getOrCreateConnection(projectId, location, APPHOSTING_OAUTH_CONN_NAME);
57
+ while (oauthConn.installationState.stage === "PENDING_USER_OAUTH") {
58
+ oauthConn = await promptConnectionAuth(oauthConn);
59
+ }
51
60
  const existingConns = await listAppHostingConnections(projectId);
52
61
  if (existingConns.length < 1) {
53
62
  const grantSuccess = await promptSecretManagerAdminGrant(projectId);
54
63
  if (!grantSuccess) {
55
64
  throw new error_1.FirebaseError("Insufficient IAM permissions to create a new connection to GitHub");
56
65
  }
57
- let oauthConn = await getOrCreateConnection(projectId, location, APPHOSTING_OAUTH_CONN_NAME);
58
- while (oauthConn.installationState.stage === "PENDING_USER_OAUTH") {
59
- oauthConn = await promptConnectionAuth(oauthConn);
60
- }
61
66
  const connectionId = generateConnectionId();
62
67
  const conn = await createConnection(projectId, location, connectionId, {
63
68
  authorizerCredential: oauthConn.githubConfig?.authorizerCredential,
@@ -69,12 +74,25 @@ async function linkGitHubRepository(projectId, location) {
69
74
  existingConns.push(refreshedConn);
70
75
  }
71
76
  let { remoteUri, connection } = await promptRepositoryUri(projectId, existingConns);
72
- while (remoteUri === "") {
73
- await utils.openInBrowser("https://github.com/apps/google-cloud-build/installations/new");
74
- await (0, prompt_1.promptOnce)({
75
- type: "input",
76
- message: "Press ENTER once you have finished configuring your installation's access settings.",
77
- });
77
+ while (CONFIGURE_REMOTE_URI_CHOICES.includes(remoteUri)) {
78
+ if (remoteUri === ADD_REPO_CHOICE) {
79
+ await utils.openInBrowser("https://github.com/apps/google-cloud-build/installations/new");
80
+ await (0, prompt_1.promptOnce)({
81
+ type: "input",
82
+ message: "Press ENTER once you have provided the GitHub app installation with access to your desired repository.",
83
+ });
84
+ }
85
+ else if (remoteUri === ADD_CONN_CHOICE) {
86
+ const connectionId = generateConnectionId();
87
+ const conn = await createConnection(projectId, location, connectionId, {
88
+ authorizerCredential: oauthConn.githubConfig?.authorizerCredential,
89
+ });
90
+ let refreshedConn = conn;
91
+ while (refreshedConn.installationState.stage !== "COMPLETE") {
92
+ refreshedConn = await promptAppInstall(conn);
93
+ }
94
+ existingConns.push(refreshedConn);
95
+ }
78
96
  const selection = await promptRepositoryUri(projectId, existingConns);
79
97
  remoteUri = selection.remoteUri;
80
98
  connection = selection.connection;
@@ -91,28 +109,36 @@ async function linkGitHubRepository(projectId, location) {
91
109
  }
92
110
  exports.linkGitHubRepository = linkGitHubRepository;
93
111
  async function promptRepositoryUri(projectId, connections) {
94
- const remoteUriToConnection = {};
95
- for (const conn of connections) {
96
- const { location, id } = parseConnectionName(conn.name);
97
- const resp = await gcb.fetchLinkableRepositories(projectId, location, id);
98
- if (resp.repositories && resp.repositories.length > 0) {
99
- for (const repo of resp.repositories) {
100
- remoteUriToConnection[repo.remoteUri] = conn;
101
- }
102
- }
103
- }
104
- const choices = Object.keys(remoteUriToConnection).map((remoteUri) => ({
105
- name: extractRepoSlugFromUri(remoteUri) || remoteUri,
106
- value: remoteUri,
107
- }));
108
- choices.push({
109
- name: "Missing a repo? Select this option to configure your installation's access settings",
110
- value: "",
111
- });
112
+ const { repos, remoteUriToConnection } = await fetchAllRepositories(projectId, connections);
113
+ const searchRepos = (repos) => async (_, input = "") => {
114
+ return [
115
+ new inquirer.Separator(),
116
+ {
117
+ name: "Missing a repo? Select this option to configure your installation's access settings",
118
+ value: ADD_REPO_CHOICE,
119
+ },
120
+ {
121
+ name: "Missing an account or org? Select this option to create a new connection",
122
+ value: ADD_CONN_CHOICE,
123
+ },
124
+ new inquirer.Separator(),
125
+ ...fuzzy
126
+ .filter(input, repos, {
127
+ extract: (repo) => extractRepoSlugFromUri(repo.remoteUri) || "",
128
+ })
129
+ .map((result) => {
130
+ return {
131
+ name: extractRepoSlugFromUri(result.original.remoteUri) || "",
132
+ value: result.original.remoteUri,
133
+ };
134
+ }),
135
+ ];
136
+ };
112
137
  const remoteUri = await (0, prompt_1.promptOnce)({
113
- type: "list",
138
+ type: "autocomplete",
139
+ name: "remoteUri",
114
140
  message: "Which of the following repositories would you like to deploy?",
115
- choices,
141
+ source: searchRepos(repos),
116
142
  });
117
143
  return { remoteUri, connection: remoteUriToConnection[remoteUri] };
118
144
  }
@@ -223,3 +249,25 @@ async function listAppHostingConnections(projectId) {
223
249
  !conn.disabled);
224
250
  }
225
251
  exports.listAppHostingConnections = listAppHostingConnections;
252
+ async function fetchAllRepositories(projectId, connections) {
253
+ const repos = [];
254
+ const remoteUriToConnection = {};
255
+ const getNextPage = async (conn, pageToken = "") => {
256
+ const { location, id } = parseConnectionName(conn.name);
257
+ const resp = await gcb.fetchLinkableRepositories(projectId, location, id, pageToken);
258
+ if (resp.repositories && resp.repositories.length > 0) {
259
+ for (const repo of resp.repositories) {
260
+ repos.push(repo);
261
+ remoteUriToConnection[repo.remoteUri] = conn;
262
+ }
263
+ }
264
+ if (resp.nextPageToken) {
265
+ await getNextPage(conn, resp.nextPageToken);
266
+ }
267
+ };
268
+ for (const conn of connections) {
269
+ await getNextPage(conn);
270
+ }
271
+ return { repos, remoteUriToConnection };
272
+ }
273
+ exports.fetchAllRepositories = fetchAllRepositories;