firebase-tools-with-isolate 13.15.0-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 (235) 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 +5 -1
  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 +3 -2
  61. package/lib/dataconnect/dataplaneClient.js +12 -9
  62. package/lib/dataconnect/ensureApis.js +6 -1
  63. package/lib/dataconnect/fileUtils.js +29 -12
  64. package/lib/dataconnect/freeTrial.js +45 -9
  65. package/lib/dataconnect/load.js +3 -1
  66. package/lib/dataconnect/provisionCloudSql.js +41 -24
  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 +95 -5
  76. package/lib/deploy/extensions/prepare.js +89 -42
  77. package/lib/deploy/extensions/release.js +17 -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/build.js +5 -5
  82. package/lib/deploy/functions/checkIam.js +7 -2
  83. package/lib/deploy/functions/deploy.js +12 -12
  84. package/lib/deploy/functions/ensure.js +11 -3
  85. package/lib/deploy/functions/params.js +5 -3
  86. package/lib/deploy/functions/prepare.js +18 -3
  87. package/lib/deploy/functions/release/index.js +4 -0
  88. package/lib/deploy/functions/release/planner.js +2 -1
  89. package/lib/deploy/functions/runtimes/discovery/index.js +6 -2
  90. package/lib/deploy/functions/runtimes/discovery/parsing.js +1 -1
  91. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +46 -0
  92. package/lib/deploy/functions/runtimes/node/index.js +5 -0
  93. package/lib/deploy/functions/services/auth.js +34 -3
  94. package/lib/deploy/functions/services/index.js +2 -0
  95. package/lib/deploy/index.js +8 -5
  96. package/lib/deploy/lifecycleHooks.js +2 -1
  97. package/lib/emulator/apphosting/config.js +27 -0
  98. package/lib/emulator/apphosting/index.js +38 -0
  99. package/lib/emulator/apphosting/serve.js +50 -0
  100. package/lib/emulator/apphosting/utils.js +18 -0
  101. package/lib/emulator/auth/handlers.js +27 -0
  102. package/lib/emulator/auth/operations.js +41 -2
  103. package/lib/emulator/auth/state.js +2 -1
  104. package/lib/emulator/commandUtils.js +8 -3
  105. package/lib/emulator/constants.js +11 -1
  106. package/lib/emulator/controller.js +59 -6
  107. package/lib/emulator/dataconnect/pg-gateway/auth/base-auth-flow.js +11 -0
  108. package/lib/emulator/dataconnect/pg-gateway/auth/cert.js +58 -0
  109. package/lib/emulator/dataconnect/pg-gateway/auth/index.js +22 -0
  110. package/lib/emulator/dataconnect/pg-gateway/auth/md5.js +124 -0
  111. package/lib/emulator/dataconnect/pg-gateway/auth/password.js +54 -0
  112. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/sasl-mechanism.js +34 -0
  113. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/scram-sha-256.js +270 -0
  114. package/lib/emulator/dataconnect/pg-gateway/auth/trust.js +2 -0
  115. package/lib/emulator/dataconnect/pg-gateway/backend-error.js +75 -0
  116. package/lib/emulator/dataconnect/pg-gateway/buffer-reader.js +54 -0
  117. package/lib/emulator/dataconnect/pg-gateway/buffer-writer.js +79 -0
  118. package/lib/emulator/dataconnect/pg-gateway/connection.js +315 -0
  119. package/lib/emulator/dataconnect/pg-gateway/connection.types.js +8 -0
  120. package/lib/emulator/dataconnect/pg-gateway/crypto.js +40 -0
  121. package/lib/emulator/dataconnect/pg-gateway/duplex.js +53 -0
  122. package/lib/emulator/dataconnect/pg-gateway/index.js +27 -0
  123. package/lib/emulator/dataconnect/pg-gateway/message-buffer.js +82 -0
  124. package/lib/emulator/dataconnect/pg-gateway/message-codes.js +52 -0
  125. package/lib/emulator/dataconnect/pg-gateway/platforms/node/index.js +16 -0
  126. package/lib/emulator/dataconnect/pg-gateway/polyfills/readable-stream-async-iterator.js +35 -0
  127. package/lib/emulator/dataconnect/pg-gateway/utils.js +40 -0
  128. package/lib/emulator/dataconnect/pgliteServer.js +95 -0
  129. package/lib/emulator/dataconnectEmulator.js +58 -75
  130. package/lib/emulator/dataconnectToolkitController.js +44 -0
  131. package/lib/emulator/downloadableEmulators.js +30 -19
  132. package/lib/emulator/emulatorLogger.js +3 -0
  133. package/lib/emulator/env.js +3 -0
  134. package/lib/emulator/eventarcEmulator.js +1 -1
  135. package/lib/emulator/extensionsEmulator.js +38 -6
  136. package/lib/emulator/functionsEmulator.js +115 -42
  137. package/lib/emulator/functionsEmulatorShared.js +18 -1
  138. package/lib/emulator/functionsRuntimeWorker.js +2 -1
  139. package/lib/emulator/hub.js +13 -9
  140. package/lib/emulator/hubExport.js +10 -3
  141. package/lib/emulator/loggingEmulator.js +2 -2
  142. package/lib/emulator/portUtils.js +11 -11
  143. package/lib/emulator/registry.js +2 -0
  144. package/lib/emulator/storage/persistence.js +2 -2
  145. package/lib/emulator/storage/rules/runtime.js +1 -1
  146. package/lib/emulator/taskQueue.js +348 -0
  147. package/lib/emulator/tasksEmulator.js +240 -0
  148. package/lib/emulator/types.js +6 -0
  149. package/lib/emulator/ui.js +51 -25
  150. package/lib/error.js +31 -1
  151. package/lib/experiments.js +5 -0
  152. package/lib/extensions/askUserForEventsConfig.js +18 -8
  153. package/lib/extensions/askUserForParam.js +2 -1
  154. package/lib/extensions/displayExtensionInfo.js +5 -5
  155. package/lib/extensions/emulator/triggerHelper.js +1 -1
  156. package/lib/extensions/extensionsApi.js +15 -11
  157. package/lib/extensions/extensionsHelper.js +39 -8
  158. package/lib/extensions/localHelper.js +32 -1
  159. package/lib/extensions/refs.js +26 -11
  160. package/lib/extensions/runtimes/common.js +215 -0
  161. package/lib/extensions/runtimes/node.js +401 -0
  162. package/lib/extensions/types.js +67 -1
  163. package/lib/extensions/warnings.js +5 -2
  164. package/lib/firestore/api.js +2 -1
  165. package/lib/firestore/checkDatabaseType.js +10 -3
  166. package/lib/firestore/delete.js +11 -0
  167. package/lib/firestore/options.js +7 -0
  168. package/lib/frameworks/angular/index.js +15 -3
  169. package/lib/frameworks/constants.js +2 -2
  170. package/lib/frameworks/flutter/index.js +6 -6
  171. package/lib/frameworks/flutter/utils.js +34 -1
  172. package/lib/frameworks/next/constants.js +1 -1
  173. package/lib/frameworks/next/index.js +45 -17
  174. package/lib/frameworks/next/utils.js +57 -4
  175. package/lib/frameworks/vite/index.js +2 -2
  176. package/lib/fsutils.js +13 -1
  177. package/lib/functions/constants.js +4 -0
  178. package/lib/functions/events/v1.js +9 -2
  179. package/lib/gcp/apphosting.js +1 -1
  180. package/lib/gcp/cloudmonitoring.js +3 -3
  181. package/lib/gcp/cloudsql/cloudsqladmin.js +32 -20
  182. package/lib/gcp/cloudsql/connect.js +49 -37
  183. package/lib/gcp/cloudsql/interactive.js +49 -0
  184. package/lib/gcp/cloudsql/permissions.js +165 -0
  185. package/lib/gcp/devConnect.js +38 -1
  186. package/lib/gcp/firestore.js +5 -1
  187. package/lib/gcp/secretManager.js +12 -5
  188. package/lib/getProjectNumber.js +1 -1
  189. package/lib/init/features/apphosting.js +15 -0
  190. package/lib/init/features/dataconnect/index.js +166 -121
  191. package/lib/init/features/dataconnect/sdk.js +90 -81
  192. package/lib/init/features/emulators.js +2 -15
  193. package/lib/init/features/firestore/index.js +20 -1
  194. package/lib/init/features/firestore/indexes.js +4 -4
  195. package/lib/init/features/genkit/index.js +444 -0
  196. package/lib/init/features/hosting/index.js +2 -2
  197. package/lib/init/features/index.js +1 -1
  198. package/lib/init/features/project.js +6 -6
  199. package/lib/init/features/storage.js +0 -2
  200. package/lib/init/index.js +1 -0
  201. package/lib/init/spawn.js +23 -2
  202. package/lib/logger.js +2 -2
  203. package/lib/management/projects.js +24 -4
  204. package/lib/projectUtils.js +1 -1
  205. package/lib/prompt.js +22 -1
  206. package/lib/rc.js +1 -8
  207. package/lib/requireAuth.js +19 -5
  208. package/lib/requireDatabaseInstance.js +1 -1
  209. package/lib/requirePermissions.js +1 -1
  210. package/lib/responseToError.js +5 -2
  211. package/lib/rulesDeploy.js +1 -1
  212. package/lib/templates.js +2 -2
  213. package/lib/utils.js +16 -11
  214. package/lib/vsCodeUtils.js +8 -0
  215. package/package.json +8 -7
  216. package/schema/connector-yaml.json +57 -17
  217. package/schema/firebase-config.json +36 -0
  218. package/templates/extensions/javascript/package.lint.json +2 -2
  219. package/templates/extensions/javascript/package.nolint.json +2 -2
  220. package/templates/extensions/typescript/package.lint.json +2 -2
  221. package/templates/extensions/typescript/package.nolint.json +2 -2
  222. package/templates/genkit/firebase.0.9.0.template +57 -0
  223. package/templates/init/apphosting/apphosting.yaml +23 -0
  224. package/templates/init/dataconnect/connector.yaml +4 -3
  225. package/templates/init/dataconnect/dataconnect-fdccompatiblemode.yaml +12 -0
  226. package/templates/init/dataconnect/dataconnect.yaml +6 -6
  227. package/templates/init/dataconnect/mutations.gql +44 -29
  228. package/templates/init/dataconnect/queries.gql +65 -38
  229. package/templates/init/dataconnect/schema.gql +38 -21
  230. package/templates/init/functions/javascript/package.lint.json +2 -2
  231. package/templates/init/functions/javascript/package.nolint.json +2 -2
  232. package/templates/init/functions/typescript/package.lint.json +2 -2
  233. package/templates/init/functions/typescript/package.nolint.json +2 -2
  234. package/lib/ensureCloudResourceLocation.js +0 -12
  235. package/lib/init/features/genkit.js +0 -53
@@ -1,52 +1,78 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EmulatorUI = void 0;
4
+ const express = require("express");
5
+ const path = require("path");
4
6
  const types_1 = require("./types");
5
7
  const downloadableEmulators = require("./downloadableEmulators");
6
8
  const registry_1 = require("./registry");
7
9
  const error_1 = require("../error");
10
+ const emulatorLogger_1 = require("./emulatorLogger");
8
11
  const constants_1 = require("./constants");
9
12
  const track_1 = require("../track");
10
13
  const ExpressBasedEmulator_1 = require("./ExpressBasedEmulator");
11
14
  const experiments_1 = require("../experiments");
12
- class EmulatorUI {
15
+ class EmulatorUI extends ExpressBasedEmulator_1.ExpressBasedEmulator {
13
16
  constructor(args) {
17
+ super({
18
+ listen: args.listen,
19
+ });
14
20
  this.args = args;
15
21
  }
16
- start() {
22
+ async start() {
23
+ await super.start();
24
+ }
25
+ async createExpressApp() {
17
26
  if (!registry_1.EmulatorRegistry.isRunning(types_1.Emulators.HUB)) {
18
27
  throw new error_1.FirebaseError(`Cannot start ${constants_1.Constants.description(types_1.Emulators.UI)} without ${constants_1.Constants.description(types_1.Emulators.HUB)}!`);
19
28
  }
20
- const { auto_download: autoDownload, projectId } = this.args;
21
- const env = {
22
- LISTEN: JSON.stringify(ExpressBasedEmulator_1.ExpressBasedEmulator.listenOptionsFromSpecs(this.args.listen)),
23
- GCLOUD_PROJECT: projectId,
24
- [constants_1.Constants.FIREBASE_EMULATOR_HUB]: registry_1.EmulatorRegistry.url(types_1.Emulators.HUB).host,
25
- };
26
- const session = (0, track_1.emulatorSession)();
27
- if (session) {
28
- env[constants_1.Constants.FIREBASE_GA_SESSION] = JSON.stringify(session);
29
- }
29
+ const hub = registry_1.EmulatorRegistry.get(types_1.Emulators.HUB);
30
+ const app = await super.createExpressApp();
31
+ const { projectId } = this.args;
30
32
  const enabledExperiments = Object.keys(experiments_1.ALL_EXPERIMENTS).filter((experimentName) => (0, experiments_1.isEnabled)(experimentName));
31
- env[constants_1.Constants.FIREBASE_ENABLED_EXPERIMENTS] = JSON.stringify(enabledExperiments);
32
- return downloadableEmulators.start(types_1.Emulators.UI, { auto_download: autoDownload }, env);
33
+ const emulatorGaSession = (0, track_1.emulatorSession)();
34
+ await downloadableEmulators.downloadIfNecessary(types_1.Emulators.UI);
35
+ const downloadDetails = downloadableEmulators.getDownloadDetails(types_1.Emulators.UI);
36
+ const webDir = path.join(downloadDetails.unzipDir, "client");
37
+ app.get("/api/config", this.jsonHandler(() => {
38
+ const json = {
39
+ projectId,
40
+ experiments: [],
41
+ ...hub.getRunningEmulatorsMapping(),
42
+ };
43
+ if (emulatorGaSession) {
44
+ json.analytics = emulatorGaSession;
45
+ }
46
+ if (enabledExperiments) {
47
+ json.experiments = enabledExperiments;
48
+ }
49
+ return Promise.resolve(json);
50
+ }));
51
+ app.use(express.static(webDir));
52
+ app.get("*", (_, res) => {
53
+ res.sendFile(path.join(webDir, "index.html"));
54
+ });
55
+ return app;
33
56
  }
34
57
  connect() {
35
58
  return Promise.resolve();
36
59
  }
37
- stop() {
38
- return downloadableEmulators.stop(types_1.Emulators.UI);
39
- }
40
- getInfo() {
41
- return {
42
- name: this.getName(),
43
- host: this.args.listen[0].address,
44
- port: this.args.listen[0].port,
45
- pid: downloadableEmulators.getPID(types_1.Emulators.UI),
46
- };
47
- }
48
60
  getName() {
49
61
  return types_1.Emulators.UI;
50
62
  }
63
+ jsonHandler(handler) {
64
+ return (req, res) => {
65
+ handler(req).then((body) => {
66
+ res.status(200).json(body);
67
+ }, (err) => {
68
+ emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.UI).log("ERROR", err);
69
+ res.status(500).json({
70
+ message: err.message,
71
+ stack: err.stack,
72
+ raw: err,
73
+ });
74
+ });
75
+ };
76
+ }
51
77
  }
52
78
  exports.EmulatorUI = EmulatorUI;
package/lib/error.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBillingError = exports.FirebaseError = void 0;
3
+ exports.isBillingError = exports.getError = exports.getErrStatus = exports.getErrMsg = exports.FirebaseError = void 0;
4
4
  const lodash_1 = require("lodash");
5
5
  const DEFAULT_CHILDREN = [];
6
6
  const DEFAULT_EXIT = 1;
@@ -18,6 +18,36 @@ class FirebaseError extends Error {
18
18
  }
19
19
  }
20
20
  exports.FirebaseError = FirebaseError;
21
+ function getErrMsg(err, defaultMsg) {
22
+ if (err instanceof Error) {
23
+ return err.message;
24
+ }
25
+ else if (typeof err === "string") {
26
+ return err;
27
+ }
28
+ else if (defaultMsg) {
29
+ return defaultMsg;
30
+ }
31
+ return JSON.stringify(err);
32
+ }
33
+ exports.getErrMsg = getErrMsg;
34
+ function isObject(value) {
35
+ return typeof value === "object" && value !== null;
36
+ }
37
+ function getErrStatus(err, defaultStatus) {
38
+ if (isObject(err) && err.status && typeof err.status === "number") {
39
+ return err.status;
40
+ }
41
+ return defaultStatus || DEFAULT_STATUS;
42
+ }
43
+ exports.getErrStatus = getErrStatus;
44
+ function getError(err) {
45
+ if (err instanceof Error) {
46
+ return err;
47
+ }
48
+ return Error(getErrMsg(err));
49
+ }
50
+ exports.getError = getError;
21
51
  function isBillingError(e) {
22
52
  return !!e.context?.body?.error?.details?.find((d) => {
23
53
  return (d.violations?.find((v) => v.type === "serviceusage/billing-enabled") ||
@@ -56,6 +56,10 @@ exports.ALL_EXPERIMENTS = experiments({
56
56
  emulatoruisnapshot: {
57
57
  shortDescription: "Load pre-release versions of the emulator UI",
58
58
  },
59
+ emulatorapphosting: {
60
+ shortDescription: "App Hosting emulator",
61
+ public: false,
62
+ },
59
63
  webframeworks: {
60
64
  shortDescription: "Native support for popular web frameworks",
61
65
  fullDescription: "Adds support for popular web frameworks such as Next.js " +
@@ -105,6 +109,7 @@ exports.ALL_EXPERIMENTS = experiments({
105
109
  fdccompatiblemode: {
106
110
  shortDescription: "Enable Data Connect schema migrations in Compatible Mode",
107
111
  fullDescription: "Enable Data Connect schema migrations in Compatible Mode",
112
+ default: true,
108
113
  public: false,
109
114
  },
110
115
  });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.askForEventArcLocation = exports.askShouldCollectEventsConfig = exports.askForAllowedEventTypes = exports.askForEventsConfig = exports.checkAllowedEventTypesResponse = void 0;
3
+ exports.askForEventArcLocation = exports.EXTENSIONS_DEFAULT_EVENT_ARC_REGION = exports.ALLOWED_EVENT_ARC_REGIONS = exports.askShouldCollectEventsConfig = exports.askForAllowedEventTypes = exports.getEventArcChannel = exports.askForEventsConfig = exports.checkAllowedEventTypesResponse = void 0;
4
4
  const prompt_1 = require("../prompt");
5
5
  const extensionsApi = require("../extensions/extensionsApi");
6
6
  const utils = require("../utils");
@@ -22,7 +22,7 @@ function checkAllowedEventTypesResponse(response, validEvents) {
22
22
  }
23
23
  exports.checkAllowedEventTypesResponse = checkAllowedEventTypesResponse;
24
24
  async function askForEventsConfig(events, projectId, instanceId) {
25
- logger_1.logger.info(`\n${clc.bold("Enable Events")}: ${(0, marked_1.marked)("If you enable events, you can write custom event handlers ([https://firebase.google.com/docs/extensions/install-extensions#eventarc](https://firebase.google.com/docs/extensions/install-extensions#eventarc)) that respond to these events.\n\nYou can always enable or disable events later. Events will be emitted via Eventarc. Fees apply ([https://cloud.google.com/eventarc/pricing](https://cloud.google.com/eventarc/pricing)).")}`);
25
+ logger_1.logger.info(`\n${clc.bold("Enable Events")}: ${await (0, marked_1.marked)("If you enable events, you can write custom event handlers ([https://firebase.google.com/docs/extensions/install-extensions#eventarc](https://firebase.google.com/docs/extensions/install-extensions#eventarc)) that respond to these events.\n\nYou can always enable or disable events later. Events will be emitted via Eventarc. Fees apply ([https://cloud.google.com/eventarc/pricing](https://cloud.google.com/eventarc/pricing)).")}`);
26
26
  if (!(await askShouldCollectEventsConfig())) {
27
27
  return undefined;
28
28
  }
@@ -37,11 +37,15 @@ async function askForEventsConfig(events, projectId, instanceId) {
37
37
  const preselectedTypes = existingInstance?.config.allowedEventTypes ?? [];
38
38
  const oldLocation = existingInstance?.config.eventarcChannel?.split("/")[3];
39
39
  const location = await askForEventArcLocation(oldLocation);
40
- const channel = `projects/${projectId}/locations/${location}/channels/firebase`;
40
+ const channel = getEventArcChannel(projectId, location);
41
41
  const allowedEventTypes = await askForAllowedEventTypes(events, preselectedTypes);
42
42
  return { channel, allowedEventTypes };
43
43
  }
44
44
  exports.askForEventsConfig = askForEventsConfig;
45
+ function getEventArcChannel(projectId, location) {
46
+ return `projects/${projectId}/locations/${location}/channels/firebase`;
47
+ }
48
+ exports.getEventArcChannel = getEventArcChannel;
45
49
  async function askForAllowedEventTypes(eventDescriptors, preselectedTypes) {
46
50
  let valid = false;
47
51
  let response = [];
@@ -74,21 +78,27 @@ async function askShouldCollectEventsConfig() {
74
78
  });
75
79
  }
76
80
  exports.askShouldCollectEventsConfig = askShouldCollectEventsConfig;
81
+ exports.ALLOWED_EVENT_ARC_REGIONS = [
82
+ "us-central1",
83
+ "us-west1",
84
+ "europe-west4",
85
+ "asia-northeast1",
86
+ ];
87
+ exports.EXTENSIONS_DEFAULT_EVENT_ARC_REGION = "us-central1";
77
88
  async function askForEventArcLocation(preselectedLocation) {
78
89
  let valid = false;
79
- const allowedRegions = ["us-central1", "us-west1", "europe-west4", "asia-northeast1"];
80
90
  let location = "";
81
91
  while (!valid) {
82
92
  location = await (0, prompt_1.promptOnce)({
83
93
  name: "input",
84
94
  type: "list",
85
- default: preselectedLocation ?? "us-central1",
95
+ default: preselectedLocation ?? exports.EXTENSIONS_DEFAULT_EVENT_ARC_REGION,
86
96
  message: "Which location would you like the Eventarc channel to live in? We recommend using the default option. A channel location that differs from the extension's Cloud Functions location can incur egress cost.",
87
- choices: allowedRegions.map((e) => ({ checked: false, value: e })),
97
+ choices: exports.ALLOWED_EVENT_ARC_REGIONS.map((e) => ({ checked: false, value: e })),
88
98
  });
89
- valid = allowedRegions.includes(location);
99
+ valid = exports.ALLOWED_EVENT_ARC_REGIONS.includes(location);
90
100
  if (!valid) {
91
- utils.logWarning(`Unexpected EventArc region '${location}' was specified. Allowed regions: ${allowedRegions.join(", ")}`);
101
+ utils.logWarning(`Unexpected EventArc region '${location}' was specified. Allowed regions: ${exports.ALLOWED_EVENT_ARC_REGIONS.join(", ")}`);
92
102
  }
93
103
  }
94
104
  return location;
@@ -254,7 +254,7 @@ async function promptReconfigureSecret(projectId, instanceId, paramSpec) {
254
254
  ],
255
255
  });
256
256
  switch (action) {
257
- case SecretUpdateAction.SET_NEW:
257
+ case SecretUpdateAction.SET_NEW: {
258
258
  let secret;
259
259
  let secretName;
260
260
  if (paramSpec.default) {
@@ -287,6 +287,7 @@ async function promptReconfigureSecret(projectId, instanceId, paramSpec) {
287
287
  else {
288
288
  return "";
289
289
  }
290
+ }
290
291
  case SecretUpdateAction.LEAVE:
291
292
  default:
292
293
  return paramSpec.default || "";
@@ -49,7 +49,7 @@ async function displayExtensionVersionInfo(args) {
49
49
  if (extensionVersion.buildSourceUri) {
50
50
  const buildSourceUri = new URL(extensionVersion.buildSourceUri);
51
51
  buildSourceUri.pathname = path.join(buildSourceUri.pathname, extensionVersion.extensionRoot ?? "");
52
- lines.push(`${clc.bold("Source in GitHub:")} ${buildSourceUri}`);
52
+ lines.push(`${clc.bold("Source in GitHub:")} ${buildSourceUri.toString()}`);
53
53
  }
54
54
  else {
55
55
  lines.push(`${clc.bold("Source download URI:")} ${extensionVersion.sourceDownloadUri ?? "-"}`);
@@ -101,24 +101,24 @@ function displayResources(spec) {
101
101
  break;
102
102
  default:
103
103
  }
104
- return ` - ${clc.blue(`${resource.name} (${type})`)}${resource.description ? `: ${resource.description}` : ""}`;
104
+ return ` - ${clc.blueBright(`${resource.name} (${type})`)}${resource.description ? `: ${resource.description}` : ""}`;
105
105
  });
106
106
  lines.push(...new Set(spec.lifecycleEvents?.map((event) => {
107
- return ` - ${clc.blue(`${event.taskQueueTriggerFunction} (Cloud Task queue)`)}`;
107
+ return ` - ${clc.blueBright(`${event.taskQueueTriggerFunction} (Cloud Task queue)`)}`;
108
108
  })));
109
109
  lines.push(...spec.params
110
110
  .filter((param) => {
111
111
  return param.type === "SECRET";
112
112
  })
113
113
  .map((param) => {
114
- return ` - ${clc.blue(`${param.param} (Cloud Secret Manager secret)`)}`;
114
+ return ` - ${clc.blueBright(`${param.param} (Cloud Secret Manager secret)`)}`;
115
115
  }));
116
116
  return clc.bold("Resources created:\n") + (lines.length ? lines.join("\n") : " - None");
117
117
  }
118
118
  exports.displayResources = displayResources;
119
119
  async function retrieveRoleInfo(role) {
120
120
  const res = await iam.getRole(role);
121
- return ` - ${clc.yellow(res.title)}${res.description ? `: ${res.description}` : ""}`;
121
+ return ` - ${clc.yellow(res.title || res.name)}${res.description ? `: ${res.description}` : ""}`;
122
122
  }
123
123
  exports.retrieveRoleInfo = retrieveRoleInfo;
124
124
  async function displayRoles(roles) {
@@ -58,7 +58,7 @@ function functionResourceToEmulatedTriggerDefintion(resource, systemParams = {})
58
58
  };
59
59
  }
60
60
  else {
61
- emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.FUNCTIONS).log("WARN", `Function '${resource.name} is missing a trigger in extension.yaml. Please add one, as triggers defined in code are ignored.`);
61
+ emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.FUNCTIONS).log("WARN", `Function '${resource.name}' is missing a trigger in extension.yaml. Please add one, as triggers defined in code are ignored.`);
62
62
  }
63
63
  return etd;
64
64
  }
@@ -9,16 +9,18 @@ const error_1 = require("../error");
9
9
  const logger_1 = require("../logger");
10
10
  const operationPoller = require("../operation-poller");
11
11
  const refs = require("./refs");
12
+ const types_1 = require("./types");
12
13
  const EXTENSIONS_API_VERSION = "v1beta";
13
14
  const PAGE_SIZE_MAX = 100;
14
15
  const extensionsApiClient = new apiv2_1.Client({
15
16
  urlPrefix: (0, api_1.extensionsOrigin)(),
16
17
  apiVersion: EXTENSIONS_API_VERSION,
17
18
  });
18
- async function createInstanceHelper(projectId, instanceId, config, validateOnly = false) {
19
+ async function createInstanceHelper(projectId, instanceId, config, labels, validateOnly = false) {
19
20
  const createRes = await extensionsApiClient.post(`/projects/${projectId}/instances/`, {
20
21
  name: `projects/${projectId}/instances/${instanceId}`,
21
22
  config,
23
+ labels,
22
24
  }, {
23
25
  queryParams: {
24
26
  validateOnly: validateOnly ? "true" : "false",
@@ -62,7 +64,7 @@ async function createInstance(args) {
62
64
  if (args.eventarcChannel) {
63
65
  config.eventarcChannel = args.eventarcChannel;
64
66
  }
65
- return createInstanceHelper(args.projectId, args.instanceId, config, args.validateOnly);
67
+ return await createInstanceHelper(args.projectId, args.instanceId, config, args.labels, args.validateOnly);
66
68
  }
67
69
  exports.createInstance = createInstance;
68
70
  async function deleteInstance(projectId, instanceId) {
@@ -79,10 +81,12 @@ exports.deleteInstance = deleteInstance;
79
81
  async function getInstance(projectId, instanceId) {
80
82
  try {
81
83
  const res = await extensionsApiClient.get(`/projects/${projectId}/instances/${instanceId}`);
82
- return res.body;
84
+ if ((0, types_1.isExtensionInstance)(res.body)) {
85
+ return res.body;
86
+ }
83
87
  }
84
88
  catch (err) {
85
- if (err.status === 404) {
89
+ if ((0, error_1.getErrStatus)(err) === 404) {
86
90
  throw new error_1.FirebaseError(`Extension instance '${clc.bold(instanceId)}' not found in project '${clc.bold(projectId)}'.`, { status: 404 });
87
91
  }
88
92
  throw err;
@@ -229,7 +233,7 @@ function populateSpec(spec) {
229
233
  }
230
234
  }
231
235
  catch (err) {
232
- logger_1.logger.debug(`[ext] failed to parse resource properties yaml: ${err}`);
236
+ logger_1.logger.debug(`[ext] failed to parse resource properties yaml: ${(0, error_1.getErrMsg)(err)}`);
233
237
  }
234
238
  }
235
239
  spec.params = spec.params ?? [];
@@ -275,13 +279,13 @@ async function getExtensionVersion(extensionVersionRef) {
275
279
  return res.body;
276
280
  }
277
281
  catch (err) {
278
- if (err.status === 404) {
282
+ if ((0, error_1.getErrStatus)(err) === 404) {
279
283
  throw refNotFoundError(ref);
280
284
  }
281
285
  else if (err instanceof error_1.FirebaseError) {
282
286
  throw err;
283
287
  }
284
- throw new error_1.FirebaseError(`Failed to query the extension version '${clc.bold(extensionVersionRef)}': ${err}`);
288
+ throw new error_1.FirebaseError(`Failed to query the extension version '${clc.bold(extensionVersionRef)}': ${(0, error_1.getErrMsg)(err)}`);
285
289
  }
286
290
  }
287
291
  exports.getExtensionVersion = getExtensionVersion;
@@ -335,14 +339,14 @@ async function getExtension(extensionRef) {
335
339
  return res.body;
336
340
  }
337
341
  catch (err) {
338
- if (err.status === 404) {
342
+ if ((0, error_1.getErrStatus)(err) === 404) {
339
343
  throw refNotFoundError(ref);
340
344
  }
341
345
  else if (err instanceof error_1.FirebaseError) {
342
346
  throw err;
343
347
  }
344
- throw new error_1.FirebaseError(`Failed to query the extension '${clc.bold(extensionRef)}': ${err}`, {
345
- status: err.status,
348
+ throw new error_1.FirebaseError(`Failed to query the extension '${clc.bold(extensionRef)}': ${(0, error_1.getErrMsg)(err)}`, {
349
+ status: (0, error_1.getErrStatus)(err),
346
350
  });
347
351
  }
348
352
  }
@@ -351,6 +355,6 @@ function refNotFoundError(ref) {
351
355
  return new error_1.FirebaseError(`The extension reference '${clc.bold(ref.version ? refs.toExtensionVersionRef(ref) : refs.toExtensionRef(ref))}' doesn't exist. This could happen for two reasons:\n` +
352
356
  ` -The publisher ID '${clc.bold(ref.publisherId)}' doesn't exist or could be misspelled\n` +
353
357
  ` -The name of the ${ref.version ? "extension version" : "extension"} '${clc.bold(ref.version ? `${ref.extensionId}@${ref.version}` : ref.extensionId)}' doesn't exist or could be misspelled\n\n` +
354
- `Please correct the extension reference and try again. If you meant to install an extension from a local source, please provide a relative path prefixed with '${clc.bold("./")}', '${clc.bold("../")}', or '${clc.bold("~/")}'.}`, { status: 404 });
358
+ `Please correct the extension reference and try again. If you meant to reference an extension from a local source, please provide a relative path prefixed with '${clc.bold("./")}', '${clc.bold("../")}', or '${clc.bold("~/")}'.}`, { status: 404 });
355
359
  }
356
360
  exports.refNotFoundError = refNotFoundError;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.diagnoseAndFixProject = exports.getSourceOrigin = exports.isLocalOrURLPath = exports.isLocalPath = exports.isUrlPath = exports.instanceIdExists = exports.promptForRepeatInstance = exports.promptForOfficialExtension = exports.displayReleaseNotes = exports.getPublisherProjectFromName = exports.createSourceFromLocation = exports.getMissingPublisherError = exports.uploadExtensionVersionFromLocalSource = exports.uploadExtensionVersionFromGitHubSource = exports.unpackExtensionState = exports.getNextVersionByStage = exports.ensureExtensionsPublisherApiEnabled = exports.ensureExtensionsApiEnabled = exports.promptForExtensionRoot = exports.promptForValidRepoURI = exports.promptForValidInstanceId = exports.validateSpec = exports.validateCommandLineParams = exports.populateDefaultParams = exports.substituteParams = exports.getFirebaseProjectParams = exports.getDBInstanceFromURL = exports.resourceTypeToNiceName = exports.AUTOPOULATED_PARAM_PLACEHOLDERS = exports.EXTENSIONS_BUCKET_NAME = exports.URL_REGEX = exports.logPrefix = exports.SourceOrigin = exports.SpecParamType = void 0;
3
+ exports.diagnoseAndFixProject = exports.getSourceOrigin = exports.isLocalOrURLPath = exports.isLocalPath = exports.isUrlPath = exports.instanceIdExists = exports.promptForRepeatInstance = exports.promptForOfficialExtension = exports.displayReleaseNotes = exports.getPublisherProjectFromName = exports.createSourceFromLocation = exports.getMissingPublisherError = exports.uploadExtensionVersionFromLocalSource = exports.uploadExtensionVersionFromGitHubSource = exports.unpackExtensionState = exports.getNextVersionByStage = exports.ensureExtensionsPublisherApiEnabled = exports.ensureExtensionsApiEnabled = exports.checkExtensionsApiEnabled = exports.promptForExtensionRoot = exports.promptForValidRepoURI = exports.promptForValidInstanceId = exports.validateSpec = exports.validateCommandLineParams = exports.populateDefaultParams = exports.substituteSecretParams = exports.substituteParams = exports.getFirebaseProjectParams = exports.getDBInstanceFromURL = exports.resourceTypeToNiceName = exports.AUTOPOPULATED_PARAM_PLACEHOLDERS = exports.EXTENSIONS_BUCKET_NAME = exports.URL_REGEX = exports.logPrefix = exports.SourceOrigin = exports.SpecParamType = void 0;
4
4
  const clc = require("colorette");
5
5
  const ora = require("ora");
6
6
  const semver = require("semver");
@@ -62,7 +62,7 @@ const AUTOPOPULATED_PARAM_NAMES = [
62
62
  "DATABASE_INSTANCE",
63
63
  "DATABASE_URL",
64
64
  ];
65
- exports.AUTOPOULATED_PARAM_PLACEHOLDERS = {
65
+ exports.AUTOPOPULATED_PARAM_PLACEHOLDERS = {
66
66
  PROJECT_ID: "project-id",
67
67
  STORAGE_BUCKET: "project-id.appspot.com",
68
68
  EXT_INSTANCE_ID: "extension-id",
@@ -90,9 +90,18 @@ async function getFirebaseProjectParams(projectId, emulatorMode = false) {
90
90
  const body = emulatorMode
91
91
  ? await (0, adminSdkConfig_1.getProjectAdminSdkConfigOrCached)(projectId)
92
92
  : await (0, functionsConfig_1.getFirebaseConfig)({ project: projectId });
93
- const projectNumber = emulatorMode && constants_1.Constants.isDemoProject(projectId)
94
- ? constants_1.Constants.FAKE_PROJECT_NUMBER
95
- : await (0, getProjectNumber_1.getProjectNumber)({ projectId });
93
+ let projectNumber = constants_1.Constants.FAKE_PROJECT_NUMBER;
94
+ if (!constants_1.Constants.isDemoProject(projectId)) {
95
+ try {
96
+ projectNumber = await (0, getProjectNumber_1.getProjectNumber)({ projectId });
97
+ }
98
+ catch (err) {
99
+ (0, utils_2.logLabeledError)("extensions", `Unable to look up project number for ${projectId}.\n` +
100
+ " If this is a real project, ensure that you are logged in and have access to it.\n" +
101
+ " If this is a fake project, please use a project ID starting with 'demo-' to skip production calls.\n" +
102
+ " Continuing with a fake project number - secrets and other features that require production access may behave unexpectedly.");
103
+ }
104
+ }
96
105
  const databaseURL = body?.databaseURL ?? `https://${projectId}.firebaseio.com`;
97
106
  const storageBucket = body?.storageBucket ?? `${projectId}.appspot.com`;
98
107
  const FIREBASE_CONFIG = JSON.stringify({
@@ -125,6 +134,20 @@ function substituteParams(original, params) {
125
134
  return JSON.parse(s);
126
135
  }
127
136
  exports.substituteParams = substituteParams;
137
+ async function substituteSecretParams(projectNumber, params) {
138
+ const newParams = {};
139
+ for await (const [key, value] of Object.entries(params)) {
140
+ if (typeof value !== "string") {
141
+ newParams[key] =
142
+ `projects/${projectNumber}/secrets/${value.name}/versions/latest`;
143
+ }
144
+ else {
145
+ newParams[key] = value;
146
+ }
147
+ }
148
+ return newParams;
149
+ }
150
+ exports.substituteSecretParams = substituteSecretParams;
128
151
  function populateDefaultParams(paramVars, paramSpecs) {
129
152
  const newParams = paramVars;
130
153
  for (const param of paramSpecs) {
@@ -345,6 +368,14 @@ async function promptForReleaseStage(args) {
345
368
  }
346
369
  return stage;
347
370
  }
371
+ async function checkExtensionsApiEnabled(options) {
372
+ const projectId = (0, projectUtils_1.getProjectId)(options);
373
+ if (!projectId) {
374
+ return false;
375
+ }
376
+ return await (0, ensureApiEnabled_1.check)(projectId, (0, api_1.extensionsOrigin)(), "extensions", options.markdown);
377
+ }
378
+ exports.checkExtensionsApiEnabled = checkExtensionsApiEnabled;
348
379
  async function ensureExtensionsApiEnabled(options) {
349
380
  const projectId = (0, projectUtils_1.getProjectId)(options);
350
381
  if (!projectId) {
@@ -401,7 +432,7 @@ async function validateExtensionSpec(rootDirectory, extensionId) {
401
432
  throw new error_1.FirebaseError(`Extension ID '${clc.bold(extensionId)}' does not match the name in extension.yaml '${clc.bold(extensionSpec.name)}'.`);
402
433
  }
403
434
  const subbedSpec = JSON.parse(JSON.stringify(extensionSpec));
404
- subbedSpec.params = substituteParams(extensionSpec.params || [], exports.AUTOPOULATED_PARAM_PLACEHOLDERS);
435
+ subbedSpec.params = substituteParams(extensionSpec.params || [], exports.AUTOPOPULATED_PARAM_PLACEHOLDERS);
405
436
  validateSpec(subbedSpec);
406
437
  return extensionSpec;
407
438
  }
@@ -470,7 +501,7 @@ function displayExtensionHeader(extensionRef, extension, extensionRoot) {
470
501
  }
471
502
  else {
472
503
  logger_1.logger.info(`\n${clc.bold("Extension:")} ${extensionRef}\n` +
473
- `${clc.bold("State:")} ${clc.bold(clc.blue("New"))}\n`);
504
+ `${clc.bold("State:")} ${clc.bold(clc.blueBright("New"))}\n`);
474
505
  }
475
506
  }
476
507
  async function fetchExtensionSource(repoUri, sourceRef, extensionRoot) {
@@ -791,7 +822,7 @@ async function instanceIdExists(projectId, instanceId) {
791
822
  if (err.status === 404) {
792
823
  return false;
793
824
  }
794
- const msg = `Unexpected error when checking if instance ID exists: ${err}`;
825
+ const msg = `Unexpected error when checking if instance ID exists: ${err.message}`;
795
826
  throw new error_1.FirebaseError(msg, {
796
827
  original: err,
797
828
  });
@@ -6,11 +6,20 @@ const path = require("path");
6
6
  const yaml = require("yaml");
7
7
  const fsutils_1 = require("../fsutils");
8
8
  const error_1 = require("../error");
9
+ const types_1 = require("./types");
9
10
  const logger_1 = require("../logger");
11
+ const extensionsHelper_1 = require("./extensionsHelper");
10
12
  exports.EXTENSIONS_SPEC_FILE = "extension.yaml";
11
13
  const EXTENSIONS_PREINSTALL_FILE = "PREINSTALL.md";
12
14
  async function getLocalExtensionSpec(directory) {
13
15
  const spec = await parseYAML(readFile(path.resolve(directory, exports.EXTENSIONS_SPEC_FILE)));
16
+ if (spec.lifecycleEvents) {
17
+ spec.lifecycleEvents = fixLifecycleEvents(spec.lifecycleEvents);
18
+ }
19
+ if (!(0, types_1.isExtensionSpec)(spec)) {
20
+ (0, extensionsHelper_1.validateSpec)(spec);
21
+ throw new error_1.FirebaseError("Error: extension.yaml does not contain a valid extension specification.");
22
+ }
14
23
  try {
15
24
  const preinstall = readFile(path.resolve(directory, EXTENSIONS_PREINSTALL_FILE));
16
25
  spec.preinstallContent = preinstall;
@@ -21,6 +30,28 @@ async function getLocalExtensionSpec(directory) {
21
30
  return spec;
22
31
  }
23
32
  exports.getLocalExtensionSpec = getLocalExtensionSpec;
33
+ function fixLifecycleEvents(lifecycleEvents) {
34
+ const stages = {
35
+ onInstall: "ON_INSTALL",
36
+ onUpdate: "ON_UPDATE",
37
+ onConfigure: "ON_CONFIGURE",
38
+ stageUnspecified: "STAGE_UNSPECIFIED",
39
+ };
40
+ const arrayLifecycle = [];
41
+ if ((0, types_1.isObject)(lifecycleEvents)) {
42
+ for (const [key, val] of Object.entries(lifecycleEvents)) {
43
+ if ((0, types_1.isObject)(val) &&
44
+ typeof val.function === "string" &&
45
+ typeof val.processingMessage === "string") {
46
+ arrayLifecycle.push({
47
+ stage: stages[key] || stages["stageUnspecified"],
48
+ taskQueueTriggerFunction: val.function,
49
+ });
50
+ }
51
+ }
52
+ }
53
+ return arrayLifecycle;
54
+ }
24
55
  function findExtensionYaml(directory) {
25
56
  while (!(0, fsutils_1.fileExistsSync)(path.resolve(directory, exports.EXTENSIONS_SPEC_FILE))) {
26
57
  const parentDir = path.dirname(directory);
@@ -38,7 +69,7 @@ function readFile(pathToFile) {
38
69
  }
39
70
  catch (err) {
40
71
  if (err.code === "ENOENT") {
41
- throw new error_1.FirebaseError(`Could not find "${pathToFile}""`, { original: err });
72
+ throw new error_1.FirebaseError(`Could not find "${pathToFile}"`, { original: err });
42
73
  }
43
74
  throw new error_1.FirebaseError(`Failed to read file at "${pathToFile}"`, { original: err });
44
75
  }
@@ -7,13 +7,16 @@ const refRegex = new RegExp(/^([^/@\n]+)\/{1}([^/@\n]+)(@{1}([^\n]+)|)$/);
7
7
  function parse(refOrName) {
8
8
  const ret = parseRef(refOrName) || parseName(refOrName);
9
9
  if (!ret || !ret.publisherId || !ret.extensionId) {
10
- throw new error_1.FirebaseError(`Unable to parse ${refOrName} as an extension ref`);
10
+ throw new error_1.FirebaseError(`Unable to parse ${refOrName} as an extension ref.\n` +
11
+ "Expected format is either publisherId/extensionId@version or " +
12
+ "publishers/publisherId/extensions/extensionId/versions/version. If you " +
13
+ "are referring to a local extension directory, please ensure the directory exists.");
11
14
  }
12
15
  if (ret.version &&
13
16
  !semver.valid(ret.version) &&
14
17
  !semver.validRange(ret.version) &&
15
18
  !["latest", "latest-approved"].includes(ret.version)) {
16
- throw new error_1.FirebaseError(`Extension reference ${ret} contains an invalid version ${ret.version}.`);
19
+ throw new error_1.FirebaseError(`Extension reference ${JSON.stringify(ret, null, 2)} contains an invalid version ${ret.version}.`);
17
20
  }
18
21
  return ret;
19
22
  }
@@ -21,19 +24,31 @@ exports.parse = parse;
21
24
  function parseRef(ref) {
22
25
  const parts = refRegex.exec(ref);
23
26
  if (parts && (parts.length === 5 || parts.length === 7)) {
24
- const publisherId = parts[1];
25
- const extensionId = parts[2];
26
- const version = parts[4];
27
- return { publisherId, extensionId, version };
27
+ return {
28
+ publisherId: parts[1],
29
+ extensionId: parts[2],
30
+ version: parts[4],
31
+ };
28
32
  }
29
33
  }
30
34
  function parseName(name) {
31
35
  const parts = name.split("/");
32
- return {
33
- publisherId: parts[1],
34
- extensionId: parts[3],
35
- version: parts[5],
36
- };
36
+ if (parts[0] !== "publishers" || parts[2] !== "extensions") {
37
+ return;
38
+ }
39
+ if (parts.length === 4) {
40
+ return {
41
+ publisherId: parts[1],
42
+ extensionId: parts[3],
43
+ };
44
+ }
45
+ if (parts.length === 6 && parts[4] === "versions") {
46
+ return {
47
+ publisherId: parts[1],
48
+ extensionId: parts[3],
49
+ version: parts[5],
50
+ };
51
+ }
37
52
  }
38
53
  function toExtensionRef(ref) {
39
54
  return `${ref.publisherId}/${ref.extensionId}`;