firebase-tools-with-isolate 13.16.0 → 13.26.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 (220) hide show
  1. package/lib/api.js +3 -1
  2. package/lib/apiv2.js +10 -3
  3. package/lib/appdistribution/client.js +62 -8
  4. package/lib/appdistribution/distribution.js +1 -1
  5. package/lib/apphosting/backend.js +299 -0
  6. package/lib/apphosting/config.js +31 -8
  7. package/lib/apphosting/githubConnections.js +70 -22
  8. package/lib/apphosting/index.js +3 -312
  9. package/lib/apphosting/rollout.js +138 -0
  10. package/lib/apphosting/secrets/index.js +70 -5
  11. package/lib/apphosting/utils.js +41 -0
  12. package/lib/apphosting/yaml.js +82 -0
  13. package/lib/archiveDirectory.js +1 -1
  14. package/lib/auth.js +31 -5
  15. package/lib/bin/firebase.js +2 -2
  16. package/lib/command.js +18 -4
  17. package/lib/commands/appdistribution-distribute.js +4 -4
  18. package/lib/commands/{appdistribution-group-create.js → appdistribution-groups-create.js} +2 -1
  19. package/lib/commands/{appdistribution-group-delete.js → appdistribution-groups-delete.js} +3 -2
  20. package/lib/commands/appdistribution-groups-list.js +55 -0
  21. package/lib/commands/appdistribution-testers-list.js +52 -0
  22. package/lib/commands/appdistribution-testers-remove.js +1 -1
  23. package/lib/commands/apphosting-backends-create.js +4 -4
  24. package/lib/commands/apphosting-backends-delete.js +7 -15
  25. package/lib/commands/apphosting-backends-get.js +1 -1
  26. package/lib/commands/apphosting-config-export.js +51 -0
  27. package/lib/commands/apphosting-repos-create.js +23 -0
  28. package/lib/commands/apphosting-rollouts-create.js +14 -15
  29. package/lib/commands/apphosting-secrets-grantaccess.js +2 -2
  30. package/lib/commands/database-import.js +4 -2
  31. package/lib/commands/database-push.js +4 -2
  32. package/lib/commands/database-set.js +4 -2
  33. package/lib/commands/database-settings-get.js +1 -1
  34. package/lib/commands/database-settings-set.js +1 -1
  35. package/lib/commands/dataconnect-sdk-generate.js +4 -1
  36. package/lib/commands/dataconnect-services-list.js +4 -3
  37. package/lib/commands/dataconnect-sql-diff.js +1 -1
  38. package/lib/commands/dataconnect-sql-grant.js +37 -0
  39. package/lib/commands/dataconnect-sql-migrate.js +1 -1
  40. package/lib/commands/dataconnect-sql-shell.js +115 -0
  41. package/lib/commands/deploy.js +2 -0
  42. package/lib/commands/emulators-start.js +4 -1
  43. package/lib/commands/ext-dev-init.js +2 -2
  44. package/lib/commands/ext-dev-list.js +1 -1
  45. package/lib/commands/ext-dev-register.js +2 -2
  46. package/lib/commands/ext-dev-upload.js +2 -2
  47. package/lib/commands/ext-dev-usage.js +2 -2
  48. package/lib/commands/ext-info.js +3 -1
  49. package/lib/commands/ext-install.js +2 -2
  50. package/lib/commands/ext-sdk-install.js +88 -0
  51. package/lib/commands/ext.js +1 -0
  52. package/lib/commands/firestore-databases-restore.js +39 -1
  53. package/lib/commands/functions-secrets-access.js +2 -4
  54. package/lib/commands/index.js +15 -2
  55. package/lib/commands/init.js +25 -15
  56. package/lib/commands/setup-emulators-dataconnect.js +0 -13
  57. package/lib/commands/use.js +1 -1
  58. package/lib/config.js +14 -4
  59. package/lib/crashlytics/buildToolsJarHelper.js +2 -2
  60. package/lib/dataconnect/client.js +1 -1
  61. package/lib/dataconnect/dataplaneClient.js +12 -9
  62. package/lib/dataconnect/ensureApis.js +6 -1
  63. package/lib/dataconnect/fileUtils.js +15 -39
  64. package/lib/dataconnect/freeTrial.js +45 -9
  65. package/lib/dataconnect/load.js +3 -1
  66. package/lib/dataconnect/provisionCloudSql.js +39 -26
  67. package/lib/dataconnect/schemaMigration.js +215 -74
  68. package/lib/dataconnect/types.js +4 -1
  69. package/lib/dataconnect/webhook.js +32 -0
  70. package/lib/deploy/dataconnect/deploy.js +18 -15
  71. package/lib/deploy/dataconnect/prepare.js +41 -0
  72. package/lib/deploy/dataconnect/release.js +16 -7
  73. package/lib/deploy/extensions/deploy.js +3 -1
  74. package/lib/deploy/extensions/deploymentSummary.js +7 -3
  75. package/lib/deploy/extensions/planner.js +44 -5
  76. package/lib/deploy/extensions/prepare.js +45 -73
  77. package/lib/deploy/extensions/release.js +11 -10
  78. package/lib/deploy/extensions/tasks.js +32 -21
  79. package/lib/deploy/firestore/prepare.js +9 -0
  80. package/lib/deploy/firestore/release.js +3 -6
  81. package/lib/deploy/functions/checkIam.js +7 -2
  82. package/lib/deploy/functions/ensure.js +11 -3
  83. package/lib/deploy/functions/prepare.js +10 -2
  84. package/lib/deploy/functions/release/planner.js +2 -1
  85. package/lib/deploy/functions/runtimes/discovery/index.js +6 -2
  86. package/lib/deploy/functions/runtimes/node/index.js +5 -0
  87. package/lib/deploy/functions/services/auth.js +34 -3
  88. package/lib/deploy/functions/services/index.js +2 -0
  89. package/lib/deploy/index.js +8 -5
  90. package/lib/deploy/lifecycleHooks.js +2 -1
  91. package/lib/emulator/apphosting/config.js +27 -0
  92. package/lib/emulator/apphosting/index.js +38 -0
  93. package/lib/emulator/apphosting/serve.js +50 -0
  94. package/lib/emulator/apphosting/utils.js +18 -0
  95. package/lib/emulator/auth/handlers.js +27 -0
  96. package/lib/emulator/auth/operations.js +41 -2
  97. package/lib/emulator/auth/state.js +2 -1
  98. package/lib/emulator/commandUtils.js +8 -3
  99. package/lib/emulator/constants.js +4 -1
  100. package/lib/emulator/controller.js +48 -5
  101. package/lib/emulator/dataconnect/pg-gateway/auth/base-auth-flow.js +11 -0
  102. package/lib/emulator/dataconnect/pg-gateway/auth/cert.js +58 -0
  103. package/lib/emulator/dataconnect/pg-gateway/auth/index.js +22 -0
  104. package/lib/emulator/dataconnect/pg-gateway/auth/md5.js +124 -0
  105. package/lib/emulator/dataconnect/pg-gateway/auth/password.js +54 -0
  106. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/sasl-mechanism.js +34 -0
  107. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/scram-sha-256.js +270 -0
  108. package/lib/emulator/dataconnect/pg-gateway/auth/trust.js +2 -0
  109. package/lib/emulator/dataconnect/pg-gateway/backend-error.js +75 -0
  110. package/lib/emulator/dataconnect/pg-gateway/buffer-reader.js +54 -0
  111. package/lib/emulator/dataconnect/pg-gateway/buffer-writer.js +79 -0
  112. package/lib/emulator/dataconnect/pg-gateway/connection.js +315 -0
  113. package/lib/emulator/dataconnect/pg-gateway/connection.types.js +8 -0
  114. package/lib/emulator/dataconnect/pg-gateway/crypto.js +40 -0
  115. package/lib/emulator/dataconnect/pg-gateway/duplex.js +53 -0
  116. package/lib/emulator/dataconnect/pg-gateway/index.js +27 -0
  117. package/lib/emulator/dataconnect/pg-gateway/message-buffer.js +82 -0
  118. package/lib/emulator/dataconnect/pg-gateway/message-codes.js +52 -0
  119. package/lib/emulator/dataconnect/pg-gateway/platforms/node/index.js +16 -0
  120. package/lib/emulator/dataconnect/pg-gateway/polyfills/readable-stream-async-iterator.js +35 -0
  121. package/lib/emulator/dataconnect/pg-gateway/utils.js +40 -0
  122. package/lib/emulator/dataconnect/pgliteServer.js +95 -0
  123. package/lib/emulator/dataconnectEmulator.js +58 -75
  124. package/lib/emulator/dataconnectToolkitController.js +44 -0
  125. package/lib/emulator/downloadableEmulators.js +27 -16
  126. package/lib/emulator/emulatorLogger.js +3 -0
  127. package/lib/emulator/eventarcEmulator.js +1 -1
  128. package/lib/emulator/extensionsEmulator.js +38 -6
  129. package/lib/emulator/functionsEmulator.js +85 -41
  130. package/lib/emulator/functionsEmulatorShared.js +2 -1
  131. package/lib/emulator/functionsRuntimeWorker.js +2 -1
  132. package/lib/emulator/hub.js +13 -9
  133. package/lib/emulator/hubExport.js +10 -3
  134. package/lib/emulator/loggingEmulator.js +2 -2
  135. package/lib/emulator/portUtils.js +10 -11
  136. package/lib/emulator/registry.js +1 -0
  137. package/lib/emulator/storage/persistence.js +2 -2
  138. package/lib/emulator/storage/rules/runtime.js +1 -1
  139. package/lib/emulator/tasksEmulator.js +5 -2
  140. package/lib/emulator/types.js +3 -0
  141. package/lib/emulator/ui.js +51 -25
  142. package/lib/error.js +31 -1
  143. package/lib/experiments.js +5 -0
  144. package/lib/extensions/emulator/triggerHelper.js +1 -1
  145. package/lib/extensions/extensionsApi.js +14 -10
  146. package/lib/extensions/extensionsHelper.js +15 -6
  147. package/lib/extensions/localHelper.js +31 -0
  148. package/lib/extensions/runtimes/common.js +179 -39
  149. package/lib/extensions/runtimes/node.js +401 -0
  150. package/lib/extensions/types.js +25 -14
  151. package/lib/extensions/warnings.js +5 -2
  152. package/lib/firestore/api.js +2 -1
  153. package/lib/firestore/checkDatabaseType.js +10 -3
  154. package/lib/firestore/delete.js +11 -0
  155. package/lib/firestore/options.js +7 -0
  156. package/lib/frameworks/angular/index.js +15 -3
  157. package/lib/frameworks/constants.js +1 -1
  158. package/lib/frameworks/flutter/index.js +6 -6
  159. package/lib/frameworks/flutter/utils.js +34 -1
  160. package/lib/frameworks/next/index.js +10 -2
  161. package/lib/frameworks/next/utils.js +8 -5
  162. package/lib/frameworks/vite/index.js +2 -2
  163. package/lib/fsutils.js +13 -1
  164. package/lib/functions/constants.js +4 -0
  165. package/lib/functions/events/v1.js +9 -2
  166. package/lib/gcp/apphosting.js +1 -1
  167. package/lib/gcp/cloudmonitoring.js +3 -3
  168. package/lib/gcp/cloudsql/cloudsqladmin.js +32 -20
  169. package/lib/gcp/cloudsql/connect.js +49 -37
  170. package/lib/gcp/cloudsql/interactive.js +49 -0
  171. package/lib/gcp/cloudsql/permissions.js +165 -0
  172. package/lib/gcp/devConnect.js +38 -1
  173. package/lib/gcp/firestore.js +5 -1
  174. package/lib/gcp/secretManager.js +12 -5
  175. package/lib/getProjectNumber.js +1 -1
  176. package/lib/init/features/apphosting.js +15 -0
  177. package/lib/init/features/dataconnect/index.js +159 -120
  178. package/lib/init/features/dataconnect/sdk.js +77 -84
  179. package/lib/init/features/emulators.js +2 -15
  180. package/lib/init/features/firestore/index.js +20 -1
  181. package/lib/init/features/firestore/indexes.js +4 -4
  182. package/lib/init/features/genkit/index.js +444 -0
  183. package/lib/init/features/hosting/index.js +2 -2
  184. package/lib/init/features/index.js +1 -1
  185. package/lib/init/features/project.js +6 -6
  186. package/lib/init/features/storage.js +0 -2
  187. package/lib/init/index.js +1 -0
  188. package/lib/init/spawn.js +23 -2
  189. package/lib/logger.js +2 -2
  190. package/lib/management/projects.js +24 -4
  191. package/lib/projectUtils.js +1 -1
  192. package/lib/prompt.js +1 -1
  193. package/lib/rc.js +1 -8
  194. package/lib/requireAuth.js +19 -5
  195. package/lib/requireDatabaseInstance.js +1 -1
  196. package/lib/requirePermissions.js +1 -1
  197. package/lib/responseToError.js +5 -2
  198. package/lib/rulesDeploy.js +1 -1
  199. package/lib/templates.js +2 -2
  200. package/lib/utils.js +16 -11
  201. package/lib/vsCodeUtils.js +8 -0
  202. package/package.json +7 -6
  203. package/schema/connector-yaml.json +57 -17
  204. package/schema/firebase-config.json +24 -0
  205. package/templates/extensions/javascript/package.lint.json +2 -2
  206. package/templates/extensions/javascript/package.nolint.json +2 -2
  207. package/templates/extensions/typescript/package.lint.json +2 -2
  208. package/templates/extensions/typescript/package.nolint.json +2 -2
  209. package/templates/genkit/firebase.0.9.0.template +57 -0
  210. package/templates/init/apphosting/apphosting.yaml +23 -0
  211. package/templates/init/dataconnect/connector.yaml +0 -1
  212. package/templates/init/dataconnect/dataconnect-fdccompatiblemode.yaml +12 -0
  213. package/templates/init/dataconnect/dataconnect.yaml +1 -1
  214. package/templates/init/dataconnect/queries.gql +1 -2
  215. package/templates/init/functions/javascript/package.lint.json +2 -2
  216. package/templates/init/functions/javascript/package.nolint.json +2 -2
  217. package/templates/init/functions/typescript/package.lint.json +2 -2
  218. package/templates/init/functions/typescript/package.nolint.json +2 -2
  219. package/lib/ensureCloudResourceLocation.js +0 -12
  220. package/lib/init/features/genkit.js +0 -53
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchRepositoryCloneUris = exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.ensureSecretManagerAdminGrant = exports.promptGitHubBranch = exports.getOrCreateOauthConnection = exports.listValidInstallations = exports.promptGitHubInstallation = exports.getConnectionForInstallation = exports.linkGitHubRepository = exports.generateRepositoryId = exports.extractRepoSlugFromUri = exports.parseConnectionName = void 0;
3
+ exports.getGitHubCommit = exports.getGitHubBranch = exports.fetchRepositoryCloneUris = exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.ensureSecretManagerAdminGrant = exports.promptGitHubBranch = exports.getOrCreateOauthConnection = exports.listValidInstallations = exports.promptGitHubInstallation = exports.getConnectionForInstallation = exports.linkGitHubRepository = exports.getOrCreateGithubConnectionWithSentinel = exports.generateRepositoryId = exports.extractRepoSlugFromUri = exports.parseConnectionName = void 0;
4
4
  const clc = require("colorette");
5
5
  const devConnect = require("../gcp/devConnect");
6
6
  const rm = require("../gcp/resourceManager");
@@ -12,6 +12,8 @@ const getProjectNumber_1 = require("../getProjectNumber");
12
12
  const api_1 = require("../api");
13
13
  const fuzzy = require("fuzzy");
14
14
  const inquirer = require("inquirer");
15
+ const apiv2_1 = require("../apiv2");
16
+ const githubApiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.githubApiOrigin)(), auth: false });
15
17
  const APPHOSTING_CONN_PATTERN = /.+\/apphosting-github-conn-.+$/;
16
18
  const APPHOSTING_OAUTH_CONN_NAME = "firebase-app-hosting-github-oauth";
17
19
  const CONNECTION_NAME_REGEX = /^projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/connections\/(?<id>[^\/]+)$/;
@@ -52,8 +54,20 @@ function generateConnectionId() {
52
54
  }
53
55
  const ADD_ACCOUNT_CHOICE = "@ADD_ACCOUNT";
54
56
  const MANAGE_INSTALLATION_CHOICE = "@MANAGE_INSTALLATION";
55
- async function linkGitHubRepository(projectId, location) {
57
+ async function getOrCreateGithubConnectionWithSentinel(projectId, location, createConnectionId) {
56
58
  utils.logBullet(clc.bold(`${clc.yellow("===")} Import a GitHub repository`));
59
+ if (createConnectionId) {
60
+ try {
61
+ const connection = await devConnect.getConnection(projectId, location, createConnectionId);
62
+ utils.logBullet(`Reusing existing connection ${createConnectionId}`);
63
+ return connection;
64
+ }
65
+ catch (err) {
66
+ if (err.status !== 404) {
67
+ throw err;
68
+ }
69
+ }
70
+ }
57
71
  const oauthConn = await getOrCreateOauthConnection(projectId, location);
58
72
  let installationId = await promptGitHubInstallation(projectId, location, oauthConn);
59
73
  while (installationId === ADD_ACCOUNT_CHOICE) {
@@ -67,21 +81,34 @@ async function linkGitHubRepository(projectId, location) {
67
81
  });
68
82
  installationId = await promptGitHubInstallation(projectId, location, oauthConn);
69
83
  }
70
- let connectionMatchingInstallation = await getConnectionForInstallation(projectId, location, installationId);
71
- if (!connectionMatchingInstallation) {
72
- connectionMatchingInstallation = await createFullyInstalledConnection(projectId, location, generateConnectionId(), oauthConn, installationId);
84
+ const connectionMatchingInstallation = await getConnectionForInstallation(projectId, location, installationId);
85
+ if (connectionMatchingInstallation) {
86
+ const { id: matchingConnectionId } = parseConnectionName(connectionMatchingInstallation.name);
87
+ if (!createConnectionId) {
88
+ utils.logBullet(`Reusing matching connection ${matchingConnectionId}`);
89
+ return connectionMatchingInstallation;
90
+ }
91
+ }
92
+ if (!createConnectionId) {
93
+ createConnectionId = generateConnectionId();
73
94
  }
95
+ const connection = await createFullyInstalledConnection(projectId, location, createConnectionId, oauthConn, installationId);
96
+ return connection;
97
+ }
98
+ exports.getOrCreateGithubConnectionWithSentinel = getOrCreateGithubConnectionWithSentinel;
99
+ async function linkGitHubRepository(projectId, location, createConnectionId) {
100
+ const connection = await getOrCreateGithubConnectionWithSentinel(projectId, location, createConnectionId);
74
101
  let repoCloneUri;
75
102
  do {
76
103
  if (repoCloneUri === MANAGE_INSTALLATION_CHOICE) {
77
- await manageInstallation(connectionMatchingInstallation);
104
+ await manageInstallation(connection);
78
105
  }
79
- repoCloneUri = await promptCloneUri(projectId, connectionMatchingInstallation);
106
+ repoCloneUri = await promptCloneUri(projectId, connection);
80
107
  } while (repoCloneUri === MANAGE_INSTALLATION_CHOICE);
81
- const { id: connectionId } = parseConnectionName(connectionMatchingInstallation.name);
108
+ const { id: connectionId } = parseConnectionName(connection.name);
82
109
  await getOrCreateConnection(projectId, location, connectionId, {
83
- authorizerCredential: connectionMatchingInstallation.githubConfig?.authorizerCredential,
84
- appInstallationId: connectionMatchingInstallation.githubConfig?.appInstallationId,
110
+ authorizerCredential: connection.githubConfig?.authorizerCredential,
111
+ appInstallationId: connection.githubConfig?.appInstallationId,
85
112
  });
86
113
  const repo = await getOrCreateRepository(projectId, location, connectionId, repoCloneUri);
87
114
  return repo;
@@ -233,18 +260,23 @@ async function promptCloneUri(projectId, connection) {
233
260
  }
234
261
  async function promptGitHubBranch(repoLink) {
235
262
  const branches = await devConnect.listAllBranches(repoLink.name);
236
- while (true) {
237
- const branch = await (0, prompt_1.promptOnce)({
238
- name: "branch",
239
- type: "input",
240
- default: "main",
241
- message: "Pick a branch for continuous deployment",
242
- });
243
- if (branches.has(branch)) {
244
- return branch;
245
- }
246
- utils.logWarning(`The branch "${branch}" does not exist on "${extractRepoSlugFromUri(repoLink.cloneUri)}". Please enter a valid branch for this repo.`);
247
- }
263
+ const branch = await (0, prompt_1.promptOnce)({
264
+ type: "autocomplete",
265
+ name: "branch",
266
+ message: "Pick a branch for continuous deployment",
267
+ source: (_, input = "") => {
268
+ return new Promise((resolve) => resolve([
269
+ ...fuzzy.filter(input, Array.from(branches)).map((result) => {
270
+ return {
271
+ name: result.original,
272
+ value: result.original,
273
+ };
274
+ }),
275
+ ]));
276
+ },
277
+ });
278
+ utils.logWarning(`The branch "${branch}" does not exist on "${extractRepoSlugFromUri(repoLink.cloneUri) ?? ""}". Please enter a valid branch for this repo.`);
279
+ return branch;
248
280
  }
249
281
  exports.promptGitHubBranch = promptGitHubBranch;
250
282
  async function ensureSecretManagerAdminGrant(projectId) {
@@ -349,3 +381,19 @@ async function fetchRepositoryCloneUris(projectId, connection) {
349
381
  return cloneUris;
350
382
  }
351
383
  exports.fetchRepositoryCloneUris = fetchRepositoryCloneUris;
384
+ async function getGitHubBranch(owner, repo, branch, readToken) {
385
+ const headers = { Authorization: `Bearer ${readToken}`, "User-Agent": "Firebase CLI" };
386
+ const { body } = await githubApiClient.get(`/repos/${owner}/${repo}/branches/${branch}`, {
387
+ headers,
388
+ });
389
+ return body;
390
+ }
391
+ exports.getGitHubBranch = getGitHubBranch;
392
+ async function getGitHubCommit(owner, repo, ref, readToken) {
393
+ const headers = { Authorization: `Bearer ${readToken}`, "User-Agent": "Firebase CLI" };
394
+ const { body } = await githubApiClient.get(`/repos/${owner}/${repo}/commits/${ref}`, {
395
+ headers,
396
+ });
397
+ return body;
398
+ }
399
+ exports.getGitHubCommit = getGitHubCommit;
@@ -1,314 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getBackendForAmbiguousLocation = exports.promptLocation = exports.deleteBackendAndPoll = exports.orchestrateRollout = exports.setDefaultTrafficPolicy = exports.createBackend = exports.ensureAppHostingComputeServiceAccount = exports.doSetup = void 0;
4
- const clc = require("colorette");
5
- const poller = require("../operation-poller");
6
- const apphosting = require("../gcp/apphosting");
7
- const githubConnections = require("./githubConnections");
8
- const utils_1 = require("../utils");
9
- const api_1 = require("../api");
10
- const apphosting_1 = require("../gcp/apphosting");
11
- const resourceManager_1 = require("../gcp/resourceManager");
12
- const iam = require("../gcp/iam");
13
- const error_1 = require("../error");
14
- const prompt_1 = require("../prompt");
15
- const constants_1 = require("./constants");
16
- const ensureApiEnabled_1 = require("../ensureApiEnabled");
17
- const deploymentTool = require("../deploymentTool");
18
- const app_1 = require("./app");
19
- const ora = require("ora");
20
- const node_fetch_1 = require("node-fetch");
21
- const DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME = "firebase-app-hosting-compute";
22
- const apphostingPollerOptions = {
23
- apiOrigin: (0, api_1.apphostingOrigin)(),
24
- apiVersion: apphosting_1.API_VERSION,
25
- masterTimeout: 25 * 60 * 1000,
26
- maxBackoff: 10000,
27
- };
28
- async function tlsReady(url) {
29
- try {
30
- await (0, node_fetch_1.default)(url);
31
- return true;
32
- }
33
- catch (err) {
34
- const maybeNodeError = err;
35
- if (/HANDSHAKE_FAILURE/.test(maybeNodeError?.cause?.code)) {
36
- return false;
37
- }
38
- return true;
39
- }
40
- }
41
- async function awaitTlsReady(url) {
42
- let ready;
43
- do {
44
- ready = await tlsReady(url);
45
- if (!ready) {
46
- await (0, utils_1.sleep)(1000);
47
- }
48
- } while (!ready);
49
- }
50
- async function doSetup(projectId, webAppName, location, serviceAccount) {
51
- await Promise.all([
52
- (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.developerConnectOrigin)(), "apphosting", true),
53
- (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.cloudbuildOrigin)(), "apphosting", true),
54
- (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.secretManagerOrigin)(), "apphosting", true),
55
- (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.cloudRunApiOrigin)(), "apphosting", true),
56
- (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.artifactRegistryDomain)(), "apphosting", true),
57
- (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.iamOrigin)(), "apphosting", true),
58
- ]);
59
- await ensureAppHostingComputeServiceAccount(projectId, serviceAccount);
60
- const allowedLocations = (await apphosting.listLocations(projectId)).map((loc) => loc.locationId);
61
- if (location) {
62
- if (!allowedLocations.includes(location)) {
63
- throw new error_1.FirebaseError(`Invalid location ${location}. Valid choices are ${allowedLocations.join(", ")}`);
64
- }
65
- }
66
- location =
67
- location || (await promptLocation(projectId, "Select a location to host your backend:\n"));
68
- const gitRepositoryLink = await githubConnections.linkGitHubRepository(projectId, location);
69
- const rootDir = await (0, prompt_1.promptOnce)({
70
- name: "rootDir",
71
- type: "input",
72
- default: "/",
73
- message: "Specify your app's root directory relative to your repository",
74
- });
75
- const branch = await githubConnections.promptGitHubBranch(gitRepositoryLink);
76
- (0, utils_1.logSuccess)(`Repo linked successfully!\n`);
77
- (0, utils_1.logBullet)(`${clc.yellow("===")} Set up your backend`);
78
- const backendId = await promptNewBackendId(projectId, location, {
79
- name: "backendId",
80
- type: "input",
81
- default: "my-web-app",
82
- message: "Provide a name for your backend [1-30 characters]",
83
- });
84
- (0, utils_1.logSuccess)(`Name set to ${backendId}\n`);
85
- const webApp = await app_1.webApps.getOrCreateWebApp(projectId, webAppName, backendId);
86
- if (!webApp) {
87
- (0, utils_1.logWarning)(`Firebase web app not set`);
88
- }
89
- const createBackendSpinner = ora("Creating your new backend...").start();
90
- const backend = await createBackend(projectId, location, backendId, gitRepositoryLink, serviceAccount, webApp?.id, rootDir);
91
- createBackendSpinner.succeed(`Successfully created backend!\n\t${backend.name}\n`);
92
- await setDefaultTrafficPolicy(projectId, location, backendId, branch);
93
- const confirmRollout = await (0, prompt_1.promptOnce)({
94
- type: "confirm",
95
- name: "rollout",
96
- default: true,
97
- message: "Do you want to deploy now?",
98
- });
99
- if (!confirmRollout) {
100
- (0, utils_1.logSuccess)(`Your backend will be deployed at:\n\thttps://${backend.uri}`);
101
- return;
102
- }
103
- const url = `https://${backend.uri}`;
104
- (0, utils_1.logBullet)(`You may also track this rollout at:\n\t${(0, api_1.consoleOrigin)()}/project/${projectId}/apphosting`);
105
- const createRolloutSpinner = ora("Starting a new rollout; this may take a few minutes. It's safe to exit now.").start();
106
- await orchestrateRollout(projectId, location, backendId, {
107
- source: {
108
- codebase: {
109
- branch,
110
- },
111
- },
112
- });
113
- createRolloutSpinner.succeed("Rollout complete");
114
- if (!(await tlsReady(url))) {
115
- const tlsSpinner = ora("Finalizing your backend's TLS certificate; this may take a few minutes.").start();
116
- await awaitTlsReady(url);
117
- tlsSpinner.succeed("TLS certificate ready");
118
- }
119
- (0, utils_1.logSuccess)(`Your backend is now deployed at:\n\thttps://${backend.uri}`);
120
- }
121
- exports.doSetup = doSetup;
122
- async function ensureAppHostingComputeServiceAccount(projectId, serviceAccount) {
123
- const sa = serviceAccount || defaultComputeServiceAccountEmail(projectId);
124
- const name = `projects/${projectId}/serviceAccounts/${sa}`;
125
- try {
126
- await iam.testResourceIamPermissions((0, api_1.iamOrigin)(), "v1", name, ["iam.serviceAccounts.actAs"], `projects/${projectId}`);
127
- }
128
- catch (err) {
129
- if (!(err instanceof error_1.FirebaseError)) {
130
- throw err;
131
- }
132
- if (err.status === 404) {
133
- await provisionDefaultComputeServiceAccount(projectId);
134
- }
135
- else if (err.status === 403) {
136
- throw new error_1.FirebaseError(`Failed to create backend due to missing delegation permissions for ${sa}. Make sure you have the iam.serviceAccounts.actAs permission.`, { original: err });
137
- }
138
- }
139
- }
140
- exports.ensureAppHostingComputeServiceAccount = ensureAppHostingComputeServiceAccount;
141
- async function promptNewBackendId(projectId, location, prompt) {
142
- while (true) {
143
- const backendId = await (0, prompt_1.promptOnce)(prompt);
144
- try {
145
- await apphosting.getBackend(projectId, location, backendId);
146
- }
147
- catch (err) {
148
- if (err.status === 404) {
149
- return backendId;
150
- }
151
- throw new error_1.FirebaseError(`Failed to check if backend with id ${backendId} already exists in ${location}`, { original: err });
152
- }
153
- (0, utils_1.logWarning)(`Backend with id ${backendId} already exists in ${location}`);
154
- }
155
- }
156
- function defaultComputeServiceAccountEmail(projectId) {
157
- return `${DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME}@${projectId}.iam.gserviceaccount.com`;
158
- }
159
- async function createBackend(projectId, location, backendId, repository, serviceAccount, webAppId, rootDir = "/") {
160
- const defaultServiceAccount = defaultComputeServiceAccountEmail(projectId);
161
- const backendReqBody = {
162
- servingLocality: "GLOBAL_ACCESS",
163
- codebase: {
164
- repository: `${repository.name}`,
165
- rootDirectory: rootDir,
166
- },
167
- labels: deploymentTool.labels(),
168
- serviceAccount: serviceAccount || defaultServiceAccount,
169
- appId: webAppId,
170
- };
171
- async function createBackendAndPoll() {
172
- const op = await apphosting.createBackend(projectId, location, backendReqBody, backendId);
173
- return await poller.pollOperation({
174
- ...apphostingPollerOptions,
175
- pollerName: `create-${projectId}-${location}-${backendId}`,
176
- operationResourceName: op.name,
177
- });
178
- }
179
- return await createBackendAndPoll();
180
- }
181
- exports.createBackend = createBackend;
182
- async function provisionDefaultComputeServiceAccount(projectId) {
183
- try {
184
- await iam.createServiceAccount(projectId, DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME, "Default service account used to run builds and deploys for Firebase App Hosting", "Firebase App Hosting compute service account");
185
- }
186
- catch (err) {
187
- if (err.status !== 409) {
188
- throw err;
189
- }
190
- }
191
- await (0, resourceManager_1.addServiceAccountToRoles)(projectId, defaultComputeServiceAccountEmail(projectId), [
192
- "roles/firebaseapphosting.computeRunner",
193
- "roles/firebase.sdkAdminServiceAgent",
194
- "roles/developerconnect.readTokenAccessor",
195
- ], true);
196
- }
197
- async function setDefaultTrafficPolicy(projectId, location, backendId, codebaseBranch) {
198
- const traffic = {
199
- rolloutPolicy: {
200
- codebaseBranch: codebaseBranch,
201
- stages: [
202
- {
203
- progression: "IMMEDIATE",
204
- targetPercent: 100,
205
- },
206
- ],
207
- },
208
- };
209
- const op = await apphosting.updateTraffic(projectId, location, backendId, traffic);
210
- await poller.pollOperation({
211
- ...apphostingPollerOptions,
212
- pollerName: `updateTraffic-${projectId}-${location}-${backendId}`,
213
- operationResourceName: op.name,
214
- });
215
- }
216
- exports.setDefaultTrafficPolicy = setDefaultTrafficPolicy;
217
- async function orchestrateRollout(projectId, location, backendId, buildInput) {
218
- const buildId = await apphosting.getNextRolloutId(projectId, location, backendId, 1);
219
- const buildOp = await apphosting.createBuild(projectId, location, backendId, buildId, buildInput);
220
- const rolloutBody = {
221
- build: `projects/${projectId}/locations/${location}/backends/${backendId}/builds/${buildId}`,
222
- };
223
- let tries = 0;
224
- let done = false;
225
- while (!done) {
226
- tries++;
227
- try {
228
- const validateOnly = true;
229
- await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody, validateOnly);
230
- done = true;
231
- }
232
- catch (err) {
233
- if (err instanceof error_1.FirebaseError && err.status === 400) {
234
- if (tries >= 5) {
235
- throw err;
236
- }
237
- await (0, utils_1.sleep)(1000);
238
- }
239
- else {
240
- throw err;
241
- }
242
- }
243
- }
244
- const rolloutOp = await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody);
245
- const rolloutPoll = poller.pollOperation({
246
- ...apphostingPollerOptions,
247
- pollerName: `create-${projectId}-${location}-backend-${backendId}-rollout-${buildId}`,
248
- operationResourceName: rolloutOp.name,
249
- });
250
- const buildPoll = poller.pollOperation({
251
- ...apphostingPollerOptions,
252
- pollerName: `create-${projectId}-${location}-backend-${backendId}-build-${buildId}`,
253
- operationResourceName: buildOp.name,
254
- });
255
- const [rollout, build] = await Promise.all([rolloutPoll, buildPoll]);
256
- if (build.state !== "READY") {
257
- if (!build.buildLogsUri) {
258
- throw new error_1.FirebaseError("Failed to build your app, but failed to get build logs as well. " +
259
- "This is an internal error and should be reported");
260
- }
261
- throw new error_1.FirebaseError(`Failed to build your app. Please inspect the build logs at ${build.buildLogsUri}.`, { children: [build.error] });
262
- }
263
- return { rollout, build };
264
- }
265
- exports.orchestrateRollout = orchestrateRollout;
266
- async function deleteBackendAndPoll(projectId, location, backendId) {
267
- const op = await apphosting.deleteBackend(projectId, location, backendId);
268
- await poller.pollOperation({
269
- ...apphostingPollerOptions,
270
- pollerName: `delete-${projectId}-${location}-${backendId}`,
271
- operationResourceName: op.name,
272
- });
273
- }
274
- exports.deleteBackendAndPoll = deleteBackendAndPoll;
275
- async function promptLocation(projectId, prompt = "Please select a location:") {
276
- const allowedLocations = (await apphosting.listLocations(projectId)).map((loc) => loc.locationId);
277
- if (allowedLocations.length === 1) {
278
- return allowedLocations[0];
279
- }
280
- const location = (await (0, prompt_1.promptOnce)({
281
- name: "location",
282
- type: "list",
283
- default: constants_1.DEFAULT_LOCATION,
284
- message: prompt,
285
- choices: allowedLocations,
286
- }));
287
- (0, utils_1.logSuccess)(`Location set to ${location}.\n`);
288
- return location;
289
- }
290
- exports.promptLocation = promptLocation;
291
- async function getBackendForAmbiguousLocation(projectId, backendId, locationDisambugationPrompt) {
292
- let { unreachable, backends } = await apphosting.listBackends(projectId, "-");
293
- if (unreachable && unreachable.length !== 0) {
294
- (0, utils_1.logWarning)(`The following locations are currently unreachable: ${unreachable}.\n` +
295
- "If your backend is in one of these regions, please try again later.");
296
- }
297
- backends = backends.filter((backend) => apphosting.parseBackendName(backend.name).id === backendId);
298
- if (backends.length === 0) {
299
- throw new error_1.FirebaseError(`No backend named "${backendId}" found.`);
300
- }
301
- if (backends.length === 1) {
302
- return backends[0];
303
- }
304
- const backendsByLocation = new Map();
305
- backends.forEach((backend) => backendsByLocation.set(apphosting.parseBackendName(backend.name).location, backend));
306
- const location = await (0, prompt_1.promptOnce)({
307
- name: "location",
308
- type: "list",
309
- message: locationDisambugationPrompt,
310
- choices: [...backendsByLocation.keys()],
311
- });
312
- return backendsByLocation.get(location);
313
- }
314
- exports.getBackendForAmbiguousLocation = getBackendForAmbiguousLocation;
3
+ exports.setupBackend = void 0;
4
+ const backend_1 = require("./backend");
5
+ Object.defineProperty(exports, "setupBackend", { enumerable: true, get: function () { return backend_1.doSetup; } });
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.orchestrateRollout = exports.createRollout = void 0;
4
+ const apphosting = require("../gcp/apphosting");
5
+ const error_1 = require("../error");
6
+ const ora = require("ora");
7
+ const devConnect_1 = require("../gcp/devConnect");
8
+ const githubConnections_1 = require("../apphosting/githubConnections");
9
+ const poller = require("../operation-poller");
10
+ const utils_1 = require("../utils");
11
+ const api_1 = require("../api");
12
+ const backend_1 = require("./backend");
13
+ const apphostingPollerOptions = {
14
+ apiOrigin: (0, api_1.apphostingOrigin)(),
15
+ apiVersion: apphosting.API_VERSION,
16
+ masterTimeout: 25 * 60 * 1000,
17
+ maxBackoff: 10000,
18
+ };
19
+ const GIT_COMMIT_SHA_REGEX = /^(?:[0-9a-f]{40}|[0-9a-f]{7})$/;
20
+ async function createRollout(backendId, projectId, location, branch, commit, force) {
21
+ let backend;
22
+ if (location === "-" || location === "") {
23
+ backend = await (0, backend_1.getBackendForAmbiguousLocation)(projectId, backendId, "Please select the location of the backend you'd like to roll out:", force);
24
+ location = apphosting.parseBackendName(backend.name).location;
25
+ }
26
+ else {
27
+ backend = await (0, backend_1.getBackendForLocation)(projectId, location, backendId);
28
+ }
29
+ if (!backend.codebase.repository) {
30
+ throw new error_1.FirebaseError(`Backend ${backendId} is misconfigured due to missing a connected repository. You can delete and recreate your backend using 'firebase apphosting:backends:delete' and 'firebase apphosting:backends:create'.`);
31
+ }
32
+ const { repoLink, owner, repo, readToken } = await (0, devConnect_1.getRepoDetailsFromBackend)(projectId, location, backend.codebase.repository);
33
+ let targetCommit;
34
+ if (branch) {
35
+ const branches = await (0, devConnect_1.listAllBranches)(repoLink.name);
36
+ if (!branches.has(branch)) {
37
+ throw new error_1.FirebaseError(`Unrecognized git branch ${branch}. Please double-check your branch name and try again.`);
38
+ }
39
+ const branchInfo = await (0, githubConnections_1.getGitHubBranch)(owner, repo, branch, readToken.token);
40
+ targetCommit = branchInfo.commit;
41
+ }
42
+ else if (commit) {
43
+ if (!GIT_COMMIT_SHA_REGEX.test(commit)) {
44
+ throw new error_1.FirebaseError(`Invalid git commit ${commit}. Must be a valid SHA1 hash.`);
45
+ }
46
+ try {
47
+ const commitInfo = await (0, githubConnections_1.getGitHubCommit)(owner, repo, commit, readToken.token);
48
+ targetCommit = commitInfo;
49
+ }
50
+ catch (err) {
51
+ if (err.status === 422) {
52
+ throw new error_1.FirebaseError(`Unrecognized git commit ${commit}. Please double-check your commit hash and try again.`);
53
+ }
54
+ throw err;
55
+ }
56
+ }
57
+ else {
58
+ if (force) {
59
+ throw new error_1.FirebaseError(`Failed to create rollout with --force option because no target branch or commit was specified. Please specify which branch or commit to roll out with the --git-branch or --git-commit flag.`);
60
+ }
61
+ branch = await (0, githubConnections_1.promptGitHubBranch)(repoLink);
62
+ const branchInfo = await (0, githubConnections_1.getGitHubBranch)(owner, repo, branch, readToken.token);
63
+ targetCommit = branchInfo.commit;
64
+ }
65
+ (0, utils_1.logBullet)(`You are about to deploy [${targetCommit.sha.substring(0, 7)}]: ${targetCommit.commit.message}`);
66
+ (0, utils_1.logBullet)(`You may also track this rollout at:\n\t${(0, api_1.consoleOrigin)()}/project/${projectId}/apphosting`);
67
+ const createRolloutSpinner = ora("Starting a new rollout; this may take a few minutes. It's safe to exit now.").start();
68
+ try {
69
+ await orchestrateRollout({
70
+ projectId,
71
+ location,
72
+ backendId,
73
+ buildInput: {
74
+ source: {
75
+ codebase: {
76
+ commit: targetCommit.sha,
77
+ },
78
+ },
79
+ },
80
+ });
81
+ }
82
+ catch (err) {
83
+ createRolloutSpinner.fail("Rollout failed.");
84
+ throw err;
85
+ }
86
+ createRolloutSpinner.succeed("Successfully created a new rollout!");
87
+ }
88
+ exports.createRollout = createRollout;
89
+ async function orchestrateRollout(args) {
90
+ const { projectId, location, backendId, buildInput, isFirstRollout } = args;
91
+ const buildId = await apphosting.getNextRolloutId(projectId, location, backendId, isFirstRollout ? 1 : undefined);
92
+ const buildOp = await apphosting.createBuild(projectId, location, backendId, buildId, buildInput);
93
+ const rolloutBody = {
94
+ build: `projects/${projectId}/locations/${location}/backends/${backendId}/builds/${buildId}`,
95
+ };
96
+ let tries = 0;
97
+ let done = false;
98
+ while (!done) {
99
+ tries++;
100
+ try {
101
+ const validateOnly = true;
102
+ await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody, validateOnly);
103
+ done = true;
104
+ }
105
+ catch (err) {
106
+ if (err instanceof error_1.FirebaseError && err.status === 400) {
107
+ if (tries >= 5) {
108
+ throw err;
109
+ }
110
+ await (0, utils_1.sleep)(1000);
111
+ }
112
+ else {
113
+ throw err;
114
+ }
115
+ }
116
+ }
117
+ const rolloutOp = await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody);
118
+ const rolloutPoll = poller.pollOperation({
119
+ ...apphostingPollerOptions,
120
+ pollerName: `create-${projectId}-${location}-backend-${backendId}-rollout-${buildId}`,
121
+ operationResourceName: rolloutOp.name,
122
+ });
123
+ const buildPoll = poller.pollOperation({
124
+ ...apphostingPollerOptions,
125
+ pollerName: `create-${projectId}-${location}-backend-${backendId}-build-${buildId}`,
126
+ operationResourceName: buildOp.name,
127
+ });
128
+ const [rollout, build] = await Promise.all([rolloutPoll, buildPoll]);
129
+ if (build.state !== "READY") {
130
+ if (!build.buildLogsUri) {
131
+ throw new error_1.FirebaseError("Failed to build your app, but failed to get build logs as well. " +
132
+ "This is an internal error and should be reported");
133
+ }
134
+ throw new error_1.FirebaseError(`Failed to build your app. Please inspect the build logs at ${build.buildLogsUri}.`, { children: [build.error] });
135
+ }
136
+ return { rollout, build };
137
+ }
138
+ exports.orchestrateRollout = orchestrateRollout;