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
@@ -5,46 +5,56 @@ const cloudSqlAdminClient = require("../gcp/cloudsql/cloudsqladmin");
5
5
  const utils = require("../utils");
6
6
  const checkIam_1 = require("./checkIam");
7
7
  const utils_1 = require("../utils");
8
+ const logger_1 = require("../logger");
8
9
  const GOOGLE_ML_INTEGRATION_ROLE = "roles/aiplatform.user";
9
10
  const freeTrial_1 = require("./freeTrial");
10
11
  const error_1 = require("../error");
11
12
  async function provisionCloudSql(args) {
12
13
  let connectionName = "";
13
- const { projectId, locationId, instanceId, databaseId, enableGoogleMlIntegration, waitForCreation, silent, } = args;
14
+ const { projectId, locationId, instanceId, databaseId, configYamlPath, enableGoogleMlIntegration, waitForCreation, silent, dryRun, } = args;
14
15
  try {
15
16
  const existingInstance = await cloudSqlAdminClient.getInstance(projectId, instanceId);
16
17
  silent || utils.logLabeledBullet("dataconnect", `Found existing instance ${instanceId}.`);
17
18
  connectionName = existingInstance?.connectionName || "";
18
19
  const why = getUpdateReason(existingInstance, enableGoogleMlIntegration);
19
20
  if (why) {
21
+ const cta = dryRun
22
+ ? `It will be updated on your next deploy.`
23
+ : `Updating instance. This may take a few minutes...`;
20
24
  silent ||
21
- utils.logLabeledBullet("dataconnect", `Instance ${instanceId} settings not compatible with Firebase Data Connect. ` +
22
- `Updating instance. This may take a few minutes...` +
23
- why);
24
- await (0, utils_1.promiseWithSpinner)(() => cloudSqlAdminClient.updateInstanceForDataConnect(existingInstance, enableGoogleMlIntegration), "Updating your instance...");
25
- silent || utils.logLabeledBullet("dataconnect", "Instance updated");
25
+ utils.logLabeledBullet("dataconnect", `Instance ${instanceId} settings not compatible with Firebase Data Connect. ` + cta + why);
26
+ if (!dryRun) {
27
+ await (0, utils_1.promiseWithSpinner)(() => cloudSqlAdminClient.updateInstanceForDataConnect(existingInstance, enableGoogleMlIntegration), "Updating your instance...");
28
+ silent || utils.logLabeledBullet("dataconnect", "Instance updated");
29
+ }
26
30
  }
27
31
  }
28
32
  catch (err) {
29
33
  if (err.status !== 404) {
30
34
  throw err;
31
35
  }
32
- const freeTrialInstanceId = await (0, freeTrial_1.checkForFreeTrialInstance)(projectId);
33
- if (freeTrialInstanceId) {
34
- (0, freeTrial_1.printFreeTrialUnavailable)(projectId, freeTrialInstanceId);
35
- throw new error_1.FirebaseError("Free trial unavailable.");
36
+ const freeTrialInstanceId = await (0, freeTrial_1.getFreeTrialInstanceId)(projectId);
37
+ if (await (0, freeTrial_1.checkFreeTrialInstanceUsed)(projectId)) {
38
+ (0, freeTrial_1.printFreeTrialUnavailable)(projectId, configYamlPath, freeTrialInstanceId);
39
+ throw new error_1.FirebaseError("No-cost Cloud SQL trial has already been used on this project.");
36
40
  }
41
+ const cta = dryRun ? "It will be created on your next deploy" : "Creating it now.";
37
42
  silent ||
38
- utils.logLabeledBullet("dataconnect", `CloudSQL instance '${instanceId}' not found, creating it.` +
39
- `\nThis instance is provided under the terms of the Data Connect free trial ${(0, freeTrial_1.freeTrialTermsLink)()}` +
43
+ utils.logLabeledBullet("dataconnect", `CloudSQL instance '${instanceId}' not found.` +
44
+ cta +
45
+ `\nThis instance is provided under the terms of the Data Connect no-cost trial ${(0, freeTrial_1.freeTrialTermsLink)()}` +
40
46
  `\nMonitor the progress at ${cloudSqlAdminClient.instanceConsoleLink(projectId, instanceId)}`);
41
- const newInstance = await (0, utils_1.promiseWithSpinner)(() => cloudSqlAdminClient.createInstance(projectId, locationId, instanceId, enableGoogleMlIntegration, waitForCreation), "Creating your instance...");
42
- if (newInstance) {
43
- silent || utils.logLabeledBullet("dataconnect", "Instance created");
44
- connectionName = newInstance?.connectionName || "";
45
- }
46
- else {
47
- silent || utils.logLabeledBullet("dataconnect", "Instance creation process started");
47
+ if (!dryRun) {
48
+ const newInstance = await (0, utils_1.promiseWithSpinner)(() => cloudSqlAdminClient.createInstance(projectId, locationId, instanceId, enableGoogleMlIntegration, waitForCreation), "Creating your instance...");
49
+ if (newInstance) {
50
+ silent || utils.logLabeledBullet("dataconnect", "Instance created");
51
+ connectionName = newInstance?.connectionName || "";
52
+ }
53
+ else {
54
+ silent ||
55
+ utils.logLabeledBullet("dataconnect", "Cloud SQL instance creation started - it should be ready shortly. Database and users will be created on your next deploy.");
56
+ return connectionName;
57
+ }
48
58
  }
49
59
  }
50
60
  try {
@@ -53,16 +63,23 @@ async function provisionCloudSql(args) {
53
63
  }
54
64
  catch (err) {
55
65
  if (err.status === 404) {
56
- silent ||
57
- utils.logLabeledBullet("dataconnect", `Database ${databaseId} not found, creating it now...`);
58
- await cloudSqlAdminClient.createDatabase(projectId, instanceId, databaseId);
59
- silent || utils.logLabeledBullet("dataconnect", `Database ${databaseId} created.`);
66
+ if (dryRun) {
67
+ silent ||
68
+ utils.logLabeledBullet("dataconnect", `Database ${databaseId} not found. It will be created on your next deploy.`);
69
+ }
70
+ else {
71
+ silent ||
72
+ utils.logLabeledBullet("dataconnect", `Database ${databaseId} not found, creating it now...`);
73
+ await cloudSqlAdminClient.createDatabase(projectId, instanceId, databaseId);
74
+ silent || utils.logLabeledBullet("dataconnect", `Database ${databaseId} created.`);
75
+ }
60
76
  }
61
77
  else {
78
+ logger_1.logger.debug(`Unexpected error from CloudSQL: ${err}`);
62
79
  silent || utils.logLabeledWarning("dataconnect", `Database ${databaseId} is not accessible.`);
63
80
  }
64
81
  }
65
- if (enableGoogleMlIntegration) {
82
+ if (enableGoogleMlIntegration && !dryRun) {
66
83
  await (0, checkIam_1.grantRolesToCloudSqlServiceAccount)(projectId, instanceId, [GOOGLE_ML_INTEGRATION_ROLE]);
67
84
  }
68
85
  return connectionName;
@@ -1,28 +1,42 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.migrateSchema = exports.diffSchema = void 0;
3
+ exports.getIdentifiers = exports.grantRoleToUserInSchema = exports.migrateSchema = exports.diffSchema = void 0;
4
4
  const clc = require("colorette");
5
5
  const sql_formatter_1 = require("sql-formatter");
6
6
  const types_1 = require("./types");
7
7
  const client_1 = require("./client");
8
8
  const connect_1 = require("../gcp/cloudsql/connect");
9
+ const permissions_1 = require("../gcp/cloudsql/permissions");
10
+ const cloudSqlAdminClient = require("../gcp/cloudsql/cloudsqladmin");
11
+ const projectUtils_1 = require("../projectUtils");
9
12
  const prompt_1 = require("../prompt");
10
13
  const logger_1 = require("../logger");
11
14
  const error_1 = require("../error");
12
- const projectUtils_1 = require("../projectUtils");
13
15
  const utils_1 = require("../utils");
14
16
  const experiments = require("../experiments");
15
17
  const errors = require("./errors");
16
- async function diffSchema(schema) {
18
+ async function diffSchema(schema, schemaValidation) {
17
19
  const { serviceName, instanceName, databaseId } = getIdentifiers(schema);
18
20
  await ensureServiceIsConnectedToCloudSql(serviceName, instanceName, databaseId, false);
19
- setCompatibleMode(schema, databaseId, instanceName);
21
+ let diffs = [];
22
+ let validationMode = experiments.isEnabled("fdccompatiblemode")
23
+ ? schemaValidation ?? "COMPATIBLE"
24
+ : "STRICT";
25
+ setSchemaValidationMode(schema, validationMode);
20
26
  try {
27
+ if (!schemaValidation && experiments.isEnabled("fdccompatiblemode")) {
28
+ (0, utils_1.logLabeledBullet)("dataconnect", `generating required schema changes...`);
29
+ }
21
30
  await (0, client_1.upsertSchema)(schema, true);
22
- (0, utils_1.logLabeledSuccess)("dataconnect", `Database schema is up to date.`);
31
+ if (validationMode === "STRICT") {
32
+ (0, utils_1.logLabeledSuccess)("dataconnect", `Database schema is up to date.`);
33
+ }
34
+ else {
35
+ (0, utils_1.logLabeledSuccess)("dataconnect", `Database schema is compatible.`);
36
+ }
23
37
  }
24
38
  catch (err) {
25
- if (err.status !== 400) {
39
+ if (err?.status !== 400) {
26
40
  throw err;
27
41
  }
28
42
  const invalidConnectors = errors.getInvalidConnectors(err);
@@ -34,24 +48,57 @@ async function diffSchema(schema) {
34
48
  displayInvalidConnectors(invalidConnectors);
35
49
  }
36
50
  if (incompatible) {
37
- displaySchemaChanges(incompatible);
38
- return incompatible.diffs;
51
+ displaySchemaChanges(incompatible, validationMode, instanceName, databaseId);
52
+ diffs = incompatible.diffs;
39
53
  }
40
54
  }
41
- return [];
55
+ if (experiments.isEnabled("fdccompatiblemode") && !schemaValidation) {
56
+ validationMode = "STRICT";
57
+ setSchemaValidationMode(schema, validationMode);
58
+ try {
59
+ (0, utils_1.logLabeledBullet)("dataconnect", `generating schema changes, including optional changes...`);
60
+ await (0, client_1.upsertSchema)(schema, true);
61
+ (0, utils_1.logLabeledSuccess)("dataconnect", `no additional optional changes`);
62
+ }
63
+ catch (err) {
64
+ if (err?.status !== 400) {
65
+ throw err;
66
+ }
67
+ const incompatible = errors.getIncompatibleSchemaError(err);
68
+ if (incompatible) {
69
+ if (!diffsEqual(diffs, incompatible.diffs)) {
70
+ if (diffs.length === 0) {
71
+ displaySchemaChanges(incompatible, "STRICT_AFTER_COMPATIBLE", instanceName, databaseId);
72
+ }
73
+ else {
74
+ displaySchemaChanges(incompatible, validationMode, instanceName, databaseId);
75
+ }
76
+ diffs = incompatible.diffs;
77
+ }
78
+ else {
79
+ (0, utils_1.logLabeledSuccess)("dataconnect", `no additional optional changes`);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ return diffs;
42
85
  }
43
86
  exports.diffSchema = diffSchema;
44
87
  async function migrateSchema(args) {
45
- const { options, schema, validateOnly } = args;
88
+ const { options, schema, validateOnly, schemaValidation } = args;
46
89
  const { serviceName, instanceId, instanceName, databaseId } = getIdentifiers(schema);
47
90
  await ensureServiceIsConnectedToCloudSql(serviceName, instanceName, databaseId, true);
48
- setCompatibleMode(schema, databaseId, instanceName);
91
+ let diffs = [];
92
+ let validationMode = experiments.isEnabled("fdccompatiblemode")
93
+ ? schemaValidation ?? "COMPATIBLE"
94
+ : "STRICT";
95
+ setSchemaValidationMode(schema, validationMode);
49
96
  try {
50
97
  await (0, client_1.upsertSchema)(schema, validateOnly);
51
98
  logger_1.logger.debug(`Database schema was up to date for ${instanceId}:${databaseId}`);
52
99
  }
53
100
  catch (err) {
54
- if (err.status !== 400) {
101
+ if (err?.status !== 400) {
55
102
  throw err;
56
103
  }
57
104
  const incompatible = errors.getIncompatibleSchemaError(err);
@@ -59,9 +106,8 @@ async function migrateSchema(args) {
59
106
  if (!incompatible && !invalidConnectors.length) {
60
107
  throw err;
61
108
  }
62
- const migrationMode = await promptForSchemaMigration(options, databaseId, incompatible, validateOnly);
109
+ const migrationMode = await promptForSchemaMigration(options, instanceName, databaseId, incompatible, validateOnly, validationMode);
63
110
  const shouldDeleteInvalidConnectors = await promptForInvalidConnectorError(options, serviceName, invalidConnectors, validateOnly);
64
- let diffs = [];
65
111
  if (incompatible) {
66
112
  diffs = await handleIncompatibleSchemaError({
67
113
  options,
@@ -77,35 +123,82 @@ async function migrateSchema(args) {
77
123
  if (!validateOnly) {
78
124
  await (0, client_1.upsertSchema)(schema, validateOnly);
79
125
  }
80
- return diffs;
81
126
  }
82
- return [];
127
+ if (experiments.isEnabled("fdccompatiblemode") && !schemaValidation) {
128
+ validationMode = "STRICT";
129
+ setSchemaValidationMode(schema, validationMode);
130
+ try {
131
+ await (0, client_1.upsertSchema)(schema, validateOnly);
132
+ }
133
+ catch (err) {
134
+ if (err.status !== 400) {
135
+ throw err;
136
+ }
137
+ const incompatible = errors.getIncompatibleSchemaError(err);
138
+ const invalidConnectors = errors.getInvalidConnectors(err);
139
+ if (!incompatible && !invalidConnectors.length) {
140
+ throw err;
141
+ }
142
+ const migrationMode = await promptForSchemaMigration(options, instanceName, databaseId, incompatible, validateOnly, "STRICT_AFTER_COMPATIBLE");
143
+ if (incompatible) {
144
+ const maybeDiffs = await handleIncompatibleSchemaError({
145
+ options,
146
+ databaseId,
147
+ instanceId,
148
+ incompatibleSchemaError: incompatible,
149
+ choice: migrationMode,
150
+ });
151
+ diffs = diffs.concat(maybeDiffs);
152
+ }
153
+ }
154
+ }
155
+ return diffs;
83
156
  }
84
157
  exports.migrateSchema = migrateSchema;
85
- function setCompatibleMode(schema, databaseId, instanceName) {
86
- if (experiments.isEnabled("fdccompatiblemode")) {
87
- if (schema.primaryDatasource.postgresql?.schemaValidation) {
88
- schema.primaryDatasource.postgresql.schemaValidation = "COMPATIBLE";
158
+ async function grantRoleToUserInSchema(options, schema) {
159
+ const role = options.role;
160
+ const email = options.email;
161
+ const { instanceId, databaseId } = getIdentifiers(schema);
162
+ const projectId = (0, projectUtils_1.needProjectId)(options);
163
+ const { user, mode } = (0, connect_1.toDatabaseUser)(email);
164
+ const fdcSqlRole = permissions_1.fdcSqlRoleMap[role](databaseId);
165
+ const userIsCSQLAdmin = await (0, permissions_1.iamUserIsCSQLAdmin)(options);
166
+ if (!userIsCSQLAdmin) {
167
+ throw new error_1.FirebaseError(`Only users with 'roles/cloudsql.admin' can grant SQL roles. If you do not have this role, ask your database administrator to run this command or manually grant ${fdcSqlRole} to ${user}`);
168
+ }
169
+ await (0, connect_1.setupIAMUsers)(instanceId, databaseId, options);
170
+ await cloudSqlAdminClient.createUser(projectId, instanceId, mode, user);
171
+ await (0, connect_1.executeSqlCmdsAsSuperUser)(options, instanceId, databaseId, [`GRANT "${fdcSqlRole}" TO "${user}"`], false);
172
+ }
173
+ exports.grantRoleToUserInSchema = grantRoleToUserInSchema;
174
+ function diffsEqual(x, y) {
175
+ if (x.length !== y.length) {
176
+ return false;
177
+ }
178
+ for (let i = 0; i < x.length; i++) {
179
+ if (x[i].description !== y[i].description ||
180
+ x[i].destructive !== y[i].destructive ||
181
+ x[i].sql !== y[i].sql) {
182
+ return false;
89
183
  }
90
- else {
91
- schema.primaryDatasource = {
92
- postgresql: {
93
- database: databaseId,
94
- cloudSql: {
95
- instance: instanceName,
96
- },
97
- schemaValidation: "COMPATIBLE",
98
- },
99
- };
184
+ }
185
+ return true;
186
+ }
187
+ function setSchemaValidationMode(schema, schemaValidation) {
188
+ if (experiments.isEnabled("fdccompatiblemode")) {
189
+ const postgresDatasource = schema.datasources.find((d) => d.postgresql);
190
+ if (postgresDatasource?.postgresql) {
191
+ postgresDatasource.postgresql.schemaValidation = schemaValidation;
100
192
  }
101
193
  }
102
194
  }
103
195
  function getIdentifiers(schema) {
104
- const databaseId = schema.primaryDatasource.postgresql?.database;
196
+ const postgresDatasource = schema.datasources.find((d) => d.postgresql);
197
+ const databaseId = postgresDatasource?.postgresql?.database;
105
198
  if (!databaseId) {
106
- throw new error_1.FirebaseError("Schema is missing primaryDatasource.postgresql?.database, cannot migrate");
199
+ throw new error_1.FirebaseError("Service does not have a postgres datasource, cannot migrate");
107
200
  }
108
- const instanceName = schema.primaryDatasource.postgresql?.cloudSql.instance;
201
+ const instanceName = postgresDatasource?.postgresql?.cloudSql.instance;
109
202
  if (!instanceName) {
110
203
  throw new error_1.FirebaseError("tried to migrate schema but instance name was not provided in dataconnect.yaml");
111
204
  }
@@ -118,6 +211,7 @@ function getIdentifiers(schema) {
118
211
  serviceName,
119
212
  };
120
213
  }
214
+ exports.getIdentifiers = getIdentifiers;
121
215
  function suggestedCommand(serviceName, invalidConnectorNames) {
122
216
  const serviceId = serviceName.split("/")[5];
123
217
  const connectorIds = invalidConnectorNames.map((i) => i.split("/")[7]);
@@ -129,8 +223,6 @@ async function handleIncompatibleSchemaError(args) {
129
223
  if (incompatibleSchemaError.destructive && choice === "safe") {
130
224
  throw new error_1.FirebaseError("This schema migration includes potentially destructive changes. If you'd like to execute it anyway, rerun this command with --force");
131
225
  }
132
- const projectId = (0, projectUtils_1.needProjectId)(options);
133
- const iamUser = await (0, connect_1.setupIAMUser)(instanceId, databaseId, options);
134
226
  const commandsToExecute = incompatibleSchemaError.diffs
135
227
  .filter((d) => {
136
228
  switch (choice) {
@@ -144,42 +236,63 @@ async function handleIncompatibleSchemaError(args) {
144
236
  })
145
237
  .map((d) => d.sql);
146
238
  if (commandsToExecute.length) {
147
- await (0, connect_1.execute)([
148
- `SET ROLE "${(0, connect_1.firebaseowner)(databaseId)}"`,
149
- ...commandsToExecute,
150
- `GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA "public" TO PUBLIC`,
151
- ], {
152
- projectId,
153
- instanceId,
154
- databaseId,
155
- username: iamUser,
156
- });
157
- return incompatibleSchemaError.diffs;
239
+ const commandsToExecuteBySuperUser = commandsToExecute.filter((sql) => sql.startsWith("CREATE EXTENSION") || sql.startsWith("CREATE SCHEMA"));
240
+ const commandsToExecuteByOwner = commandsToExecute.filter((sql) => !commandsToExecuteBySuperUser.includes(sql));
241
+ const userIsCSQLAdmin = await (0, permissions_1.iamUserIsCSQLAdmin)(options);
242
+ if (!userIsCSQLAdmin && commandsToExecuteBySuperUser.length) {
243
+ throw new error_1.FirebaseError(`Some SQL commands required for this migration require Admin permissions.\n
244
+ Please ask a user with 'roles/cloudsql.admin' to apply the following commands.\n
245
+ ${commandsToExecuteBySuperUser.join("\n")}`);
246
+ }
247
+ if (userIsCSQLAdmin) {
248
+ await (0, connect_1.setupIAMUsers)(instanceId, databaseId, options);
249
+ }
250
+ if (!(await (0, permissions_1.checkSQLRoleIsGranted)(options, instanceId, databaseId, (0, permissions_1.firebaseowner)(databaseId), (await (0, connect_1.getIAMUser)(options)).user))) {
251
+ throw new error_1.FirebaseError(`Command aborted. Only users granted firebaseowner SQL role can run migrations.`);
252
+ }
253
+ if (commandsToExecuteBySuperUser.length) {
254
+ logger_1.logger.info(`The diffs require CloudSQL superuser permissions, attempting to apply changes as superuser.`);
255
+ await (0, connect_1.executeSqlCmdsAsSuperUser)(options, instanceId, databaseId, commandsToExecuteBySuperUser, false);
256
+ }
257
+ if (commandsToExecuteByOwner.length) {
258
+ await (0, connect_1.executeSqlCmdsAsIamUser)(options, instanceId, databaseId, [`SET ROLE "${(0, permissions_1.firebaseowner)(databaseId)}"`, ...commandsToExecuteByOwner], false);
259
+ return incompatibleSchemaError.diffs;
260
+ }
158
261
  }
159
262
  return [];
160
263
  }
161
- async function promptForSchemaMigration(options, databaseName, err, validateOnly) {
264
+ async function promptForSchemaMigration(options, instanceName, databaseId, err, validateOnly, validationMode) {
162
265
  if (!err) {
163
266
  return "none";
164
267
  }
165
- displaySchemaChanges(err);
268
+ if (validationMode === "STRICT_AFTER_COMPATIBLE" && (options.nonInteractive || options.force)) {
269
+ return "none";
270
+ }
271
+ displaySchemaChanges(err, validationMode, instanceName, databaseId);
166
272
  if (!options.nonInteractive) {
167
273
  if (validateOnly && options.force) {
168
274
  return "all";
169
275
  }
170
- const choices = err.destructive
171
- ? [
172
- { name: "Execute all changes (including destructive changes)", value: "all" },
173
- { name: "Abort changes", value: "none" },
174
- ]
175
- : [
176
- { name: "Execute changes", value: "all" },
177
- { name: "Abort changes", value: "none" },
178
- ];
276
+ const message = validationMode === "STRICT_AFTER_COMPATIBLE"
277
+ ? `Would you like to execute these optional changes against ${databaseId} in your CloudSQL instance ${instanceName}?`
278
+ : `Would you like to execute these changes against ${databaseId} in your CloudSQL instance ${instanceName}?`;
279
+ let executeChangePrompt = "Execute changes";
280
+ if (validationMode === "STRICT_AFTER_COMPATIBLE") {
281
+ executeChangePrompt = "Execute optional changes";
282
+ }
283
+ if (err.destructive) {
284
+ executeChangePrompt = executeChangePrompt + " (including destructive changes)";
285
+ }
286
+ const choices = [
287
+ { name: executeChangePrompt, value: "all" },
288
+ { name: "Abort changes", value: "none" },
289
+ ];
290
+ const defaultValue = validationMode === "STRICT_AFTER_COMPATIBLE" ? "none" : "all";
179
291
  return await (0, prompt_1.promptOnce)({
180
- message: `Would you like to execute these changes against ${databaseName}?`,
292
+ message: message,
181
293
  type: "list",
182
294
  choices,
295
+ default: defaultValue,
183
296
  });
184
297
  }
185
298
  if (!validateOnly) {
@@ -201,10 +314,7 @@ async function promptForInvalidConnectorError(options, serviceName, invalidConne
201
314
  }
202
315
  displayInvalidConnectors(invalidConnectors);
203
316
  if (validateOnly) {
204
- if (options.force) {
205
- return false;
206
- }
207
- throw new error_1.FirebaseError(`Command aborted. If you'd like to migrate it anyway, you may override with --force.`);
317
+ return false;
208
318
  }
209
319
  if (options.force) {
210
320
  return true;
@@ -240,17 +350,20 @@ async function ensureServiceIsConnectedToCloudSql(serviceName, instanceId, datab
240
350
  source: {
241
351
  files: [],
242
352
  },
243
- primaryDatasource: {
244
- postgresql: {
245
- database: databaseId,
246
- cloudSql: {
247
- instance: instanceId,
353
+ datasources: [
354
+ {
355
+ postgresql: {
356
+ database: databaseId,
357
+ cloudSql: {
358
+ instance: instanceId,
359
+ },
248
360
  },
249
361
  },
250
- },
362
+ ],
251
363
  };
252
364
  }
253
- const postgresql = currentSchema.primaryDatasource.postgresql;
365
+ const postgresDatasource = currentSchema.datasources.find((d) => d.postgresql);
366
+ const postgresql = postgresDatasource?.postgresql;
254
367
  if (postgresql?.cloudSql.instance !== instanceId) {
255
368
  (0, utils_1.logLabeledWarning)("dataconnect", `Switching connected Cloud SQL instance\nFrom ${postgresql?.cloudSql.instance}\nTo ${instanceId}`);
256
369
  }
@@ -265,19 +378,47 @@ async function ensureServiceIsConnectedToCloudSql(serviceName, instanceId, datab
265
378
  await (0, client_1.upsertSchema)(currentSchema, false);
266
379
  }
267
380
  catch (err) {
268
- if (err.status >= 500) {
381
+ if (err?.status >= 500) {
269
382
  throw err;
270
383
  }
271
384
  logger_1.logger.debug(err);
272
385
  }
273
386
  }
274
- function displaySchemaChanges(error) {
387
+ function displaySchemaChanges(error, validationMode, instanceName, databaseId) {
275
388
  switch (error.violationType) {
276
389
  case "INCOMPATIBLE_SCHEMA":
277
390
  {
278
- const message = "Your new schema is incompatible with the schema of your CloudSQL database. " +
279
- "The following SQL statements will migrate your database schema to match your new Data Connect schema.\n" +
280
- error.diffs.map(toString).join("\n");
391
+ let message;
392
+ if (validationMode === "COMPATIBLE") {
393
+ message =
394
+ "Your PostgreSQL database " +
395
+ databaseId +
396
+ " in your CloudSQL instance " +
397
+ instanceName +
398
+ " must be migrated in order to be compatible with your application schema. " +
399
+ "The following SQL statements will migrate your database schema to be compatible with your new Data Connect schema.\n" +
400
+ error.diffs.map(toString).join("\n");
401
+ }
402
+ else if (validationMode === "STRICT_AFTER_COMPATIBLE") {
403
+ message =
404
+ "Your new application schema is compatible with the schema of your PostgreSQL database " +
405
+ databaseId +
406
+ " in your CloudSQL instance " +
407
+ instanceName +
408
+ ", but contains unused tables or columns. " +
409
+ "The following optional SQL statements will migrate your database schema to match your new Data Connect schema.\n" +
410
+ error.diffs.map(toString).join("\n");
411
+ }
412
+ else {
413
+ message =
414
+ "Your PostgreSQL database " +
415
+ databaseId +
416
+ " in your CloudSQL instance " +
417
+ instanceName +
418
+ " must be migrated in order to match your application schema. " +
419
+ "The following SQL statements will migrate your database schema to match your new Data Connect schema.\n" +
420
+ error.diffs.map(toString).join("\n");
421
+ }
281
422
  (0, utils_1.logLabeledWarning)("dataconnect", message);
282
423
  }
283
424
  break;
@@ -8,10 +8,12 @@ function requiresVector(dm) {
8
8
  exports.requiresVector = requiresVector;
9
9
  var Platform;
10
10
  (function (Platform) {
11
+ Platform["NONE"] = "NONE";
11
12
  Platform["ANDROID"] = "ANDROID";
12
13
  Platform["WEB"] = "WEB";
13
14
  Platform["IOS"] = "IOS";
14
- Platform["UNDETERMINED"] = "UNDETERMINED";
15
+ Platform["FLUTTER"] = "FLUTTER";
16
+ Platform["MULTIPLE"] = "MULTIPLE";
15
17
  })(Platform = exports.Platform || (exports.Platform = {}));
16
18
  function toDatasource(projectId, locationId, ds) {
17
19
  if (ds.postgresql) {
@@ -21,6 +23,7 @@ function toDatasource(projectId, locationId, ds) {
21
23
  cloudSql: {
22
24
  instance: `projects/${projectId}/locations/${locationId}/instances/${ds.postgresql.cloudSql.instanceId}`,
23
25
  },
26
+ schemaValidation: ds.postgresql.schemaValidation,
24
27
  },
25
28
  };
26
29
  }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendVSCodeMessage = exports.port = exports.DEFAULT_PORT = exports.VSCODE_MESSAGE = void 0;
4
+ const node_fetch_1 = require("node-fetch");
5
+ const logger_1 = require("../logger");
6
+ var VSCODE_MESSAGE;
7
+ (function (VSCODE_MESSAGE) {
8
+ VSCODE_MESSAGE["EMULATORS_STARTED"] = "EMULATORS_STARTED";
9
+ VSCODE_MESSAGE["EMULATORS_START_ERRORED"] = "EMULATORS_START_ERRORED";
10
+ VSCODE_MESSAGE["EMULATORS_SHUTDOWN"] = "EMULATORS_SHUTDOWN";
11
+ })(VSCODE_MESSAGE = exports.VSCODE_MESSAGE || (exports.VSCODE_MESSAGE = {}));
12
+ exports.DEFAULT_PORT = "40001";
13
+ exports.port = process.env.VSCODE_WEBHOOK_PORT || exports.DEFAULT_PORT;
14
+ async function sendVSCodeMessage(body) {
15
+ const jsonBody = JSON.stringify(body);
16
+ try {
17
+ return await (0, node_fetch_1.default)(`http://localhost:${exports.port}/vscode/notify`, {
18
+ method: "POST",
19
+ headers: {
20
+ Accept: "application/json",
21
+ "Content-Type": "application/json",
22
+ "x-mantle-admin": "all",
23
+ },
24
+ body: jsonBody,
25
+ signal: AbortSignal.timeout(3000),
26
+ });
27
+ }
28
+ catch (e) {
29
+ logger_1.logger.debug(`Could not find VSCode notification endpoint: ${e}. If you are not running the Firebase Data Connect VSCode extension, this is expected and not an issue.`);
30
+ }
31
+ }
32
+ exports.sendVSCodeMessage = sendVSCodeMessage;
@@ -8,6 +8,7 @@ const provisionCloudSql_1 = require("../../dataconnect/provisionCloudSql");
8
8
  const names_1 = require("../../dataconnect/names");
9
9
  const api_1 = require("../../api");
10
10
  const ensureApiEnabled = require("../../ensureApiEnabled");
11
+ const node_path_1 = require("node:path");
11
12
  async function default_1(context, options) {
12
13
  const projectId = (0, projectUtils_1.needProjectId)(options);
13
14
  const serviceInfos = context.dataconnect.serviceInfos;
@@ -43,22 +44,24 @@ async function default_1(context, options) {
43
44
  return !filters || filters?.some((f) => si.dataConnectYaml.serviceId === f.serviceId);
44
45
  })
45
46
  .map(async (s) => {
46
- const instanceId = s.schema.primaryDatasource.postgresql?.cloudSql.instance
47
- .split("/")
48
- .pop();
49
- const databaseId = s.schema.primaryDatasource.postgresql?.database;
50
- if (!instanceId || !databaseId) {
51
- return Promise.resolve();
47
+ const postgresDatasource = s.schema.datasources.find((d) => d.postgresql);
48
+ if (postgresDatasource) {
49
+ const instanceId = postgresDatasource.postgresql?.cloudSql.instance.split("/").pop();
50
+ const databaseId = postgresDatasource.postgresql?.database;
51
+ if (!instanceId || !databaseId) {
52
+ return Promise.resolve();
53
+ }
54
+ const enableGoogleMlIntegration = (0, types_1.requiresVector)(s.deploymentMetadata);
55
+ return (0, provisionCloudSql_1.provisionCloudSql)({
56
+ projectId,
57
+ locationId: (0, names_1.parseServiceName)(s.serviceName).location,
58
+ instanceId,
59
+ databaseId,
60
+ configYamlPath: (0, node_path_1.join)(s.sourceDirectory, "dataconnect.yaml"),
61
+ enableGoogleMlIntegration,
62
+ waitForCreation: true,
63
+ });
52
64
  }
53
- const enableGoogleMlIntegration = (0, types_1.requiresVector)(s.deploymentMetadata);
54
- return (0, provisionCloudSql_1.provisionCloudSql)({
55
- projectId,
56
- locationId: (0, names_1.parseServiceName)(s.serviceName).location,
57
- instanceId,
58
- databaseId,
59
- enableGoogleMlIntegration,
60
- waitForCreation: true,
61
- });
62
65
  }));
63
66
  return;
64
67
  }