firebase-tools 15.33.0 → 15.34.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 (58) hide show
  1. package/README.md +9 -0
  2. package/lib/apphosting/backend.js +1 -1
  3. package/lib/checkValidTargetFilters.js +1 -0
  4. package/lib/command.js +30 -23
  5. package/lib/commands/crashlytics-heapdumps-disable.js +26 -0
  6. package/lib/commands/crashlytics-heapdumps-enable.js +54 -0
  7. package/lib/commands/crashlytics-heapdumps-status.js +32 -0
  8. package/lib/commands/deploy.js +3 -0
  9. package/lib/commands/hosting-clone.js +49 -9
  10. package/lib/commands/index.js +9 -0
  11. package/lib/commands/init.js +7 -0
  12. package/lib/commands/run-services-update.js +16 -0
  13. package/lib/crashlytics/onboarding.js +2 -2
  14. package/lib/crashlytics/profilingManager.js +195 -0
  15. package/lib/deploy/apphosting/prepare.js +1 -0
  16. package/lib/deploy/auth/deploy.js +1 -1
  17. package/lib/deploy/auth/prepare.js +6 -7
  18. package/lib/deploy/firestore/prepare.js +5 -5
  19. package/lib/deploy/functions/release/executor.js +7 -3
  20. package/lib/deploy/functions/release/fabricator.js +41 -9
  21. package/lib/deploy/functions/release/sourceTokenScraper.js +1 -1
  22. package/lib/deploy/index.js +5 -0
  23. package/lib/deploy/run/args.js +2 -0
  24. package/lib/deploy/run/buildEnv.js +72 -0
  25. package/lib/deploy/run/deploy.js +214 -0
  26. package/lib/deploy/run/index.js +23 -0
  27. package/lib/deploy/run/prepare.js +47 -0
  28. package/lib/deploy/run/prereqs.js +32 -0
  29. package/lib/deploy/run/release.js +9 -0
  30. package/lib/deploy/run/update.js +50 -0
  31. package/lib/deploy/run/util.js +73 -0
  32. package/lib/emulator/apphosting/serve.js +1 -1
  33. package/lib/emulator/auth/utils.js +1 -1
  34. package/lib/emulator/commandUtils.js +7 -3
  35. package/lib/emulator/dataconnect/pgliteServer.js +1 -1
  36. package/lib/emulator/dataconnectEmulator.js +1 -1
  37. package/lib/emulator/download.js +1 -1
  38. package/lib/emulator/downloadableEmulatorInfo.json +31 -31
  39. package/lib/emulator/downloadableEmulators.js +1 -3
  40. package/lib/emulator/eventarcEmulator.js +1 -1
  41. package/lib/emulator/functionsEmulatorShared.js +1 -41
  42. package/lib/experiments.js +1 -12
  43. package/lib/firestore/validator.js +1 -1
  44. package/lib/functions/projectConfig.js +10 -5
  45. package/lib/gcp/cloudsql/permissions.js +21 -32
  46. package/lib/gcp/cloudsql/permissionsSetup.js +6 -6
  47. package/lib/gcp/storage.js +9 -5
  48. package/lib/init/features/index.js +4 -1
  49. package/lib/init/features/run.js +159 -0
  50. package/lib/init/index.js +6 -0
  51. package/lib/profileReport.js +8 -5
  52. package/lib/throttler/throttler.js +1 -0
  53. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  54. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  55. package/package.json +2 -8
  56. package/schema/firebaserc.json +133 -0
  57. package/lib/mcp/resources/guides/init_data_connect.js +0 -30
  58. package/lib/mcp/resources/guides/init_rtdb.js +0 -30
@@ -4,23 +4,22 @@ exports.prepare = prepare;
4
4
  const apps_1 = require("../../management/apps");
5
5
  const logger_1 = require("../../logger");
6
6
  const projectUtils_1 = require("../../projectUtils");
7
+ const DEFAULT_APP_DISPLAY_NAME = "Default Web App";
7
8
  async function prepare(context, options) {
8
9
  const projectId = (0, projectUtils_1.needProjectId)(options);
9
10
  const config = options.config.src.auth;
10
11
  if (!config) {
11
12
  return;
12
13
  }
13
- const apps = await (0, apps_1.listFirebaseApps)(projectId, apps_1.AppPlatform.WEB);
14
- let app = apps.find((a) => a.displayName === "Default Web App");
15
- if (!app && apps.length > 0) {
16
- app = apps[0];
17
- }
14
+ const apps = await (0, apps_1.listFirebaseApps)(projectId, apps_1.AppPlatform.ANY);
15
+ let app = apps.find((a) => a.displayName === DEFAULT_APP_DISPLAY_NAME) || apps[0];
18
16
  if (!app) {
19
- logger_1.logger.info("No Firebase Web App found. Creating 'Default Web App' for Auth provisioning...");
17
+ logger_1.logger.info(`No Firebase App found. Creating '${DEFAULT_APP_DISPLAY_NAME}' for Auth provisioning...`);
20
18
  app = await (0, apps_1.createWebApp)(projectId, {
21
- displayName: "Default Web App",
19
+ displayName: DEFAULT_APP_DISPLAY_NAME,
22
20
  });
23
21
  }
24
22
  context.auth = context.auth || {};
25
23
  context.auth.appId = app.appId;
24
+ context.auth.platform = app.platform;
26
25
  }
@@ -94,11 +94,11 @@ async function default_1(context, options) {
94
94
  await (0, ensureApiEnabled_1.ensure)(context.projectId, (0, api_1.firestoreOrigin)(), "firestore");
95
95
  if (options.only) {
96
96
  const targets = options.only.split(",");
97
- const excludeRules = targets.indexOf("firestore:indexes") >= 0;
98
- const excludeIndexes = targets.indexOf("firestore:rules") >= 0;
99
- const includeRules = targets.indexOf("firestore:rules") >= 0;
100
- const includeIndexes = targets.indexOf("firestore:indexes") >= 0;
101
- const onlyFirestore = targets.indexOf("firestore") >= 0;
97
+ const excludeRules = targets.includes("firestore:indexes");
98
+ const excludeIndexes = targets.includes("firestore:rules");
99
+ const includeRules = targets.includes("firestore:rules");
100
+ const includeIndexes = targets.includes("firestore:indexes");
101
+ const onlyFirestore = targets.includes("firestore");
102
102
  context.firestoreIndexes = !excludeIndexes || includeIndexes || onlyFirestore;
103
103
  context.firestoreRules = !excludeRules || includeRules || onlyFirestore;
104
104
  }
@@ -22,9 +22,10 @@ const isServiceUnavailable = (err) => parseErrorCode(err) === 503;
22
22
  exports.isServiceUnavailable = isServiceUnavailable;
23
23
  const isTransientError = (err) => (0, exports.isQuotaExhaustion)(err) || (0, exports.isConflict)(err) || (0, exports.isServiceUnavailable)(err);
24
24
  exports.isTransientError = isTransientError;
25
+ const MANAGED_SERVICE_ACCOUNT_REGEX = /\bfirebase-fn-[0-9]+@/i;
25
26
  const isServiceAccountPropagationError = (err) => {
26
27
  const code = parseErrorCode(err);
27
- if (code !== 404 && code !== 400) {
28
+ if (code !== 404 && code !== 400 && code !== 403) {
28
29
  return false;
29
30
  }
30
31
  let message = "";
@@ -44,13 +45,16 @@ const isServiceAccountPropagationError = (err) => {
44
45
  message = String(err).toLowerCase();
45
46
  }
46
47
  const hasSa = message.includes("serviceaccount") || message.includes("service account");
47
- if (!hasSa) {
48
+ if (!hasSa || !MANAGED_SERVICE_ACCOUNT_REGEX.test(message)) {
48
49
  return false;
49
50
  }
50
51
  if (code === 404) {
51
52
  return true;
52
53
  }
53
- return message.includes("invalid service account") && /\bfirebase-fn-[0-9]+@/i.test(message);
54
+ if (code === 400) {
55
+ return message.includes("invalid service account");
56
+ }
57
+ return message.includes("or it may not exist");
54
58
  };
55
59
  exports.isServiceAccountPropagationError = isServiceAccountPropagationError;
56
60
  const isCloudRunResourceExhausted = (err) => parseErrorCode(err) === 8;
@@ -173,14 +173,26 @@ class Fabricator {
173
173
  return this.applyUpserts(changes, scraperV1, scraperV2);
174
174
  });
175
175
  const createAndUpdateResultsArray = await Promise.allSettled(createAndUpdatePromises);
176
+ const upsertErrors = [];
176
177
  summary.results = createAndUpdateResultsArray.reduce((acc, r) => {
177
178
  if (r.status === "fulfilled") {
178
179
  return [...acc, ...r.value];
179
180
  }
180
- logger_1.logger.debug("Fabricator.applyUpserts returned an unhandled exception.", JSON.stringify(r.reason, null, 2));
181
+ upsertErrors.push((0, error_1.getError)(r.reason));
182
+ logger_1.logger.debug("Fabricator.applyUpserts returned an unhandled exception.", (0, error_1.getErrStack)(r.reason));
181
183
  return acc;
182
184
  }, []);
183
185
  await this.cleanupUnusedServiceAccounts(plan, summary.results);
186
+ if (upsertErrors.length) {
187
+ const opts = upsertErrors.length === 1 ? { original: upsertErrors[0] } : { children: upsertErrors };
188
+ const msg = upsertErrors.length === 1
189
+ ? `Fabricator.applyUpserts encountered an unhandled exception: ${upsertErrors[0].message}`
190
+ : "Fabricator.applyUpserts encountered unhandled exceptions";
191
+ throw new error_1.FirebaseError(msg, {
192
+ ...opts,
193
+ exit: 2,
194
+ });
195
+ }
184
196
  const hasFailures = summary.results.some((r) => r.error);
185
197
  if (hasFailures) {
186
198
  utils.logLabeledWarning("functions", "Deploys failed. Skipping deletes.");
@@ -196,14 +208,26 @@ class Fabricator {
196
208
  return summary;
197
209
  }
198
210
  const deleteResultsArray = await Promise.allSettled(allChangesets.map((changes) => this.applyDeletes(changes)));
211
+ const deleteErrors = [];
199
212
  const deleteResults = deleteResultsArray.reduce((acc, r) => {
200
213
  if (r.status === "fulfilled") {
201
214
  return [...acc, ...r.value];
202
215
  }
203
- logger_1.logger.debug("Fabricator.applyDeletes returned an unhandled exception. This should never happen", JSON.stringify(r.reason, null, 2));
216
+ deleteErrors.push((0, error_1.getError)(r.reason));
217
+ logger_1.logger.debug("Fabricator.applyDeletes returned an unhandled exception. This should never happen", (0, error_1.getErrStack)(r.reason));
204
218
  return acc;
205
219
  }, []);
206
220
  summary.results.push(...deleteResults);
221
+ if (deleteErrors.length) {
222
+ const opts = deleteErrors.length === 1 ? { original: deleteErrors[0] } : { children: deleteErrors };
223
+ const msg = deleteErrors.length === 1
224
+ ? `Fabricator.applyDeletes encountered an unhandled exception: ${deleteErrors[0].message}`
225
+ : "Fabricator.applyDeletes encountered unhandled exceptions";
226
+ throw new error_1.FirebaseError(msg, {
227
+ ...opts,
228
+ exit: 2,
229
+ });
230
+ }
207
231
  for (const [codebase, codebasePlan] of Object.entries(plan)) {
208
232
  await this.removeOldRoles(codebasePlan, codebase);
209
233
  }
@@ -231,23 +255,29 @@ class Fabricator {
231
255
  async applyUpserts(changes, scraperV1, scraperV2) {
232
256
  const ops = [];
233
257
  for (const endpoint of changes.endpointsToCreate) {
234
- this.logOpStart("creating", endpoint);
235
- ops.push(this.wrapOperation("create", endpoint, () => this.createEndpoint(endpoint, scraperV1, scraperV2)));
258
+ ops.push(this.wrapOperation("create", endpoint, () => {
259
+ this.logOpStart("creating", endpoint);
260
+ return this.createEndpoint(endpoint, scraperV1, scraperV2);
261
+ }));
236
262
  }
237
263
  for (const endpoint of changes.endpointsToSkip) {
238
264
  utils.logSuccess(this.getLogSuccessMessage("skip", endpoint));
239
265
  }
240
266
  for (const update of changes.endpointsToUpdate) {
241
- this.logOpStart("updating", update.endpoint);
242
- ops.push(this.wrapOperation("update", update.endpoint, () => this.updateEndpoint(update, scraperV1, scraperV2)));
267
+ ops.push(this.wrapOperation("update", update.endpoint, () => {
268
+ this.logOpStart("updating", update.endpoint);
269
+ return this.updateEndpoint(update, scraperV1, scraperV2);
270
+ }));
243
271
  }
244
272
  return Promise.all(ops);
245
273
  }
246
274
  async applyDeletes(changes) {
247
275
  const ops = [];
248
276
  for (const endpoint of changes.endpointsToDelete) {
249
- this.logOpStart("deleting", endpoint);
250
- ops.push(this.wrapOperation("delete", endpoint, () => this.deleteEndpoint(endpoint)));
277
+ ops.push(this.wrapOperation("delete", endpoint, () => {
278
+ this.logOpStart("deleting", endpoint);
279
+ return this.deleteEndpoint(endpoint);
280
+ }));
251
281
  }
252
282
  return Promise.all(ops);
253
283
  }
@@ -881,7 +911,9 @@ class Fabricator {
881
911
  .catch(rethrowAs(endpoint, "unregister blocking trigger"));
882
912
  }
883
913
  logOpStart(op, endpoint) {
884
- const runtime = endpoint.runtime ? supported_1.RUNTIMES[endpoint.runtime].friendly : "unknown";
914
+ const runtime = endpoint.runtime
915
+ ? supported_1.RUNTIMES[endpoint.runtime]?.friendly ?? endpoint.runtime
916
+ : "unknown";
885
917
  const platform = (0, functionsDeployHelper_1.getHumanFriendlyPlatformName)(endpoint.platform);
886
918
  const label = helper.getFunctionLabel(endpoint);
887
919
  utils.logLabeledBullet("functions", `${op} ${runtime} (${platform}) function ${clc.bold(label)}...`);
@@ -41,12 +41,12 @@ class SourceTokenScraper {
41
41
  return tokenResult.token;
42
42
  }
43
43
  else if (this.fetchState === "VALID") {
44
- const tokenResult = await this.promise;
45
44
  if (this.isTokenExpired()) {
46
45
  this.fetchState = "FETCHING";
47
46
  this.promise = new Promise((resolve) => (this.resolve = resolve));
48
47
  return undefined;
49
48
  }
49
+ const tokenResult = await this.promise;
50
50
  return tokenResult.token;
51
51
  }
52
52
  else {
@@ -23,6 +23,8 @@ const DataConnectTarget = require("./dataconnect");
23
23
  const AppHostingTarget = require("./apphosting");
24
24
  const AuthTarget = require("./auth");
25
25
  const AiLogicTarget = require("./ailogic");
26
+ const RunTarget = require("./run");
27
+ const prereqs_1 = require("./run/prereqs");
26
28
  const frameworks_1 = require("../frameworks");
27
29
  const prepare_1 = require("./hosting/prepare");
28
30
  const requirePermissions_1 = require("../requirePermissions");
@@ -39,6 +41,7 @@ exports.VALID_DEPLOY_TARGETS = [
39
41
  "apphosting",
40
42
  "auth",
41
43
  "ailogic",
44
+ "run",
42
45
  ];
43
46
  exports.TARGET_PERMISSIONS = {
44
47
  database: ["firebasedatabase.instances.update"],
@@ -95,6 +98,7 @@ exports.TARGET_PERMISSIONS = {
95
98
  "firebasevertexai.templates.delete",
96
99
  "serviceusage.services.get",
97
100
  ],
101
+ run: prereqs_1.RUN_PERMISSIONS,
98
102
  };
99
103
  exports.TARGETS = {
100
104
  hosting: HostingTarget,
@@ -108,6 +112,7 @@ exports.TARGETS = {
108
112
  apphosting: AppHostingTarget,
109
113
  auth: AuthTarget,
110
114
  ailogic: AiLogicTarget,
115
+ run: RunTarget,
111
116
  };
112
117
  const chain = async function (fns, context, options, payload) {
113
118
  for (const latest of fns) {
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BUILD_ENV_ANNOTATION = void 0;
4
+ exports.getBuildEnv = getBuildEnv;
5
+ exports.secretNames = secretNames;
6
+ exports.nonSecretValues = nonSecretValues;
7
+ exports.toLocalBuildEnv = toLocalBuildEnv;
8
+ const error_1 = require("../../error");
9
+ exports.BUILD_ENV_ANNOTATION = "firebase.google.com/buildConfig.environmentVariablesAndSecrets";
10
+ function getBuildEnv(service) {
11
+ const raw = service?.annotations?.[exports.BUILD_ENV_ANNOTATION];
12
+ if (!service || !raw) {
13
+ return {};
14
+ }
15
+ const invalid = (reason) => new error_1.FirebaseError(`Invalid ${exports.BUILD_ENV_ANNOTATION} annotation on ${service.name}: ${reason}`);
16
+ let parsed;
17
+ try {
18
+ parsed = JSON.parse(raw);
19
+ }
20
+ catch {
21
+ throw invalid("it isn't valid JSON.");
22
+ }
23
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
24
+ throw invalid("it must be a JSON object.");
25
+ }
26
+ const env = {};
27
+ for (const [name, value] of Object.entries(parsed)) {
28
+ if (typeof value === "string" || isSecretRef(value)) {
29
+ env[name] = value;
30
+ }
31
+ else if (typeof value === "number" || typeof value === "boolean") {
32
+ env[name] = String(value);
33
+ }
34
+ else {
35
+ throw invalid(`${name} must be a string, number, boolean, or {"secret": "<secret name>"}.`);
36
+ }
37
+ }
38
+ return env;
39
+ }
40
+ function isSecretRef(value) {
41
+ const ref = value;
42
+ return (typeof ref === "object" &&
43
+ ref !== null &&
44
+ Object.keys(ref).length === 1 &&
45
+ typeof ref.secret === "string");
46
+ }
47
+ function secretNames(env) {
48
+ return Object.entries(env)
49
+ .filter(([, value]) => isSecretRef(value))
50
+ .map(([name]) => name);
51
+ }
52
+ function nonSecretValues(env) {
53
+ const values = {};
54
+ for (const [name, value] of Object.entries(env)) {
55
+ if (!isSecretRef(value)) {
56
+ values[name] = value;
57
+ }
58
+ }
59
+ return values;
60
+ }
61
+ function toLocalBuildEnv(env) {
62
+ const result = {};
63
+ for (const [name, value] of Object.entries(env)) {
64
+ if (isSecretRef(value)) {
65
+ result[name] = { secret: value.secret, availability: ["BUILD"] };
66
+ }
67
+ else {
68
+ result[name] = { value, availability: ["BUILD"] };
69
+ }
70
+ }
71
+ return result;
72
+ }
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deploy = deploy;
4
+ exports.revisionTemplate = revisionTemplate;
5
+ exports.localBuildTemplate = localBuildTemplate;
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const path = require("path");
9
+ const constants_1 = require("../../apphosting/constants");
10
+ const localbuilds_1 = require("../../apphosting/localbuilds");
11
+ const error_1 = require("../../error");
12
+ const artifactregistry = require("../../gcp/artifactregistry");
13
+ const runv2 = require("../../gcp/runv2");
14
+ const gcs = require("../../gcp/storage");
15
+ const getProjectNumber_1 = require("../../getProjectNumber");
16
+ const logger_1 = require("../../logger");
17
+ const utils_1 = require("../../utils");
18
+ const prepare_1 = require("../apphosting/prepare");
19
+ const util_1 = require("../apphosting/util");
20
+ const buildEnv_1 = require("./buildEnv");
21
+ const util_2 = require("./util");
22
+ const DEPLOY_MESSAGE_ANNOTATION = "firebase.google.com/deploy-message";
23
+ const ROLLOUT_TIMEOUT_MS = 10 * 60 * 1000;
24
+ const NO_IMAGE = "scratch";
25
+ async function deploy(context, options, payload) {
26
+ for (const svc of payload.run?.services || []) {
27
+ if (svc.config.localBuild) {
28
+ await deployLocalBuild(context, options, svc);
29
+ }
30
+ else {
31
+ await deployRemoteBuild(context, options, svc);
32
+ }
33
+ }
34
+ }
35
+ async function deployRemoteBuild(context, options, svc) {
36
+ const { projectId } = context;
37
+ const source = await uploadSource(projectId, options, svc.config);
38
+ const image = await buildImage(projectId, svc, source);
39
+ const template = revisionTemplate(svc, image, options.message);
40
+ svc.deployed = await rollOut(projectId, svc, template);
41
+ }
42
+ async function deployLocalBuild(context, options, svc) {
43
+ const { projectId } = context;
44
+ const scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), `run-local-build-${svc.config.serviceId}-`));
45
+ try {
46
+ const build = await buildLocally(context, options, svc, scratchDir);
47
+ const builtApp = await uploadBuiltApp(projectId, options, svc.config, scratchDir, build);
48
+ const message = options.message;
49
+ const template = localBuildTemplate(svc, build, builtApp, message);
50
+ svc.deployed = await rollOut(projectId, svc, template);
51
+ }
52
+ finally {
53
+ removeTempPath(scratchDir);
54
+ }
55
+ }
56
+ async function buildLocally(context, options, svc, scratchDir) {
57
+ const { config } = svc;
58
+ const { serviceId, region } = config;
59
+ const cfg = toAppHostingConfig(config);
60
+ (0, localbuilds_1.validateLocalBuildNodeVersion)({ runtime: { value: svc.baseImage?.split("/").pop() } }, path.join(options.config.projectDir, cfg.rootDir));
61
+ (0, utils_1.logLabeledBullet)("run", `Starting local build for service ${serviceId} in ${region}`);
62
+ const secrets = (0, buildEnv_1.secretNames)(svc.buildEnv || {});
63
+ if (secrets.length) {
64
+ (0, utils_1.logLabeledBullet)("run", `Reading build secrets ${secrets.join(", ")} with your credentials. Their values may be ` +
65
+ `included in the build output.`);
66
+ }
67
+ await (0, prepare_1.prepareLocalBuildScratchDirectory)(options.config.projectDir, scratchDir, cfg);
68
+ const { outputFiles, buildConfig } = await (0, localbuilds_1.localBuild)(context.projectId, scratchDir, (0, buildEnv_1.toLocalBuildEnv)(svc.buildEnv || {}), { rootDir: config.rootDir, allowLocalBuildSecrets: true });
69
+ const env = (buildConfig.env || [])
70
+ .filter((e) => e.variable &&
71
+ e.value !== undefined &&
72
+ (!e.availability || e.availability.includes("RUNTIME")))
73
+ .map((e) => ({ name: e.variable, value: e.value }));
74
+ return { outputFiles, runCommand: buildConfig.runCommand, env };
75
+ }
76
+ async function uploadSource(projectId, options, config) {
77
+ const { serviceId, region } = config;
78
+ const bucketName = await sourceBucket(projectId, options, region);
79
+ const cfg = toAppHostingConfig(config);
80
+ const archive = await (0, util_1.createSourceDeployArchive)(cfg, path.join(options.config.projectDir, cfg.rootDir));
81
+ (0, utils_1.logLabeledBullet)("run", `Uploading source for service ${serviceId} in ${region}...`);
82
+ const { bucket, object } = await gcs.uploadObject({ file: archive, stream: fs.createReadStream(archive) }, bucketName, gcs.ContentType.ZIP);
83
+ return { bucket, object };
84
+ }
85
+ async function uploadBuiltApp(projectId, options, config, scratchDir, build) {
86
+ const { serviceId, region } = config;
87
+ const bucketName = await sourceBucket(projectId, options, region);
88
+ const archive = await (0, util_1.createLocalBuildTarArchive)(toAppHostingConfig(config), scratchDir, build.outputFiles);
89
+ (0, utils_1.logLabeledBullet)("run", `Uploading built app for service ${serviceId} in ${region}...`);
90
+ const { bucket, object } = await gcs.uploadObject({ file: archive, stream: fs.createReadStream(archive) }, bucketName, gcs.ContentType.TAR, constants_1.CLOUD_RUN_SIZE_LIMIT_BYTES);
91
+ return { bucket, object };
92
+ }
93
+ async function sourceBucket(projectId, options, region) {
94
+ const baseName = `firebase-run-src-${await (0, getProjectNumber_1.getProjectNumber)(options)}-${region.toLowerCase()}`;
95
+ return gcs.upsertBucket({
96
+ product: "run",
97
+ createMessage: `Creating Cloud Storage bucket in ${region} to store Cloud Run source code uploads at ${baseName}...`,
98
+ projectId,
99
+ req: {
100
+ baseName,
101
+ purposeLabel: `run-source-${region.toLowerCase()}`,
102
+ location: region,
103
+ lifecycle: { rule: [{ action: { type: "Delete" }, condition: { age: 30 } }] },
104
+ },
105
+ });
106
+ }
107
+ async function buildImage(projectId, svc, source) {
108
+ const { serviceId, region } = svc.config;
109
+ await artifactregistry.ensureDockerRepository(projectId, region, "cloud-run-source-deploy");
110
+ const imageUri = `${region}-docker.pkg.dev/${projectId}/cloud-run-source-deploy/${serviceId}:${Date.now()}`;
111
+ (0, utils_1.logLabeledBullet)("run", `Building service ${serviceId} in ${region}...`);
112
+ const buildpackBuild = {
113
+ environmentVariables: {
114
+ ...(0, buildEnv_1.nonSecretValues)(svc.buildEnv || {}),
115
+ X_GOOGLE_TARGET_PLATFORM: "fah",
116
+ FIREBASE_OUTPUT_BUNDLE_DIR: "/workspace/.apphosting",
117
+ },
118
+ };
119
+ if (svc.baseImage) {
120
+ buildpackBuild.baseImage = svc.baseImage;
121
+ buildpackBuild.enableAutomaticUpdates = true;
122
+ }
123
+ await runv2.submitBuild(projectId, region, { storageSource: source, imageUri, buildpackBuild });
124
+ return imageUri;
125
+ }
126
+ function revisionTemplate(svc, image, message) {
127
+ const { serviceId, region } = svc.config;
128
+ const template = svc.existing
129
+ ? (0, utils_1.cloneDeep)(svc.existing.template)
130
+ : { containers: [{ name: serviceId, image }] };
131
+ delete template.revision;
132
+ const container = (0, util_2.mainContainer)(template);
133
+ if (!container) {
134
+ throw new error_1.FirebaseError(`Service ${serviceId} in ${region} has no containers.`);
135
+ }
136
+ container.image = image;
137
+ if (container.sourceCode) {
138
+ delete container.sourceCode;
139
+ delete container.command;
140
+ }
141
+ if (svc.baseImage) {
142
+ container.baseImageUri = svc.baseImage;
143
+ }
144
+ else {
145
+ delete container.baseImageUri;
146
+ }
147
+ if (message) {
148
+ template.annotations = { ...template.annotations, [DEPLOY_MESSAGE_ANNOTATION]: message };
149
+ }
150
+ else if (template.annotations) {
151
+ delete template.annotations[DEPLOY_MESSAGE_ANNOTATION];
152
+ }
153
+ return template;
154
+ }
155
+ function localBuildTemplate(svc, build, builtApp, message) {
156
+ const template = revisionTemplate(svc, NO_IMAGE, message);
157
+ const container = (0, util_2.mainContainer)(template);
158
+ container.sourceCode = { cloudStorageSource: builtApp };
159
+ const command = build.runCommand?.trim();
160
+ if (command) {
161
+ container.command = command.split(/\s+/);
162
+ }
163
+ else {
164
+ delete container.command;
165
+ }
166
+ if (build.env.length) {
167
+ const buildNames = new Set(build.env.map((e) => e.name));
168
+ const otherEnv = (container.env || []).filter((e) => !buildNames.has(e.name));
169
+ container.env = [...otherEnv, ...build.env];
170
+ }
171
+ return template;
172
+ }
173
+ function rollOut(projectId, svc, template) {
174
+ if (svc.existing) {
175
+ return deployRevision(svc.existing, template);
176
+ }
177
+ return createNewService(projectId, svc.config, template);
178
+ }
179
+ function createNewService(projectId, config, template) {
180
+ const { serviceId, region } = config;
181
+ return runv2.createService(projectId, region, serviceId, {
182
+ name: `projects/${projectId}/locations/${region}/services/${serviceId}`,
183
+ template,
184
+ client: "cli-firebase",
185
+ invokerIamDisabled: true,
186
+ ingress: "INGRESS_TRAFFIC_ALL",
187
+ }, { pollTimeoutMs: ROLLOUT_TIMEOUT_MS });
188
+ }
189
+ function deployRevision(service, template) {
190
+ const tags = (service.traffic || [])
191
+ .filter((t) => t.tag)
192
+ .map((t) => ({ type: t.type, revision: t.revision, tag: t.tag }));
193
+ return runv2.updateService({
194
+ name: service.name,
195
+ template,
196
+ traffic: [{ type: "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST", percent: 100 }, ...tags],
197
+ }, { updateMask: ["template", "traffic"], pollTimeoutMs: ROLLOUT_TIMEOUT_MS });
198
+ }
199
+ function toAppHostingConfig(config) {
200
+ return {
201
+ backendId: config.serviceId,
202
+ rootDir: config.rootDir || "",
203
+ ignore: config.ignore,
204
+ localBuild: config.localBuild,
205
+ };
206
+ }
207
+ function removeTempPath(tempPath) {
208
+ try {
209
+ fs.rmSync(tempPath, { recursive: true, force: true });
210
+ }
211
+ catch (err) {
212
+ logger_1.logger.debug(`Failed to clean up ${tempPath}: ${(0, error_1.getErrMsg)(err)}`);
213
+ }
214
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.detailedHelp = exports.help = exports.release = exports.deploy = exports.prepare = void 0;
4
+ const prepare_1 = require("./prepare");
5
+ Object.defineProperty(exports, "prepare", { enumerable: true, get: function () { return prepare_1.prepare; } });
6
+ const deploy_1 = require("./deploy");
7
+ Object.defineProperty(exports, "deploy", { enumerable: true, get: function () { return deploy_1.deploy; } });
8
+ const release_1 = require("./release");
9
+ Object.defineProperty(exports, "release", { enumerable: true, get: function () { return release_1.release; } });
10
+ exports.help = "Builds and deploys web apps to Cloud Run services listed in firebase.json. Supports filtering:\n" +
11
+ " --only run:serviceId (in every region firebase.json lists it in)\n" +
12
+ " --only run:serviceId:region (in one region)";
13
+ exports.detailedHelp = "Deploys Cloud Run services from local source, or from a local build if localBuild is set.\n\n" +
14
+ "Configuration in firebase.json:\n" +
15
+ "{\n" +
16
+ ' "run": {\n' +
17
+ ' "serviceId": "my-service",\n' +
18
+ ' "region": "us-central1",\n' +
19
+ ' "rootDir": "/",\n' +
20
+ ' "ignore": ["node_modules", ".git"]\n' +
21
+ " }\n" +
22
+ "}\n\n" +
23
+ "Base images are configured on the service with firebase run:services:update --base-image and are reused on every deploy.";
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepare = prepare;
4
+ const error_1 = require("../../error");
5
+ const utils_1 = require("../../utils");
6
+ const buildEnv_1 = require("./buildEnv");
7
+ const prereqs_1 = require("./prereqs");
8
+ const util_1 = require("./util");
9
+ async function prepare(context, options, payload) {
10
+ const configs = (0, util_1.getServiceConfigs)(options);
11
+ if (!configs.length) {
12
+ return;
13
+ }
14
+ await (0, prereqs_1.prereqs)(context.projectId);
15
+ payload.run = { services: [] };
16
+ for (const config of configs) {
17
+ payload.run.services.push(await prepareService(context, config));
18
+ }
19
+ }
20
+ async function prepareService(context, config) {
21
+ const { serviceId, region } = config;
22
+ const existing = await (0, util_1.getExistingService)(context.projectId, region, serviceId);
23
+ let baseImage = (0, util_1.mainContainer)(existing?.template)?.baseImageUri;
24
+ if (context.baseImage !== undefined) {
25
+ baseImage = context.baseImage ?? undefined;
26
+ }
27
+ if (config.localBuild && !baseImage) {
28
+ const fix = existing
29
+ ? `firebase run:services:update ${serviceId} --region ${region} --base-image <baseImage>`
30
+ : "firebase init run";
31
+ throw new error_1.FirebaseError(`Local builds require a base image. Set one for service ${serviceId} in ${region} with "${fix}".`);
32
+ }
33
+ const buildEnv = (0, buildEnv_1.getBuildEnv)(existing);
34
+ const secrets = (0, buildEnv_1.secretNames)(buildEnv);
35
+ if (secrets.length && !config.localBuild) {
36
+ throw new error_1.FirebaseError(`Service ${serviceId} in ${region} has build secrets (${secrets.join(", ")}), but only ` +
37
+ `local builds can use secrets: builds on Cloud Build only take plain values. To use ` +
38
+ `them, set "localBuild": true for this service in firebase.json.`);
39
+ }
40
+ const svc = { config, existing, baseImage };
41
+ if (Object.keys(buildEnv).length) {
42
+ (0, utils_1.logLabeledBullet)("run", `Using build environment variables for service ${serviceId} in ${region} from ` +
43
+ `${buildEnv_1.BUILD_ENV_ANNOTATION}: ${Object.keys(buildEnv).join(", ")}`);
44
+ svc.buildEnv = buildEnv;
45
+ }
46
+ return svc;
47
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RUN_PERMISSIONS = void 0;
4
+ exports.prereqs = prereqs;
5
+ const ensureApiEnabled_1 = require("../../ensureApiEnabled");
6
+ const artifactregistry = require("../../gcp/artifactregistry");
7
+ exports.RUN_PERMISSIONS = [
8
+ "run.services.get",
9
+ "run.services.create",
10
+ "run.services.update",
11
+ "run.services.setIamPolicy",
12
+ "run.operations.get",
13
+ "cloudbuild.builds.create",
14
+ "cloudbuild.builds.get",
15
+ "storage.buckets.get",
16
+ "storage.buckets.list",
17
+ "storage.buckets.create",
18
+ "storage.buckets.update",
19
+ "storage.objects.create",
20
+ "artifactregistry.repositories.get",
21
+ "artifactregistry.repositories.create",
22
+ "artifactregistry.repositories.downloadArtifacts",
23
+ "iam.serviceAccounts.actAs",
24
+ ];
25
+ async function prereqs(projectId) {
26
+ await Promise.all([
27
+ (0, ensureApiEnabled_1.ensure)(projectId, "run.googleapis.com", "run", true),
28
+ (0, ensureApiEnabled_1.ensure)(projectId, "cloudbuild.googleapis.com", "cloudbuild", true),
29
+ (0, ensureApiEnabled_1.ensure)(projectId, "storage.googleapis.com", "storage", true),
30
+ artifactregistry.ensureApiEnabled(projectId),
31
+ ]);
32
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.release = release;
4
+ const utils_1 = require("../../utils");
5
+ async function release(_context, _options, payload) {
6
+ for (const { config, deployed } of payload.run?.services || []) {
7
+ (0, utils_1.logLabeledSuccess)("run", `Deployed service ${config.serviceId} in ${config.region}${deployed?.uri ? ` to ${deployed.uri}` : ""}`);
8
+ }
9
+ }