firebase-tools 15.28.2 → 15.28.3-feat-firebase-debug-path.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 (75) hide show
  1. package/lib/api.js +4 -2
  2. package/lib/apphosting/config.js +10 -8
  3. package/lib/apphosting/localbuilds.js +8 -0
  4. package/lib/apphosting/yaml.js +27 -0
  5. package/lib/bin/cli.js +4 -1
  6. package/lib/bin/mcp.js +8 -3
  7. package/lib/commands/ext-export.js +34 -13
  8. package/lib/commands/ext-migrate.js +3 -0
  9. package/lib/commands/functions-delete.js +6 -67
  10. package/lib/commands/functions-kits-install.js +3 -0
  11. package/lib/commands/functions-kits-uninstall.js +5 -71
  12. package/lib/crashlytics/onboarding.js +23 -2
  13. package/lib/deploy/apphosting/deploy.js +2 -1
  14. package/lib/deploy/apphosting/prepare.js +12 -3
  15. package/lib/deploy/apphosting/release.js +3 -0
  16. package/lib/deploy/apphosting/util.js +3 -1
  17. package/lib/deploy/extensions/secrets.js +10 -0
  18. package/lib/deploy/functions/delete.js +80 -0
  19. package/lib/emulator/types.js +3 -1
  20. package/lib/extensions/askUserForParam.js +9 -8
  21. package/lib/extensions/export.js +46 -9
  22. package/lib/extensions/extensionsHelper.js +28 -0
  23. package/lib/extensions/migrate.js +121 -2
  24. package/lib/extensions/paramHelper.js +78 -25
  25. package/lib/extensions/secretsUtils.js +3 -0
  26. package/lib/extensions/updateHelper.js +3 -1
  27. package/lib/functions/kits/install.js +238 -68
  28. package/lib/gcp/apikeys.js +89 -0
  29. package/lib/gcp/storage.js +3 -2
  30. package/lib/logger.js +83 -9
  31. package/lib/mcp/tools/apphosting/fetch_logs.js +1 -0
  32. package/lib/mcp/tools/apphosting/list_backends.js +1 -0
  33. package/lib/mcp/tools/apptesting/tests.js +2 -0
  34. package/lib/mcp/tools/auth/get_users.js +1 -0
  35. package/lib/mcp/tools/auth/set_sms_region_policy.js +1 -0
  36. package/lib/mcp/tools/auth/update_user.js +1 -0
  37. package/lib/mcp/tools/core/create_android_sha.js +1 -0
  38. package/lib/mcp/tools/core/create_app.js +1 -0
  39. package/lib/mcp/tools/core/create_project.js +1 -0
  40. package/lib/mcp/tools/core/deploy.js +1 -0
  41. package/lib/mcp/tools/core/deploy_status.js +1 -0
  42. package/lib/mcp/tools/core/get_environment.js +1 -0
  43. package/lib/mcp/tools/core/get_project.js +1 -0
  44. package/lib/mcp/tools/core/get_sdk_config.js +1 -0
  45. package/lib/mcp/tools/core/get_security_rules.js +1 -0
  46. package/lib/mcp/tools/core/init.js +1 -0
  47. package/lib/mcp/tools/core/list_apps.js +1 -0
  48. package/lib/mcp/tools/core/list_projects.js +1 -0
  49. package/lib/mcp/tools/core/login.js +1 -0
  50. package/lib/mcp/tools/core/logout.js +1 -0
  51. package/lib/mcp/tools/core/read_resources.js +1 -0
  52. package/lib/mcp/tools/core/update_environment.js +1 -0
  53. package/lib/mcp/tools/core/validate_security_rules.js +1 -0
  54. package/lib/mcp/tools/crashlytics/events.js +2 -0
  55. package/lib/mcp/tools/crashlytics/issues.js +2 -0
  56. package/lib/mcp/tools/crashlytics/notes.js +3 -0
  57. package/lib/mcp/tools/crashlytics/reports.js +1 -0
  58. package/lib/mcp/tools/dataconnect/compile.js +1 -0
  59. package/lib/mcp/tools/dataconnect/execute.js +1 -0
  60. package/lib/mcp/tools/dataconnect/list_services.js +1 -0
  61. package/lib/mcp/tools/firestore/query_collection.js +1 -0
  62. package/lib/mcp/tools/functions/get_logs.js +1 -0
  63. package/lib/mcp/tools/functions/list_functions.js +1 -0
  64. package/lib/mcp/tools/index.js +3 -1
  65. package/lib/mcp/tools/messaging/send_message.js +1 -0
  66. package/lib/mcp/tools/realtime_database/get_data.js +1 -0
  67. package/lib/mcp/tools/realtime_database/set_data.js +1 -0
  68. package/lib/mcp/tools/remoteconfig/get_template.js +1 -0
  69. package/lib/mcp/tools/remoteconfig/update_template.js +1 -0
  70. package/lib/mcp/tools/storage/get_download_url.js +1 -0
  71. package/lib/prompt.js +10 -1
  72. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  73. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  74. package/package.json +1 -1
  75. package/templates/init/functions/typescript/index-kit-migration.ts +20 -2
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleSecretParams = handleSecretParams;
4
4
  exports.checkSpecForSecrets = checkSpecForSecrets;
5
+ exports.secretHasExtensionsLabel = secretHasExtensionsLabel;
5
6
  exports.transferSecretToKits = transferSecretToKits;
6
7
  const clc = require("colorette");
7
8
  const secretUtils = require("../../extensions/secretsUtils");
@@ -140,6 +141,15 @@ async function getSecretInfo(projectId, secretName, version) {
140
141
  }
141
142
  return secretInfo;
142
143
  }
144
+ async function secretHasExtensionsLabel(projectId, secretName) {
145
+ try {
146
+ const have = await secretManager.getSecret(projectId, secretName);
147
+ return secretUtils.SECRET_LABEL in have.labels;
148
+ }
149
+ catch (err) {
150
+ throw new error_1.FirebaseError(`Error when retrieving current state of migrating secret ${projectId}/${secretName}: ${err instanceof Error ? err.message : String(err)}`, { original: err instanceof Error ? err : undefined });
151
+ }
152
+ }
143
153
  async function transferSecretToKits(projectId, secretName) {
144
154
  const newLabels = {};
145
155
  try {
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteFunctionsByEndpointFilters = deleteFunctionsByEndpointFilters;
4
+ const backend = require("./backend");
5
+ const planner = require("./release/planner");
6
+ const executor = require("./release/executor");
7
+ const fabricator = require("./release/fabricator");
8
+ const functionsDeployHelper_1 = require("./functionsDeployHelper");
9
+ const getProjectNumber_1 = require("../../getProjectNumber");
10
+ const reporter = require("./release/reporter");
11
+ const error_1 = require("../../error");
12
+ const functional_1 = require("../../functional");
13
+ const prompt_1 = require("../../prompt");
14
+ const functionsConfig = require("../../functionsConfig");
15
+ async function deleteFunctionsByEndpointFilters(context, options) {
16
+ let haveBackend = await backend.existingBackend(context);
17
+ if (options?.region) {
18
+ haveBackend = backend.matchingBackend(haveBackend, (endpoint) => endpoint.region === options.region);
19
+ }
20
+ const plan = await planner.createDeploymentPlan({
21
+ wantBackend: backend.empty(),
22
+ haveBackend: haveBackend,
23
+ codebase: "",
24
+ projectId: context.projectId,
25
+ filters: context.filters,
26
+ deleteAll: true,
27
+ });
28
+ const allEpToDelete = Object.values(plan.regionalChangesets)
29
+ .map((changes) => changes.endpointsToDelete)
30
+ .reduce(functional_1.reduceFlat, [])
31
+ .sort(backend.compareFunctions);
32
+ if (allEpToDelete.length === 0) {
33
+ return 0;
34
+ }
35
+ const deleteList = allEpToDelete.map((func) => `\t${(0, functionsDeployHelper_1.getFunctionLabel)(func)}`).join("\n");
36
+ const confirmDeletion = await (0, prompt_1.confirm)({
37
+ message: "You are about to delete the following Cloud Functions:\n" + deleteList + "\n Are you sure?",
38
+ default: false,
39
+ force: options?.force,
40
+ nonInteractive: options?.nonInteractive,
41
+ });
42
+ if (!confirmDeletion) {
43
+ throw new error_1.FirebaseError("Command aborted.");
44
+ }
45
+ const functionExecutor = new executor.QueueExecutor({
46
+ retries: 30,
47
+ backoff: 20000,
48
+ concurrency: 40,
49
+ maxBackoff: 40000,
50
+ });
51
+ try {
52
+ const firebaseConfig = await functionsConfig.getFirebaseConfig({
53
+ ...options,
54
+ projectId: context.projectId,
55
+ });
56
+ const appEngineLocation = functionsConfig.getAppEngineLocation(firebaseConfig);
57
+ const fab = new fabricator.Fabricator({
58
+ functionExecutor,
59
+ runFunctionExecutor: functionExecutor,
60
+ appEngineLocation,
61
+ executor: new executor.QueueExecutor({}),
62
+ sources: {},
63
+ projectNumber: await (0, getProjectNumber_1.getProjectNumber)({ projectId: context.projectId }),
64
+ projectId: context.projectId,
65
+ });
66
+ const summary = await fab.applyPlan({ default: plan });
67
+ await reporter.logAndTrackDeployStats(summary);
68
+ reporter.printErrors(summary);
69
+ if (summary.results.some((r) => r.error)) {
70
+ throw new error_1.FirebaseError("At least one functions deletion operation failed.");
71
+ }
72
+ return allEpToDelete.length;
73
+ }
74
+ catch (err) {
75
+ throw new error_1.FirebaseError(`Failed to delete functions: ${err}`, {
76
+ original: err,
77
+ exit: 1,
78
+ });
79
+ }
80
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Severity = exports.EmulatorLog = exports.FunctionsExecutionMode = exports.ALL_EMULATORS = exports.EMULATORS_SUPPORTED_BY_USE_EMULATOR = exports.EMULATORS_SUPPORTED_BY_UI = exports.EMULATORS_SUPPORTED_BY_FUNCTIONS = exports.ALL_SERVICE_EMULATORS = exports.IMPORT_EXPORT_EMULATORS = exports.DOWNLOADABLE_EMULATORS = exports.Emulators = void 0;
4
4
  exports.isDownloadableEmulator = isDownloadableEmulator;
5
5
  exports.isEmulator = isEmulator;
6
+ const error_1 = require("../error");
6
7
  var Emulators;
7
8
  (function (Emulators) {
8
9
  Emulators["AUTH"] = "auth";
@@ -177,7 +178,8 @@ class EmulatorLog {
177
178
  if (process.send) {
178
179
  process.send(nextMsg, undefined, {}, (err) => {
179
180
  if (err) {
180
- process.stderr.write(err);
181
+ process.stderr.write(`${(0, error_1.getErrStack)(err)}\n`);
182
+ EmulatorLog.LOG_BUFFER = [];
181
183
  }
182
184
  EmulatorLog.WAITING_FOR_FLUSH = EmulatorLog.LOG_BUFFER.length > 0;
183
185
  this.flush();
@@ -135,19 +135,20 @@ async function askForParam(args) {
135
135
  });
136
136
  valid = checkResponse(response, paramSpec);
137
137
  break;
138
- case types_1.ParamType.MULTISELECT:
138
+ case types_1.ParamType.MULTISELECT: {
139
+ const defaultValues = (paramSpec.default || "").split(",");
139
140
  response = (await (0, prompt_1.checkbox)({
140
- default: paramSpec.default
141
- ? paramSpec.default.split(",").map((def) => {
142
- return getInquirerDefault(_.get(paramSpec, "options", []), def);
143
- })
144
- : undefined,
145
141
  message: "Which options do you want enabled for this parameter? " +
146
142
  "Press Space to select, then Enter to confirm your choices. ",
147
- choices: (0, utils_1.convertExtensionOptionToLabeledList)(paramSpec.options),
143
+ choices: paramSpec.options.map((option) => ({
144
+ checked: defaultValues.includes(option.value),
145
+ name: option.label || option.value,
146
+ value: option.value,
147
+ })),
148
148
  })).join(",");
149
149
  valid = checkResponse(response, paramSpec);
150
150
  break;
151
+ }
151
152
  case types_1.ParamType.SECRET:
152
153
  do {
153
154
  secretLocations = await promptSecretLocations(paramSpec);
@@ -165,7 +166,7 @@ async function askForParam(args) {
165
166
  break;
166
167
  default:
167
168
  response = await (0, prompt_1.input)({
168
- default: paramSpec.default,
169
+ default: paramSpec.default ?? (paramSpec.required ? undefined : ""),
169
170
  message: `Enter a value for ${label}:`,
170
171
  });
171
172
  valid = checkResponse(response, paramSpec);
@@ -4,6 +4,7 @@ exports.parameterizeProject = parameterizeProject;
4
4
  exports.setSecretParamsToLatest = setSecretParamsToLatest;
5
5
  exports.displayExportInfo = displayExportInfo;
6
6
  exports.functionsEnvFromInstance = functionsEnvFromInstance;
7
+ exports.secretsNeedingEjection = secretsNeedingEjection;
7
8
  exports.ejectSecretsFromInstance = ejectSecretsFromInstance;
8
9
  const planner_1 = require("../deploy/extensions/planner");
9
10
  const deploymentSummary_1 = require("../deploy/extensions/deploymentSummary");
@@ -12,6 +13,7 @@ const secretManager_1 = require("../gcp/secretManager");
12
13
  const secretsUtils_1 = require("./secretsUtils");
13
14
  const secrets_1 = require("../deploy/extensions/secrets");
14
15
  const error_1 = require("../error");
16
+ const utils_1 = require("../utils");
15
17
  function parameterizeProject(projectId, projectNumber, spec) {
16
18
  const newParams = {};
17
19
  for (const [key, val] of Object.entries(spec.params)) {
@@ -67,8 +69,8 @@ function displaySpecs(specs) {
67
69
  function functionsEnvFromInstance(instance) {
68
70
  const liveParams = instance.config?.params || {};
69
71
  const liveSystemParams = instance.config?.systemParams || {};
70
- const specParams = instance.config?.source?.spec?.params || {};
71
- const specSystemParams = instance.config?.source?.spec?.systemParams || {};
72
+ const specParams = instance.config?.source?.spec?.params || [];
73
+ const specSystemParams = instance.config?.source?.spec?.systemParams || [];
72
74
  const envs = {};
73
75
  specParams.forEach((specParam) => {
74
76
  if (specParam.type === "SECRET") {
@@ -87,18 +89,21 @@ function functionsEnvFromInstance(instance) {
87
89
  .replace(/^firebaseextensions\.v1beta\.(v2)?function\//, "EXT_MIGRATED_SYSTEM_")
88
90
  .toUpperCase();
89
91
  if (renamed === "EXT_MIGRATED_SYSTEM_LOCATION") {
90
- renamed = "DEFAULT_FUNCTION_REGION";
92
+ renamed = "FUNCTION_DEFAULT_REGION";
91
93
  }
92
94
  envs[renamed] = sysParamValue;
93
95
  }
94
- for (const specSystemParam of Object.values(specSystemParams)) {
96
+ for (const specSystemParam of specSystemParams) {
95
97
  if (specSystemParam.param in liveSystemParams) {
96
98
  continue;
97
99
  }
98
100
  if ("default" in specSystemParam) {
99
- const renamed = specSystemParam.param
101
+ let renamed = specSystemParam.param
100
102
  .replace(/^firebaseextensions\.v1beta\.(v2)?function\//, "EXT_MIGRATED_SYSTEM_")
101
103
  .toUpperCase();
104
+ if (renamed === "EXT_MIGRATED_SYSTEM_LOCATION") {
105
+ renamed = "FUNCTION_DEFAULT_REGION";
106
+ }
102
107
  envs[renamed] = specSystemParam.default ?? "";
103
108
  }
104
109
  }
@@ -110,8 +115,32 @@ function functionsEnvFromInstance(instance) {
110
115
  }
111
116
  return envs;
112
117
  }
118
+ async function secretsNeedingEjection(instance) {
119
+ const liveParams = instance.config?.params || {};
120
+ const secretParams = (instance.config?.source?.spec?.params ?? []).filter((p) => p.type === "SECRET");
121
+ const checks = secretParams.map(async (specParam) => {
122
+ const secretName = specParam.param;
123
+ const resourceName = liveParams[secretName];
124
+ if (!resourceName) {
125
+ throw new error_1.FirebaseError("Secret " +
126
+ secretName +
127
+ " was defined in the extension spec, but is missing in live deployed secrets.", { exit: 1 });
128
+ }
129
+ const match = resourceName.match(secretManager_1.SECRET_VERSION_NAME_REGEX);
130
+ if (!match?.groups) {
131
+ throw new error_1.FirebaseError("Invalid secret version resource name [" + resourceName + "].");
132
+ }
133
+ const projectId = match.groups.project;
134
+ const secretId = match.groups.secret;
135
+ const hasLabel = await (0, secrets_1.secretHasExtensionsLabel)(projectId, secretId);
136
+ return hasLabel ? `${projectId}/${secretId}` : undefined;
137
+ });
138
+ const results = await Promise.all(checks);
139
+ return results.filter((r) => r !== undefined);
140
+ }
113
141
  async function ejectSecretsFromInstance(instance) {
114
- const secretsChanged = [];
142
+ const success = [];
143
+ const fail = [];
115
144
  const liveParams = instance.config?.params || {};
116
145
  for (const specParam of instance.config?.source?.spec?.params ?? []) {
117
146
  if (specParam.type !== "SECRET") {
@@ -128,8 +157,16 @@ async function ejectSecretsFromInstance(instance) {
128
157
  }
129
158
  const projectId = match.groups.project;
130
159
  const secretId = match.groups.secret;
131
- await (0, secrets_1.transferSecretToKits)(projectId, secretId);
132
- secretsChanged.push(`${projectId}/${secretId}`);
160
+ const combinedId = `${projectId}/${secretId}`;
161
+ try {
162
+ await (0, secrets_1.transferSecretToKits)(projectId, secretId);
163
+ success.push(combinedId);
164
+ }
165
+ catch (err) {
166
+ fail.push(combinedId);
167
+ const message = err instanceof Error ? err.message : String(err);
168
+ (0, utils_1.logLabeledError)("extensions", "failed to change labels on " + combinedId + ": " + message);
169
+ }
133
170
  }
134
- return secretsChanged;
171
+ return { success: success, fail: fail };
135
172
  }
@@ -29,6 +29,7 @@ exports.isLocalPath = isLocalPath;
29
29
  exports.isLocalOrURLPath = isLocalOrURLPath;
30
30
  exports.getSourceOrigin = getSourceOrigin;
31
31
  exports.diagnoseAndFixProject = diagnoseAndFixProject;
32
+ exports.ensureInstanceSpec = ensureInstanceSpec;
32
33
  const clc = require("colorette");
33
34
  const ora = require("ora");
34
35
  const semver = require("semver");
@@ -870,3 +871,30 @@ async function diagnoseAndFixProject(options) {
870
871
  throw new error_1.FirebaseError("Unable to proceed until all issues are resolved.");
871
872
  }
872
873
  }
874
+ async function ensureInstanceSpec(instance) {
875
+ if (instance.config?.source?.spec) {
876
+ return instance;
877
+ }
878
+ const extensionRef = instance.config?.extensionRef ?? instance.extensionRef;
879
+ if (!extensionRef) {
880
+ return instance;
881
+ }
882
+ const ref = refs.parse(extensionRef);
883
+ const extensionVersion = instance.config?.extensionVersion ?? instance.extensionVersion ?? ref.version ?? "latest";
884
+ const extVersion = await (0, publisherApi_1.getExtensionVersion)(`${ref.publisherId}/${ref.extensionId}@${extensionVersion}`);
885
+ return {
886
+ ...instance,
887
+ config: {
888
+ ...instance.config,
889
+ source: {
890
+ ...instance.config?.source,
891
+ name: instance.config?.source?.name ?? extVersion.name,
892
+ state: instance.config?.source?.state ??
893
+ (extVersion.state === "PUBLISHED" ? "ACTIVE" : "STATE_UNSPECIFIED"),
894
+ packageUri: instance.config?.source?.packageUri ?? extVersion.sourceDownloadUri,
895
+ hash: instance.config?.source?.hash ?? extVersion.hash,
896
+ spec: extVersion.spec,
897
+ },
898
+ },
899
+ };
900
+ }
@@ -7,14 +7,18 @@ exports.formatExtensionsTable = formatExtensionsTable;
7
7
  exports.getMigratableInstances = getMigratableInstances;
8
8
  exports.promptInstanceSelection = promptInstanceSelection;
9
9
  exports.createMigrationPlan = createMigrationPlan;
10
+ exports.ensureInstanceUpToDate = ensureInstanceUpToDate;
10
11
  const clc = require("colorette");
11
12
  const Table = require("cli-table3");
12
13
  const error_1 = require("../error");
13
14
  const logger_1 = require("../logger");
14
15
  const utils_1 = require("../utils");
15
16
  const extensionsHelper_1 = require("./extensionsHelper");
16
- const extensionsApi_1 = require("./extensionsApi");
17
17
  const prompt_1 = require("../prompt");
18
+ const extensionsApi = require("./extensionsApi");
19
+ const refs = require("./refs");
20
+ const paramHelper = require("./paramHelper");
21
+ const updateHelper = require("./updateHelper");
18
22
  const replacements = require("./replacements.json");
19
23
  function getKitPackage(extensionRef, packageOverride) {
20
24
  if (packageOverride) {
@@ -101,7 +105,7 @@ async function promptInstanceSelection(migratableInstances, nonInteractive) {
101
105
  return selected;
102
106
  }
103
107
  async function createMigrationPlan(projectId, options) {
104
- const instances = await (0, extensionsApi_1.listInstances)(projectId);
108
+ const instances = await extensionsApi.listInstances(projectId);
105
109
  if (options.extInstance) {
106
110
  const foundInstance = instances.find((inst) => getInstanceId(inst) === options.extInstance);
107
111
  if (!foundInstance) {
@@ -169,3 +173,118 @@ async function createMigrationPlan(projectId, options) {
169
173
  }
170
174
  return promptInstanceSelection(migratable, options.nonInteractive);
171
175
  }
176
+ async function fetchOldSpec(instance, rawRef) {
177
+ if (instance.config.source?.spec) {
178
+ return instance.config.source.spec;
179
+ }
180
+ if (!rawRef) {
181
+ return undefined;
182
+ }
183
+ try {
184
+ const oldVersion = instance.config.extensionVersion;
185
+ const oldVersionRef = rawRef.includes("@")
186
+ ? rawRef
187
+ : oldVersion
188
+ ? `${rawRef}@${oldVersion}`
189
+ : rawRef;
190
+ logger_1.logger.debug(`[ensureInstanceUpToDate] Fetching oldSpec for ${oldVersionRef}...`);
191
+ const oldExtVersion = await extensionsApi.getExtensionVersion(oldVersionRef);
192
+ return oldExtVersion.spec;
193
+ }
194
+ catch (err) {
195
+ logger_1.logger.debug(`Could not fetch old spec for ${rawRef}:`, err);
196
+ return undefined;
197
+ }
198
+ }
199
+ async function getLatestExtensionVersionNumber(baseRef) {
200
+ try {
201
+ const extInfo = await extensionsApi.getExtension(baseRef);
202
+ return extInfo.latestApprovedVersion || extInfo.latestVersion;
203
+ }
204
+ catch (err) {
205
+ logger_1.logger.debug(`Could not fetch extension details for ${baseRef}:`, err);
206
+ return undefined;
207
+ }
208
+ }
209
+ async function ensureInstanceUpToDate(projectId, instance, options) {
210
+ const instanceId = getInstanceId(instance);
211
+ (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, `Checking whether extension instance ${clc.bold(instanceId)} is up to date...`);
212
+ const rawRef = getExtensionRef(instance);
213
+ if (!rawRef) {
214
+ return instance;
215
+ }
216
+ let baseRef;
217
+ let currentVersion;
218
+ try {
219
+ const parsed = refs.parse(rawRef);
220
+ baseRef = refs.toExtensionRef(parsed);
221
+ currentVersion = parsed.version || instance.config.source?.spec?.version;
222
+ }
223
+ catch (err) {
224
+ logger_1.logger.debug(`[ensureInstanceUpToDate] Could not parse extension reference '${rawRef}':`, err);
225
+ (0, utils_1.logLabeledWarning)(extensionsHelper_1.logPrefix, `Unable to parse extension reference ${clc.bold(rawRef)} to check for available updates.`);
226
+ const shouldContinue = await (0, prompt_1.confirm)({
227
+ message: `Do you want to proceed with migrating instance ${clc.bold(instanceId)} using its current configuration?`,
228
+ default: true,
229
+ nonInteractive: options?.nonInteractive,
230
+ force: options?.force,
231
+ });
232
+ if (!shouldContinue) {
233
+ throw new error_1.FirebaseError("Migration cancelled.");
234
+ }
235
+ return instance;
236
+ }
237
+ if (!currentVersion) {
238
+ return instance;
239
+ }
240
+ const latestVersion = await getLatestExtensionVersionNumber(baseRef);
241
+ if (!latestVersion || currentVersion === latestVersion) {
242
+ return instance;
243
+ }
244
+ (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, `Upgrading extension instance ${clc.bold(instanceId)} from version ${clc.bold(currentVersion)} to ${clc.bold(latestVersion)} to ensure a smooth migration...`);
245
+ const targetRef = `${baseRef}@${latestVersion}`;
246
+ let finalParams = {
247
+ ...instance.config.params,
248
+ ...(instance.config.systemParams ?? {}),
249
+ };
250
+ const newExtensionVersion = await extensionsApi.getExtensionVersion(targetRef);
251
+ const oldSpec = await fetchOldSpec(instance, rawRef);
252
+ if (oldSpec) {
253
+ logger_1.logger.debug(`[ensureInstanceUpToDate] Comparing oldSpec (${oldSpec.version}) with newSpec (${newExtensionVersion.spec.version})...`);
254
+ const paramBindings = await paramHelper.promptForNewParams({
255
+ spec: oldSpec,
256
+ newSpec: newExtensionVersion.spec,
257
+ currentParams: finalParams ?? {},
258
+ projectId,
259
+ instanceId,
260
+ });
261
+ finalParams = paramHelper.getBaseParamBindings(paramBindings);
262
+ logger_1.logger.debug(`[ensureInstanceUpToDate] Resulting finalParams:`, JSON.stringify(finalParams, null, 2));
263
+ }
264
+ else {
265
+ logger_1.logger.debug(`[ensureInstanceUpToDate] WARNING: Could not resolve oldSpec for instance ${instanceId}`);
266
+ }
267
+ if (finalParams["LOCATION"] && !finalParams["firebaseextensions.v1beta.function/location"]) {
268
+ finalParams["firebaseextensions.v1beta.function/location"] = finalParams["LOCATION"];
269
+ }
270
+ const { params, systemParams } = paramHelper.partitionParams(finalParams);
271
+ (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, `Updating instance ${clc.bold(instanceId)}...`);
272
+ try {
273
+ await updateHelper.update({
274
+ projectId,
275
+ instanceId,
276
+ extRef: targetRef,
277
+ canEmitEvents: Boolean(instance.config.allowedEventTypes?.length),
278
+ allowedEventTypes: instance.config.allowedEventTypes,
279
+ eventarcChannel: instance.config.eventarcChannel,
280
+ params,
281
+ systemParams,
282
+ });
283
+ }
284
+ catch (err) {
285
+ const message = err instanceof Error ? err.message : String(err);
286
+ throw new error_1.FirebaseError(`Failed to automatically upgrade extension instance ${instanceId} to version ${latestVersion}: ${message}. Please upgrade your extension instance manually using 'firebase ext:update ${instanceId}' before attempting migration.`, { original: err instanceof Error ? err : undefined });
287
+ }
288
+ const updatedInstance = await extensionsApi.getInstance(projectId, instanceId);
289
+ return updatedInstance ?? instance;
290
+ }
@@ -8,6 +8,7 @@ exports.getParamsForUpdate = getParamsForUpdate;
8
8
  exports.promptForNewParams = promptForNewParams;
9
9
  exports.readEnvFile = readEnvFile;
10
10
  exports.isSystemParam = isSystemParam;
11
+ exports.partitionParams = partitionParams;
11
12
  exports.populateDefaultParams = populateDefaultParams;
12
13
  const path = require("path");
13
14
  const clc = require("colorette");
@@ -16,6 +17,7 @@ const error_1 = require("../error");
16
17
  const logger_1 = require("../logger");
17
18
  const extensionsHelper_1 = require("./extensionsHelper");
18
19
  const askUserForParam = require("./askUserForParam");
20
+ const askUserForParam_1 = require("./askUserForParam");
19
21
  const env = require("../functions/env");
20
22
  const NONINTERACTIVE_ERROR_MESSAGE = "As of firebase-tools@11, `ext:install`, `ext:update` and `ext:configure` are interactive only commands. " +
21
23
  "To deploy an extension noninteractively, use an extensions manifest and `firebase deploy --only extensions`. " +
@@ -87,40 +89,78 @@ async function getParamsForUpdate(args) {
87
89
  }
88
90
  async function promptForNewParams(args) {
89
91
  const newParamBindingOptions = buildBindingOptionsWithBaseValue(args.currentParams);
90
- const firebaseProjectParams = await (0, extensionsHelper_1.getFirebaseProjectParams)(args.projectId);
91
- const sameParam = (param1) => (param2) => {
92
- return param1.type === param2.type && param1.param === param2.param;
93
- };
94
- const paramDiff = (left, right) => {
95
- return left.filter((aLeft) => !right.find(sameParam(aLeft)));
96
- };
97
- let combinedOldParams = args.spec.params.concat(args.spec.systemParams.filter((p) => !p.advanced) ?? []);
98
- let combinedNewParams = args.newSpec.params.concat(args.newSpec.systemParams.filter((p) => !p.advanced) ?? []);
99
- if (combinedOldParams.some((p) => p.param === "LOCATION") &&
100
- combinedNewParams.some((p) => p.param === "firebaseextensions.v1beta.function/location") &&
92
+ const allOldParams = (args.spec.params ?? []).concat(args.spec.systemParams ?? []);
93
+ const allNewParams = (args.newSpec.params ?? []).concat(args.newSpec.systemParams ?? []);
94
+ if (allOldParams.some((p) => p.param === "LOCATION") &&
95
+ allNewParams.some((p) => p.param === "firebaseextensions.v1beta.function/location") &&
101
96
  !!args.currentParams["LOCATION"]) {
102
97
  newParamBindingOptions["firebaseextensions.v1beta.function/location"] = {
103
98
  baseValue: args.currentParams["LOCATION"],
104
99
  };
105
100
  delete newParamBindingOptions["LOCATION"];
106
- combinedOldParams = combinedOldParams.filter((p) => p.param !== "LOCATION");
107
- combinedNewParams = combinedNewParams.filter((p) => p.param !== "firebaseextensions.v1beta.function/location");
108
101
  }
109
- const oldParams = combinedOldParams.filter((p) => Object.keys(args.currentParams).includes(p.param));
110
- let paramsDiffDeletions = paramDiff(oldParams, combinedNewParams);
111
- paramsDiffDeletions = (0, extensionsHelper_1.substituteParams)(paramsDiffDeletions, firebaseProjectParams);
112
- let paramsDiffAdditions = paramDiff(combinedNewParams, oldParams);
113
- paramsDiffAdditions = (0, extensionsHelper_1.substituteParams)(paramsDiffAdditions, firebaseProjectParams);
114
- if (paramsDiffDeletions.length) {
102
+ for (const newP of allNewParams) {
103
+ if (!newP.required && newParamBindingOptions[newP.param] === undefined) {
104
+ newParamBindingOptions[newP.param] = {
105
+ baseValue: newP.default ?? "",
106
+ };
107
+ }
108
+ }
109
+ const unassignedOldParams = allOldParams.filter((oldP) => {
110
+ if (oldP.param === "LOCATION" &&
111
+ allNewParams.some((p) => p.param === "firebaseextensions.v1beta.function/location")) {
112
+ return false;
113
+ }
114
+ return !allNewParams.some((newP) => newP.param === oldP.param);
115
+ });
116
+ if (unassignedOldParams.length) {
115
117
  logger_1.logger.info("The following params will no longer be used:");
116
- for (const param of paramsDiffDeletions) {
117
- logger_1.logger.info(clc.red(`- ${param.param}: ${args.currentParams[param.param.toUpperCase()]}`));
118
- delete newParamBindingOptions[param.param.toUpperCase()];
118
+ for (const param of unassignedOldParams) {
119
+ if (args.currentParams[param.param] !== undefined) {
120
+ logger_1.logger.info(clc.red(`- ${param.param}: ${args.currentParams[param.param]}`));
121
+ }
122
+ delete newParamBindingOptions[param.param];
123
+ }
124
+ }
125
+ const hasLocationSpec = allNewParams.some((p) => p.param === "firebaseextensions.v1beta.function/location");
126
+ const locationIsSet = !!newParamBindingOptions["firebaseextensions.v1beta.function/location"]?.baseValue ||
127
+ !!args.currentParams["firebaseextensions.v1beta.function/location"] ||
128
+ !!args.currentParams["LOCATION"];
129
+ const locationNotSet = hasLocationSpec && !locationIsSet;
130
+ const triggerAdvancedSystemParams = unassignedOldParams.length > 0 || locationNotSet;
131
+ const paramsToPrompt = [];
132
+ for (const newP of allNewParams) {
133
+ const oldP = allOldParams.find((p) => p.param === newP.param);
134
+ const currentVal = newParamBindingOptions[newP.param]?.baseValue;
135
+ const isSystem = isSystemParam(newP.param) ||
136
+ (args.newSpec.systemParams ?? []).some((p) => p.param === newP.param);
137
+ if (!oldP && !isSystem) {
138
+ paramsToPrompt.push(newP);
139
+ continue;
140
+ }
141
+ if (oldP && oldP.type !== newP.type) {
142
+ paramsToPrompt.push(newP);
143
+ continue;
144
+ }
145
+ if (currentVal !== undefined && currentVal !== "" && !(0, askUserForParam_1.checkResponse)(currentVal, newP)) {
146
+ paramsToPrompt.push(newP);
147
+ continue;
148
+ }
149
+ if (newP.required && (currentVal === undefined || currentVal === "")) {
150
+ paramsToPrompt.push(newP);
151
+ continue;
152
+ }
153
+ if (triggerAdvancedSystemParams && (isSystem || newP.advanced)) {
154
+ paramsToPrompt.push(newP);
155
+ continue;
119
156
  }
120
157
  }
121
- if (paramsDiffAdditions.length) {
122
- logger_1.logger.info("To update this instance, configure the following new parameters:");
123
- for (const param of paramsDiffAdditions) {
158
+ let uniqueParamsToPrompt = paramsToPrompt.filter((p, index, self) => index === self.findIndex((tp) => tp.param === p.param));
159
+ if (uniqueParamsToPrompt.length) {
160
+ const firebaseProjectParams = await (0, extensionsHelper_1.getFirebaseProjectParams)(args.projectId);
161
+ uniqueParamsToPrompt = (0, extensionsHelper_1.substituteParams)(uniqueParamsToPrompt, firebaseProjectParams);
162
+ logger_1.logger.info("To update this instance, configure the following parameters:");
163
+ for (const param of uniqueParamsToPrompt) {
124
164
  const chosenValue = await askUserForParam.askForParam({
125
165
  projectId: args.projectId,
126
166
  instanceId: args.instanceId,
@@ -144,6 +184,19 @@ function isSystemParam(paramName) {
144
184
  const regex = /^firebaseextensions\.[a-zA-Z0-9\.]*\//;
145
185
  return regex.test(paramName);
146
186
  }
187
+ function partitionParams(params) {
188
+ const userParams = {};
189
+ const systemParams = {};
190
+ for (const [key, value] of Object.entries(params)) {
191
+ if (isSystemParam(key)) {
192
+ systemParams[key] = value;
193
+ }
194
+ else {
195
+ userParams[key] = value;
196
+ }
197
+ }
198
+ return { params: userParams, systemParams };
199
+ }
147
200
  function populateDefaultParams(params, spec) {
148
201
  const ret = { ...params };
149
202
  for (const p of spec.params) {
@@ -32,6 +32,9 @@ async function grantFirexServiceAgentSecretAdminRole(secret) {
32
32
  return secretManagerApi.ensureServiceAgentRole(secret, [saEmail], "roles/secretmanager.admin");
33
33
  }
34
34
  async function getManagedSecrets(instance) {
35
+ if (!instance.config?.source?.spec) {
36
+ return [];
37
+ }
35
38
  return (await Promise.all(getActiveSecrets(instance.config.source.spec, instance.config.params).map(async (secretResourceName) => {
36
39
  const secret = secretManagerApi.parseSecretResourceName(secretResourceName);
37
40
  const labels = (await secretManagerApi.getSecret(secret.projectId, secret.name)).labels;
@@ -53,13 +53,14 @@ function warningUpdateToOtherSource(sourceOrigin) {
53
53
  logger_1.logger.info(warning);
54
54
  }
55
55
  async function update(updateOptions) {
56
- const { projectId, instanceId, source, extRef, params, canEmitEvents, allowedEventTypes, eventarcChannel, } = updateOptions;
56
+ const { projectId, instanceId, source, extRef, params, systemParams, canEmitEvents, allowedEventTypes, eventarcChannel, } = updateOptions;
57
57
  if (extRef) {
58
58
  return await extensionsApi.updateInstanceFromRegistry({
59
59
  projectId,
60
60
  instanceId,
61
61
  extRef,
62
62
  params,
63
+ systemParams,
63
64
  canEmitEvents,
64
65
  allowedEventTypes,
65
66
  eventarcChannel,
@@ -71,6 +72,7 @@ async function update(updateOptions) {
71
72
  instanceId,
72
73
  extensionSource: source,
73
74
  params,
75
+ systemParams,
74
76
  canEmitEvents,
75
77
  allowedEventTypes,
76
78
  eventarcChannel,