firebase-tools-with-isolate 13.16.0 → 13.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/lib/api.js +3 -1
  2. package/lib/apiv2.js +10 -3
  3. package/lib/appdistribution/client.js +62 -8
  4. package/lib/appdistribution/distribution.js +1 -1
  5. package/lib/apphosting/backend.js +299 -0
  6. package/lib/apphosting/config.js +31 -8
  7. package/lib/apphosting/githubConnections.js +70 -22
  8. package/lib/apphosting/index.js +3 -312
  9. package/lib/apphosting/rollout.js +138 -0
  10. package/lib/apphosting/secrets/index.js +70 -5
  11. package/lib/apphosting/utils.js +41 -0
  12. package/lib/apphosting/yaml.js +82 -0
  13. package/lib/archiveDirectory.js +1 -1
  14. package/lib/auth.js +31 -5
  15. package/lib/bin/firebase.js +2 -2
  16. package/lib/command.js +18 -4
  17. package/lib/commands/appdistribution-distribute.js +4 -4
  18. package/lib/commands/{appdistribution-group-create.js → appdistribution-groups-create.js} +2 -1
  19. package/lib/commands/{appdistribution-group-delete.js → appdistribution-groups-delete.js} +3 -2
  20. package/lib/commands/appdistribution-groups-list.js +55 -0
  21. package/lib/commands/appdistribution-testers-list.js +52 -0
  22. package/lib/commands/appdistribution-testers-remove.js +1 -1
  23. package/lib/commands/apphosting-backends-create.js +4 -4
  24. package/lib/commands/apphosting-backends-delete.js +7 -15
  25. package/lib/commands/apphosting-backends-get.js +1 -1
  26. package/lib/commands/apphosting-config-export.js +51 -0
  27. package/lib/commands/apphosting-repos-create.js +23 -0
  28. package/lib/commands/apphosting-rollouts-create.js +14 -15
  29. package/lib/commands/apphosting-secrets-grantaccess.js +2 -2
  30. package/lib/commands/database-import.js +4 -2
  31. package/lib/commands/database-push.js +4 -2
  32. package/lib/commands/database-set.js +4 -2
  33. package/lib/commands/database-settings-get.js +1 -1
  34. package/lib/commands/database-settings-set.js +1 -1
  35. package/lib/commands/dataconnect-sdk-generate.js +4 -1
  36. package/lib/commands/dataconnect-services-list.js +4 -3
  37. package/lib/commands/dataconnect-sql-diff.js +1 -1
  38. package/lib/commands/dataconnect-sql-grant.js +37 -0
  39. package/lib/commands/dataconnect-sql-migrate.js +1 -1
  40. package/lib/commands/dataconnect-sql-shell.js +115 -0
  41. package/lib/commands/deploy.js +2 -0
  42. package/lib/commands/emulators-start.js +4 -1
  43. package/lib/commands/ext-dev-init.js +2 -2
  44. package/lib/commands/ext-dev-list.js +1 -1
  45. package/lib/commands/ext-dev-register.js +2 -2
  46. package/lib/commands/ext-dev-upload.js +2 -2
  47. package/lib/commands/ext-dev-usage.js +2 -2
  48. package/lib/commands/ext-info.js +3 -1
  49. package/lib/commands/ext-install.js +2 -2
  50. package/lib/commands/ext-sdk-install.js +88 -0
  51. package/lib/commands/ext.js +1 -0
  52. package/lib/commands/firestore-databases-restore.js +39 -1
  53. package/lib/commands/functions-secrets-access.js +2 -4
  54. package/lib/commands/index.js +15 -2
  55. package/lib/commands/init.js +25 -15
  56. package/lib/commands/setup-emulators-dataconnect.js +0 -13
  57. package/lib/commands/use.js +1 -1
  58. package/lib/config.js +14 -4
  59. package/lib/crashlytics/buildToolsJarHelper.js +2 -2
  60. package/lib/dataconnect/client.js +1 -1
  61. package/lib/dataconnect/dataplaneClient.js +12 -9
  62. package/lib/dataconnect/ensureApis.js +6 -1
  63. package/lib/dataconnect/fileUtils.js +15 -39
  64. package/lib/dataconnect/freeTrial.js +45 -9
  65. package/lib/dataconnect/load.js +3 -1
  66. package/lib/dataconnect/provisionCloudSql.js +39 -26
  67. package/lib/dataconnect/schemaMigration.js +215 -74
  68. package/lib/dataconnect/types.js +4 -1
  69. package/lib/dataconnect/webhook.js +32 -0
  70. package/lib/deploy/dataconnect/deploy.js +18 -15
  71. package/lib/deploy/dataconnect/prepare.js +41 -0
  72. package/lib/deploy/dataconnect/release.js +16 -7
  73. package/lib/deploy/extensions/deploy.js +3 -1
  74. package/lib/deploy/extensions/deploymentSummary.js +7 -3
  75. package/lib/deploy/extensions/planner.js +44 -5
  76. package/lib/deploy/extensions/prepare.js +45 -73
  77. package/lib/deploy/extensions/release.js +11 -10
  78. package/lib/deploy/extensions/tasks.js +32 -21
  79. package/lib/deploy/firestore/prepare.js +9 -0
  80. package/lib/deploy/firestore/release.js +3 -6
  81. package/lib/deploy/functions/checkIam.js +7 -2
  82. package/lib/deploy/functions/ensure.js +11 -3
  83. package/lib/deploy/functions/prepare.js +10 -2
  84. package/lib/deploy/functions/release/planner.js +2 -1
  85. package/lib/deploy/functions/runtimes/discovery/index.js +6 -2
  86. package/lib/deploy/functions/runtimes/node/index.js +5 -0
  87. package/lib/deploy/functions/services/auth.js +34 -3
  88. package/lib/deploy/functions/services/index.js +2 -0
  89. package/lib/deploy/index.js +8 -5
  90. package/lib/deploy/lifecycleHooks.js +2 -1
  91. package/lib/emulator/apphosting/config.js +27 -0
  92. package/lib/emulator/apphosting/index.js +38 -0
  93. package/lib/emulator/apphosting/serve.js +50 -0
  94. package/lib/emulator/apphosting/utils.js +18 -0
  95. package/lib/emulator/auth/handlers.js +27 -0
  96. package/lib/emulator/auth/operations.js +41 -2
  97. package/lib/emulator/auth/state.js +2 -1
  98. package/lib/emulator/commandUtils.js +8 -3
  99. package/lib/emulator/constants.js +4 -1
  100. package/lib/emulator/controller.js +48 -5
  101. package/lib/emulator/dataconnect/pg-gateway/auth/base-auth-flow.js +11 -0
  102. package/lib/emulator/dataconnect/pg-gateway/auth/cert.js +58 -0
  103. package/lib/emulator/dataconnect/pg-gateway/auth/index.js +22 -0
  104. package/lib/emulator/dataconnect/pg-gateway/auth/md5.js +124 -0
  105. package/lib/emulator/dataconnect/pg-gateway/auth/password.js +54 -0
  106. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/sasl-mechanism.js +34 -0
  107. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/scram-sha-256.js +270 -0
  108. package/lib/emulator/dataconnect/pg-gateway/auth/trust.js +2 -0
  109. package/lib/emulator/dataconnect/pg-gateway/backend-error.js +75 -0
  110. package/lib/emulator/dataconnect/pg-gateway/buffer-reader.js +54 -0
  111. package/lib/emulator/dataconnect/pg-gateway/buffer-writer.js +79 -0
  112. package/lib/emulator/dataconnect/pg-gateway/connection.js +315 -0
  113. package/lib/emulator/dataconnect/pg-gateway/connection.types.js +8 -0
  114. package/lib/emulator/dataconnect/pg-gateway/crypto.js +40 -0
  115. package/lib/emulator/dataconnect/pg-gateway/duplex.js +53 -0
  116. package/lib/emulator/dataconnect/pg-gateway/index.js +27 -0
  117. package/lib/emulator/dataconnect/pg-gateway/message-buffer.js +82 -0
  118. package/lib/emulator/dataconnect/pg-gateway/message-codes.js +52 -0
  119. package/lib/emulator/dataconnect/pg-gateway/platforms/node/index.js +16 -0
  120. package/lib/emulator/dataconnect/pg-gateway/polyfills/readable-stream-async-iterator.js +35 -0
  121. package/lib/emulator/dataconnect/pg-gateway/utils.js +40 -0
  122. package/lib/emulator/dataconnect/pgliteServer.js +95 -0
  123. package/lib/emulator/dataconnectEmulator.js +58 -75
  124. package/lib/emulator/dataconnectToolkitController.js +44 -0
  125. package/lib/emulator/downloadableEmulators.js +27 -16
  126. package/lib/emulator/emulatorLogger.js +3 -0
  127. package/lib/emulator/eventarcEmulator.js +1 -1
  128. package/lib/emulator/extensionsEmulator.js +38 -6
  129. package/lib/emulator/functionsEmulator.js +85 -41
  130. package/lib/emulator/functionsEmulatorShared.js +2 -1
  131. package/lib/emulator/functionsRuntimeWorker.js +2 -1
  132. package/lib/emulator/hub.js +13 -9
  133. package/lib/emulator/hubExport.js +10 -3
  134. package/lib/emulator/loggingEmulator.js +2 -2
  135. package/lib/emulator/portUtils.js +10 -11
  136. package/lib/emulator/registry.js +1 -0
  137. package/lib/emulator/storage/persistence.js +2 -2
  138. package/lib/emulator/storage/rules/runtime.js +1 -1
  139. package/lib/emulator/tasksEmulator.js +5 -2
  140. package/lib/emulator/types.js +3 -0
  141. package/lib/emulator/ui.js +51 -25
  142. package/lib/error.js +31 -1
  143. package/lib/experiments.js +5 -0
  144. package/lib/extensions/emulator/triggerHelper.js +1 -1
  145. package/lib/extensions/extensionsApi.js +14 -10
  146. package/lib/extensions/extensionsHelper.js +15 -6
  147. package/lib/extensions/localHelper.js +31 -0
  148. package/lib/extensions/runtimes/common.js +179 -39
  149. package/lib/extensions/runtimes/node.js +401 -0
  150. package/lib/extensions/types.js +25 -14
  151. package/lib/extensions/warnings.js +5 -2
  152. package/lib/firestore/api.js +2 -1
  153. package/lib/firestore/checkDatabaseType.js +10 -3
  154. package/lib/firestore/delete.js +11 -0
  155. package/lib/firestore/options.js +7 -0
  156. package/lib/frameworks/angular/index.js +15 -3
  157. package/lib/frameworks/constants.js +1 -1
  158. package/lib/frameworks/flutter/index.js +6 -6
  159. package/lib/frameworks/flutter/utils.js +34 -1
  160. package/lib/frameworks/next/index.js +10 -2
  161. package/lib/frameworks/next/utils.js +8 -5
  162. package/lib/frameworks/vite/index.js +2 -2
  163. package/lib/fsutils.js +13 -1
  164. package/lib/functions/constants.js +4 -0
  165. package/lib/functions/events/v1.js +9 -2
  166. package/lib/gcp/apphosting.js +1 -1
  167. package/lib/gcp/cloudmonitoring.js +3 -3
  168. package/lib/gcp/cloudsql/cloudsqladmin.js +32 -20
  169. package/lib/gcp/cloudsql/connect.js +49 -37
  170. package/lib/gcp/cloudsql/interactive.js +49 -0
  171. package/lib/gcp/cloudsql/permissions.js +165 -0
  172. package/lib/gcp/devConnect.js +38 -1
  173. package/lib/gcp/firestore.js +5 -1
  174. package/lib/gcp/secretManager.js +12 -5
  175. package/lib/getProjectNumber.js +1 -1
  176. package/lib/init/features/apphosting.js +15 -0
  177. package/lib/init/features/dataconnect/index.js +159 -120
  178. package/lib/init/features/dataconnect/sdk.js +77 -84
  179. package/lib/init/features/emulators.js +2 -15
  180. package/lib/init/features/firestore/index.js +20 -1
  181. package/lib/init/features/firestore/indexes.js +4 -4
  182. package/lib/init/features/genkit/index.js +444 -0
  183. package/lib/init/features/hosting/index.js +2 -2
  184. package/lib/init/features/index.js +1 -1
  185. package/lib/init/features/project.js +6 -6
  186. package/lib/init/features/storage.js +0 -2
  187. package/lib/init/index.js +1 -0
  188. package/lib/init/spawn.js +23 -2
  189. package/lib/logger.js +2 -2
  190. package/lib/management/projects.js +24 -4
  191. package/lib/projectUtils.js +1 -1
  192. package/lib/prompt.js +1 -1
  193. package/lib/rc.js +1 -8
  194. package/lib/requireAuth.js +19 -5
  195. package/lib/requireDatabaseInstance.js +1 -1
  196. package/lib/requirePermissions.js +1 -1
  197. package/lib/responseToError.js +5 -2
  198. package/lib/rulesDeploy.js +1 -1
  199. package/lib/templates.js +2 -2
  200. package/lib/utils.js +16 -11
  201. package/lib/vsCodeUtils.js +8 -0
  202. package/package.json +7 -6
  203. package/schema/connector-yaml.json +57 -17
  204. package/schema/firebase-config.json +24 -0
  205. package/templates/extensions/javascript/package.lint.json +2 -2
  206. package/templates/extensions/javascript/package.nolint.json +2 -2
  207. package/templates/extensions/typescript/package.lint.json +2 -2
  208. package/templates/extensions/typescript/package.nolint.json +2 -2
  209. package/templates/genkit/firebase.0.9.0.template +57 -0
  210. package/templates/init/apphosting/apphosting.yaml +23 -0
  211. package/templates/init/dataconnect/connector.yaml +0 -1
  212. package/templates/init/dataconnect/dataconnect-fdccompatiblemode.yaml +12 -0
  213. package/templates/init/dataconnect/dataconnect.yaml +1 -1
  214. package/templates/init/dataconnect/queries.gql +1 -2
  215. package/templates/init/functions/javascript/package.lint.json +2 -2
  216. package/templates/init/functions/javascript/package.nolint.json +2 -2
  217. package/templates/init/functions/typescript/package.lint.json +2 -2
  218. package/templates/init/functions/typescript/package.nolint.json +2 -2
  219. package/lib/ensureCloudResourceLocation.js +0 -12
  220. package/lib/init/features/genkit.js +0 -53
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateP4SA = exports.serviceAgentEmail = exports.sortConnectionsByCreateTime = exports.getGitRepositoryLink = exports.createGitRepositoryLink = exports.fetchGitHubInstallations = exports.listAllBranches = exports.listAllLinkableGitRepositories = exports.listAllConnections = exports.getConnection = exports.deleteConnection = exports.createConnection = exports.client = void 0;
3
+ exports.getRepoDetailsFromBackend = exports.extractGitRepositoryLinkComponents = exports.generateP4SA = exports.serviceAgentEmail = exports.sortConnectionsByCreateTime = exports.fetchGitRepositoryLinkReadToken = exports.getGitRepositoryLink = exports.createGitRepositoryLink = exports.fetchGitHubInstallations = exports.listAllBranches = exports.listAllLinkableGitRepositories = exports.listAllConnections = exports.getConnection = exports.deleteConnection = exports.createConnection = exports.client = void 0;
4
4
  const apiv2_1 = require("../apiv2");
5
5
  const api_1 = require("../api");
6
6
  const serviceusage_1 = require("./serviceusage");
7
+ const error_1 = require("../error");
8
+ const githubConnections_1 = require("../apphosting/githubConnections");
7
9
  const PAGE_SIZE_MAX = 1000;
8
10
  const LOCATION_OVERRIDE = process.env.FIREBASE_DEVELOPERCONNECT_LOCATION_OVERRIDE;
9
11
  exports.client = new apiv2_1.Client({
@@ -115,6 +117,12 @@ async function getGitRepositoryLink(projectId, location, connectionId, gitReposi
115
117
  return res.body;
116
118
  }
117
119
  exports.getGitRepositoryLink = getGitRepositoryLink;
120
+ async function fetchGitRepositoryLinkReadToken(projectId, location, connectionId, gitRepositoryLinkId) {
121
+ const name = `projects/${projectId}/locations/${LOCATION_OVERRIDE ?? location}/connections/${connectionId}/gitRepositoryLinks/${gitRepositoryLinkId}:fetchReadToken`;
122
+ const res = await exports.client.post(name);
123
+ return res.body;
124
+ }
125
+ exports.fetchGitRepositoryLinkReadToken = fetchGitRepositoryLinkReadToken;
118
126
  function sortConnectionsByCreateTime(connections) {
119
127
  return connections.sort((a, b) => {
120
128
  return Date.parse(a.createTime) - Date.parse(b.createTime);
@@ -130,3 +138,32 @@ async function generateP4SA(projectNumber) {
130
138
  await (0, serviceusage_1.generateServiceIdentityAndPoll)(projectNumber, new URL(devConnectOrigin).hostname, "apphosting");
131
139
  }
132
140
  exports.generateP4SA = generateP4SA;
141
+ function extractGitRepositoryLinkComponents(path) {
142
+ const connectionMatch = /connections\/([^\/]+)/.exec(path);
143
+ const repositoryMatch = /gitRepositoryLinks\/([^\/]+)/.exec(path);
144
+ const connection = connectionMatch ? connectionMatch[1] : null;
145
+ const gitRepoLink = repositoryMatch ? repositoryMatch[1] : null;
146
+ return { connection, gitRepoLink };
147
+ }
148
+ exports.extractGitRepositoryLinkComponents = extractGitRepositoryLinkComponents;
149
+ async function getRepoDetailsFromBackend(projectId, location, gitRepoLinkPath) {
150
+ const { connection, gitRepoLink } = extractGitRepositoryLinkComponents(gitRepoLinkPath);
151
+ if (!connection || !gitRepoLink) {
152
+ throw new error_1.FirebaseError(`Failed to extract connection or repository resource names from backend repository name.`);
153
+ }
154
+ const repoLink = await getGitRepositoryLink(projectId, location, connection, gitRepoLink);
155
+ const repoSlug = (0, githubConnections_1.extractRepoSlugFromUri)(repoLink.cloneUri);
156
+ const owner = repoSlug?.split("/")[0];
157
+ const repo = repoSlug?.split("/")[1];
158
+ if (!owner || !repo) {
159
+ throw new error_1.FirebaseError("Failed to parse owner and repo from git repository link");
160
+ }
161
+ const readToken = await fetchGitRepositoryLinkReadToken(projectId, location, connection, gitRepoLink);
162
+ return {
163
+ repoLink,
164
+ owner,
165
+ repo,
166
+ readToken,
167
+ };
168
+ }
169
+ exports.getRepoDetailsFromBackend = getRepoDetailsFromBackend;
@@ -62,7 +62,11 @@ async function deleteDocuments(project, docs, allowEmulator = false) {
62
62
  return { delete: doc.name };
63
63
  });
64
64
  const data = { writes };
65
- const res = await apiClient.post(url, data);
65
+ const res = await apiClient.post(url, data, {
66
+ retries: 10,
67
+ retryCodes: [429, 409, 503],
68
+ retryMaxTimeout: 20 * 1000,
69
+ });
66
70
  return res.body.writeResults.length;
67
71
  }
68
72
  exports.deleteDocuments = deleteDocuments;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.labels = exports.ensureApi = exports.isAppHostingManaged = exports.isFunctionsManaged = exports.FIREBASE_MANAGED = exports.ensureServiceAgentRole = exports.setIamPolicy = exports.getIamPolicy = exports.addVersion = exports.deleteSecret = exports.patchSecret = exports.createSecret = exports.toSecretVersionResourceName = exports.parseSecretVersionResourceName = exports.parseSecretResourceName = exports.secretExists = exports.destroySecretVersion = exports.accessSecretVersion = exports.getSecretVersion = exports.listSecretVersions = exports.getSecretMetadata = exports.listSecrets = exports.getSecret = exports.secretManagerConsoleUri = void 0;
3
+ exports.labels = exports.ensureApi = exports.isAppHostingManaged = exports.isFunctionsManaged = exports.FIREBASE_MANAGED = exports.checkServiceAgentRole = exports.ensureServiceAgentRole = exports.setIamPolicy = exports.getIamPolicy = exports.addVersion = exports.deleteSecret = exports.patchSecret = exports.createSecret = exports.toSecretVersionResourceName = exports.parseSecretVersionResourceName = exports.parseSecretResourceName = exports.secretExists = exports.destroySecretVersion = exports.accessSecretVersion = exports.getSecretVersion = exports.listSecretVersions = exports.getSecretMetadata = exports.listSecrets = exports.getSecret = exports.secretManagerConsoleUri = void 0;
4
4
  const utils_1 = require("../utils");
5
5
  const error_1 = require("../error");
6
6
  const apiv2_1 = require("../apiv2");
@@ -228,6 +228,14 @@ async function setIamPolicy(secret, bindings) {
228
228
  }
229
229
  exports.setIamPolicy = setIamPolicy;
230
230
  async function ensureServiceAgentRole(secret, serviceAccountEmails, role) {
231
+ const bindings = await checkServiceAgentRole(secret, serviceAccountEmails, role);
232
+ if (bindings.length) {
233
+ await module.exports.setIamPolicy(secret, bindings);
234
+ }
235
+ (0, utils_1.logLabeledSuccess)("secretmanager", `Granted ${role} on projects/${secret.projectId}/secrets/${secret.name} to ${serviceAccountEmails.join(", ")}`);
236
+ }
237
+ exports.ensureServiceAgentRole = ensureServiceAgentRole;
238
+ async function checkServiceAgentRole(secret, serviceAccountEmails, role) {
231
239
  const policy = await module.exports.getIamPolicy(secret);
232
240
  const bindings = policy.bindings || [];
233
241
  let binding = bindings.find((b) => b.role === role);
@@ -243,11 +251,10 @@ async function ensureServiceAgentRole(secret, serviceAccountEmails, role) {
243
251
  }
244
252
  }
245
253
  if (shouldShortCircuit)
246
- return;
247
- await module.exports.setIamPolicy(secret, bindings);
248
- (0, utils_1.logLabeledSuccess)("secretmanager", `Granted ${role} on projects/${secret.projectId}/secrets/${secret.name} to ${serviceAccountEmails.join(", ")}`);
254
+ return [];
255
+ return bindings;
249
256
  }
250
- exports.ensureServiceAgentRole = ensureServiceAgentRole;
257
+ exports.checkServiceAgentRole = checkServiceAgentRole;
251
258
  exports.FIREBASE_MANAGED = "firebase-managed";
252
259
  function isFunctionsManaged(secret) {
253
260
  return (secret.labels[exports.FIREBASE_MANAGED] === "true" || secret.labels[exports.FIREBASE_MANAGED] === "functions");
@@ -8,7 +8,7 @@ async function getProjectNumber(options) {
8
8
  return options.projectNumber;
9
9
  }
10
10
  const projectId = (0, projectUtils_1.needProjectId)(options);
11
- const metadata = await (0, projects_1.getFirebaseProject)(projectId);
11
+ const metadata = await (0, projects_1.getProject)(projectId);
12
12
  options.projectNumber = metadata.projectNumber;
13
13
  return options.projectNumber;
14
14
  }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.doSetup = void 0;
4
+ const clc = require("colorette");
5
+ const utils = require("../../utils");
6
+ const templates_1 = require("../../templates");
7
+ const cloudbilling_1 = require("../../gcp/cloudbilling");
8
+ const APPHOSTING_YAML_TEMPLATE = (0, templates_1.readTemplateSync)("init/apphosting/apphosting.yaml");
9
+ async function doSetup(setup, config) {
10
+ await (0, cloudbilling_1.checkBillingEnabled)(setup.projectId);
11
+ utils.logBullet("Writing default settings to " + clc.bold("apphosting.yaml") + "...");
12
+ await config.askWriteProjectFile("apphosting.yaml", APPHOSTING_YAML_TEMPLATE);
13
+ utils.logSuccess("Create a new App Hosting backend with `firebase apphosting:backends:create`");
14
+ }
15
+ exports.doSetup = doSetup;
@@ -8,17 +8,27 @@ const provisionCloudSql_1 = require("../../../dataconnect/provisionCloudSql");
8
8
  const freeTrial_1 = require("../../../dataconnect/freeTrial");
9
9
  const cloudsql = require("../../../gcp/cloudsql/cloudsqladmin");
10
10
  const ensureApis_1 = require("../../../dataconnect/ensureApis");
11
+ const experiments = require("../../../experiments");
11
12
  const client_1 = require("../../../dataconnect/client");
12
- const emulators_1 = require("../emulators");
13
+ const types_1 = require("../../../dataconnect/types");
13
14
  const names_1 = require("../../../dataconnect/names");
14
15
  const logger_1 = require("../../../logger");
15
16
  const templates_1 = require("../../../templates");
16
17
  const utils_1 = require("../../../utils");
18
+ const cloudbilling_1 = require("../../../gcp/cloudbilling");
19
+ const sdk = require("./sdk");
20
+ const fileUtils_1 = require("../../../dataconnect/fileUtils");
17
21
  const DATACONNECT_YAML_TEMPLATE = (0, templates_1.readTemplateSync)("init/dataconnect/dataconnect.yaml");
22
+ const DATACONNECT_YAML_COMPAT_EXPERIMENT_TEMPLATE = (0, templates_1.readTemplateSync)("init/dataconnect/dataconnect-fdccompatiblemode.yaml");
18
23
  const CONNECTOR_YAML_TEMPLATE = (0, templates_1.readTemplateSync)("init/dataconnect/connector.yaml");
19
24
  const SCHEMA_TEMPLATE = (0, templates_1.readTemplateSync)("init/dataconnect/schema.gql");
20
25
  const QUERIES_TEMPLATE = (0, templates_1.readTemplateSync)("init/dataconnect/queries.gql");
21
26
  const MUTATIONS_TEMPLATE = (0, templates_1.readTemplateSync)("init/dataconnect/mutations.gql");
27
+ const emptyConnector = {
28
+ id: "default",
29
+ path: "./connector",
30
+ files: [],
31
+ };
22
32
  const defaultConnector = {
23
33
  id: "default",
24
34
  path: "./connector",
@@ -33,14 +43,27 @@ const defaultConnector = {
33
43
  },
34
44
  ],
35
45
  };
46
+ const defaultSchema = { path: "schema.gql", content: SCHEMA_TEMPLATE };
36
47
  async function doSetup(setup, config) {
37
- const info = await askQuestions(setup, config);
48
+ const isBillingEnabled = setup.projectId ? await (0, cloudbilling_1.checkBillingEnabled)(setup.projectId) : false;
49
+ if (setup.projectId) {
50
+ isBillingEnabled ? await (0, ensureApis_1.ensureApis)(setup.projectId) : await (0, ensureApis_1.ensureSparkApis)(setup.projectId);
51
+ }
52
+ const info = await askQuestions(setup, isBillingEnabled);
38
53
  await actuate(setup, config, info);
39
- logger_1.logger.info("");
40
- (0, utils_1.logSuccess)(`If you'd like to generate an SDK for your new connector, run ${clc.bold("firebase init dataconnect:sdk")}`);
54
+ const cwdPlatformGuess = await (0, fileUtils_1.getPlatformFromFolder)(process.cwd());
55
+ if (cwdPlatformGuess !== types_1.Platform.NONE) {
56
+ await sdk.doSetup(setup, config);
57
+ }
58
+ else {
59
+ (0, utils_1.logBullet)(`If you'd like to add the generated SDK to your app your, run ${clc.bold("firebase init dataconnect:sdk")}`);
60
+ }
61
+ if (setup.projectId && !isBillingEnabled) {
62
+ (0, utils_1.logBullet)((0, freeTrial_1.upgradeInstructions)(setup.projectId));
63
+ }
41
64
  }
42
65
  exports.doSetup = doSetup;
43
- async function askQuestions(setup, config) {
66
+ async function askQuestions(setup, isBillingEnabled) {
44
67
  let info = {
45
68
  serviceId: "",
46
69
  locationId: "",
@@ -49,31 +72,37 @@ async function askQuestions(setup, config) {
49
72
  cloudSqlDatabase: "",
50
73
  isNewDatabase: false,
51
74
  connectors: [defaultConnector],
52
- schemaGql: [],
75
+ schemaGql: [defaultSchema],
53
76
  shouldProvisionCSQL: false,
54
77
  };
55
- info = await promptForService(setup, info);
56
- if (info.cloudSqlInstanceId === "") {
57
- info = await promptForCloudSQLInstance(setup, info);
78
+ info = await promptForExistingServices(setup, info, isBillingEnabled);
79
+ const requiredConfigUnset = info.serviceId === "" ||
80
+ info.cloudSqlInstanceId === "" ||
81
+ info.locationId === "" ||
82
+ info.cloudSqlDatabase === "";
83
+ const shouldConfigureBackend = isBillingEnabled && requiredConfigUnset
84
+ ? await (0, prompt_1.confirm)({
85
+ message: `Would you like to configure your backend resources now?`,
86
+ default: true,
87
+ })
88
+ : false;
89
+ if (shouldConfigureBackend) {
90
+ info = await promptForService(info);
91
+ info = await promptForCloudSQL(setup, info);
92
+ info.shouldProvisionCSQL = !!(setup.projectId &&
93
+ (info.isNewInstance || info.isNewDatabase) &&
94
+ isBillingEnabled &&
95
+ (await (0, prompt_1.confirm)({
96
+ message: `Would you like to provision your Cloud SQL instance and database now?${info.isNewInstance ? " This will take several minutes." : ""}.`,
97
+ default: true,
98
+ })));
58
99
  }
59
- if (info.cloudSqlDatabase === "") {
60
- info = await promptForDatabase(setup, config, info);
100
+ else {
101
+ info.serviceId = info.serviceId || (0, path_1.basename)(process.cwd());
102
+ info.cloudSqlInstanceId = info.cloudSqlInstanceId || `${info.serviceId || "app"}-fdc`;
103
+ info.locationId = info.locationId || `us-central1`;
104
+ info.cloudSqlDatabase = info.cloudSqlDatabase || `fdcdb`;
61
105
  }
62
- const defaultConnectionString = setup.rcfile.dataconnectEmulatorConfig?.postgres?.localConnectionString ??
63
- emulators_1.DEFAULT_POSTGRES_CONNECTION;
64
- const localConnectionString = await (0, prompt_1.promptOnce)({
65
- type: "input",
66
- name: "localConnectionString",
67
- message: `What is the connection string of the local Postgres instance you would like to use with the Data Connect emulator?`,
68
- default: defaultConnectionString,
69
- });
70
- setup.rcfile.dataconnectEmulatorConfig = { postgres: { localConnectionString } };
71
- info.shouldProvisionCSQL = !!(setup.projectId &&
72
- (info.isNewInstance || info.isNewDatabase) &&
73
- (await (0, prompt_1.confirm)({
74
- message: "Would you like to provision your CloudSQL instance and database now? This will take a few minutes.",
75
- default: true,
76
- })));
77
106
  return info;
78
107
  }
79
108
  async function actuate(setup, config, info) {
@@ -84,6 +113,7 @@ async function actuate(setup, config, info) {
84
113
  locationId: info.locationId,
85
114
  instanceId: info.cloudSqlInstanceId,
86
115
  databaseId: info.cloudSqlDatabase,
116
+ configYamlPath: (0, path_1.join)(config.get("dataconnect.source"), "dataconnect.yaml"),
87
117
  enableGoogleMlIntegration: false,
88
118
  waitForCreation: false,
89
119
  });
@@ -92,22 +122,23 @@ async function actuate(setup, config, info) {
92
122
  exports.actuate = actuate;
93
123
  async function writeFiles(config, info) {
94
124
  const dir = config.get("dataconnect.source") || "dataconnect";
95
- console.log(dir);
96
125
  const subbedDataconnectYaml = subDataconnectYamlValues({
97
126
  ...info,
98
127
  connectorDirs: info.connectors.map((c) => c.path),
99
128
  });
129
+ if (!config.get("dataconnect.source")) {
130
+ if (!info.schemaGql.length && !info.connectors.flatMap((r) => r.files).length) {
131
+ info.schemaGql = [defaultSchema];
132
+ info.connectors = [defaultConnector];
133
+ }
134
+ }
100
135
  config.set("dataconnect", { source: dir });
101
- await config.askWriteProjectFile((0, path_1.join)(dir, "dataconnect.yaml"), subbedDataconnectYaml);
136
+ await config.askWriteProjectFile((0, path_1.join)(dir, "dataconnect.yaml"), subbedDataconnectYaml, false, true);
102
137
  if (info.schemaGql.length) {
103
- (0, utils_1.logSuccess)("The service you chose already has GQL files deployed. We'll use those instead of the default templates.");
104
138
  for (const f of info.schemaGql) {
105
139
  await config.askWriteProjectFile((0, path_1.join)(dir, "schema", f.path), f.content);
106
140
  }
107
141
  }
108
- else {
109
- await config.askWriteProjectFile((0, path_1.join)(dir, "schema", "schema.gql"), SCHEMA_TEMPLATE);
110
- }
111
142
  for (const c of info.connectors) {
112
143
  await writeConnectorFiles(config, c);
113
144
  }
@@ -128,7 +159,9 @@ function subDataconnectYamlValues(replacementValues) {
128
159
  connectorDirs: "__connectorDirs__",
129
160
  locationId: "__location__",
130
161
  };
131
- let replaced = DATACONNECT_YAML_TEMPLATE;
162
+ let replaced = experiments.isEnabled("fdccompatiblemode")
163
+ ? DATACONNECT_YAML_COMPAT_EXPERIMENT_TEMPLATE
164
+ : DATACONNECT_YAML_TEMPLATE;
132
165
  for (const [k, v] of Object.entries(replacementValues)) {
133
166
  replaced = replaced.replace(replacements[k], JSON.stringify(v));
134
167
  }
@@ -144,81 +177,80 @@ function subConnectorYamlValues(replacementValues) {
144
177
  }
145
178
  return replaced;
146
179
  }
147
- async function promptForService(setup, info) {
148
- if (setup.projectId) {
149
- await (0, ensureApis_1.ensureApis)(setup.projectId);
150
- const existingServices = await (0, client_1.listAllServices)(setup.projectId);
151
- const existingServicesAndSchemas = await Promise.all(existingServices.map(async (s) => {
180
+ async function promptForExistingServices(setup, info, isBillingEnabled) {
181
+ if (!setup.projectId || !isBillingEnabled) {
182
+ return info;
183
+ }
184
+ const existingServices = await (0, client_1.listAllServices)(setup.projectId);
185
+ const existingServicesAndSchemas = await Promise.all(existingServices.map(async (s) => {
186
+ return {
187
+ service: s,
188
+ schema: await (0, client_1.getSchema)(s.name),
189
+ };
190
+ }));
191
+ if (existingServicesAndSchemas.length) {
192
+ const choices = existingServicesAndSchemas.map((s) => {
193
+ const serviceName = (0, names_1.parseServiceName)(s.service.name);
152
194
  return {
153
- service: s,
154
- schema: await (0, client_1.getSchema)(s.name),
195
+ name: `${serviceName.location}/${serviceName.serviceId}`,
196
+ value: s,
155
197
  };
156
- }));
157
- if (existingServicesAndSchemas.length) {
158
- const choices = existingServicesAndSchemas.map((s) => {
159
- const serviceName = (0, names_1.parseServiceName)(s.service.name);
160
- return {
161
- name: `${serviceName.location}/${serviceName.serviceId}`,
162
- value: s,
163
- };
164
- });
165
- choices.push({ name: "Create a new service", value: undefined });
166
- const choice = await (0, prompt_1.promptOnce)({
167
- message: "Your project already has existing services. Which would you like to set up local files for?",
168
- type: "list",
169
- choices,
170
- });
171
- if (choice) {
172
- const serviceName = (0, names_1.parseServiceName)(choice.service.name);
173
- info.serviceId = serviceName.serviceId;
174
- info.locationId = serviceName.location;
175
- if (choice.schema) {
176
- if (choice.schema.primaryDatasource.postgresql?.cloudSql.instance) {
177
- const instanceName = (0, names_1.parseCloudSQLInstanceName)(choice.schema.primaryDatasource.postgresql?.cloudSql.instance);
178
- info.cloudSqlInstanceId = instanceName.instanceId;
179
- }
180
- if (choice.schema.source.files) {
181
- info.schemaGql = choice.schema.source.files;
182
- }
183
- info.cloudSqlDatabase = choice.schema.primaryDatasource.postgresql?.database ?? "";
184
- const connectors = await (0, client_1.listConnectors)(choice.service.name, [
185
- "connectors.name",
186
- "connectors.source.files",
187
- ]);
188
- if (connectors.length) {
189
- info.connectors = connectors.map((c) => {
190
- const id = c.name.split("/").pop();
191
- return {
192
- id,
193
- path: `./${id}`,
194
- files: c.source.files || [],
195
- };
196
- });
197
- }
198
+ });
199
+ choices.push({ name: "Create a new service", value: undefined });
200
+ const choice = await (0, prompt_1.promptOnce)({
201
+ message: "Your project already has existing services. Which would you like to set up local files for?",
202
+ type: "list",
203
+ choices,
204
+ });
205
+ if (choice) {
206
+ const serviceName = (0, names_1.parseServiceName)(choice.service.name);
207
+ info.serviceId = serviceName.serviceId;
208
+ info.locationId = serviceName.location;
209
+ info.schemaGql = [];
210
+ info.connectors = [emptyConnector];
211
+ if (choice.schema) {
212
+ const primaryDatasource = choice.schema.datasources.find((d) => d.postgresql);
213
+ if (primaryDatasource?.postgresql?.cloudSql.instance) {
214
+ const instanceName = (0, names_1.parseCloudSQLInstanceName)(primaryDatasource.postgresql.cloudSql.instance);
215
+ info.cloudSqlInstanceId = instanceName.instanceId;
216
+ }
217
+ if (choice.schema.source.files?.length) {
218
+ info.schemaGql = choice.schema.source.files;
219
+ }
220
+ info.cloudSqlDatabase = primaryDatasource?.postgresql?.database ?? "";
221
+ const connectors = await (0, client_1.listConnectors)(choice.service.name, [
222
+ "connectors.name",
223
+ "connectors.source.files",
224
+ ]);
225
+ if (connectors.length) {
226
+ info.connectors = connectors.map((c) => {
227
+ const id = c.name.split("/").pop();
228
+ return {
229
+ id,
230
+ path: connectors.length === 1 ? "./connector" : `./${id}`,
231
+ files: c.source.files || [],
232
+ };
233
+ });
198
234
  }
199
235
  }
200
236
  }
201
237
  }
202
- if (info.serviceId === "") {
203
- info.serviceId = await (0, prompt_1.promptOnce)({
204
- message: "What ID would you like to use for this service?",
205
- type: "input",
206
- default: "my-service",
207
- });
208
- }
209
238
  return info;
210
239
  }
211
- async function promptForCloudSQLInstance(setup, info) {
212
- if (setup.projectId) {
240
+ async function promptForCloudSQL(setup, info) {
241
+ if (info.cloudSqlInstanceId === "" && setup.projectId) {
213
242
  const instances = await cloudsql.listInstances(setup.projectId);
214
243
  let choices = instances.map((i) => {
215
- return { name: i.name, value: i.name, location: i.region };
244
+ let display = `${i.name} (${i.region})`;
245
+ if (i.settings.userLabels?.["firebase-data-connect"] === "ft") {
246
+ display += " (no cost trial)";
247
+ }
248
+ return { name: display, value: i.name, location: i.region };
216
249
  });
217
250
  choices = choices.filter((c) => info.locationId === "" || info.locationId === c.location);
218
251
  if (choices.length) {
219
- const freeTrialInstanceId = await (0, freeTrial_1.checkForFreeTrialInstance)(setup.projectId);
220
- if (!freeTrialInstanceId) {
221
- choices.push({ name: "Create a new instance", value: "", location: "" });
252
+ if (!(await (0, freeTrial_1.checkFreeTrialInstanceUsed)(setup.projectId))) {
253
+ choices.push({ name: "Create a new free trial instance", value: "", location: "" });
222
254
  }
223
255
  info.cloudSqlInstanceId = await (0, prompt_1.promptOnce)({
224
256
  message: `Which CloudSQL instance would you like to use?`,
@@ -235,7 +267,7 @@ async function promptForCloudSQLInstance(setup, info) {
235
267
  info.cloudSqlInstanceId = await (0, prompt_1.promptOnce)({
236
268
  message: `What ID would you like to use for your new CloudSQL instance?`,
237
269
  type: "input",
238
- default: `fdc-sql`,
270
+ default: `${info.serviceId || "app"}-fdc`,
239
271
  });
240
272
  }
241
273
  if (info.locationId === "") {
@@ -246,30 +278,7 @@ async function promptForCloudSQLInstance(setup, info) {
246
278
  choices,
247
279
  });
248
280
  }
249
- return info;
250
- }
251
- async function locationChoices(setup) {
252
- if (setup.projectId) {
253
- const locations = await (0, client_1.listLocations)(setup.projectId);
254
- return locations.map((l) => {
255
- return { name: l, value: l };
256
- });
257
- }
258
- else {
259
- return [
260
- { name: "us-central1", value: "us-central1" },
261
- { name: "europe-north1", value: "europe-north1" },
262
- { name: "europe-central2", value: "europe-central2" },
263
- { name: "europe-west1", value: "europe-west1" },
264
- { name: "southamerica-west1", value: "southamerica-west1" },
265
- { name: "us-east4", value: "us-east4" },
266
- { name: "us-west1", value: "us-west1" },
267
- { name: "asia-southeast1", value: "asia-southeast1" },
268
- ];
269
- }
270
- }
271
- async function promptForDatabase(setup, config, info) {
272
- if (!info.isNewInstance && setup.projectId) {
281
+ if (info.cloudSqlDatabase === "" && setup.projectId) {
273
282
  try {
274
283
  const dbs = await cloudsql.listDatabases(setup.projectId, info.cloudSqlInstanceId);
275
284
  const choices = dbs.map((d) => {
@@ -298,3 +307,33 @@ async function promptForDatabase(setup, config, info) {
298
307
  }
299
308
  return info;
300
309
  }
310
+ async function promptForService(info) {
311
+ if (info.serviceId === "") {
312
+ info.serviceId = await (0, prompt_1.promptOnce)({
313
+ message: "What ID would you like to use for this service?",
314
+ type: "input",
315
+ default: (0, path_1.basename)(process.cwd()),
316
+ });
317
+ }
318
+ return info;
319
+ }
320
+ async function locationChoices(setup) {
321
+ if (setup.projectId) {
322
+ const locations = await (0, client_1.listLocations)(setup.projectId);
323
+ return locations.map((l) => {
324
+ return { name: l, value: l };
325
+ });
326
+ }
327
+ else {
328
+ return [
329
+ { name: "us-central1", value: "us-central1" },
330
+ { name: "europe-north1", value: "europe-north1" },
331
+ { name: "europe-central2", value: "europe-central2" },
332
+ { name: "europe-west1", value: "europe-west1" },
333
+ { name: "southamerica-west1", value: "southamerica-west1" },
334
+ { name: "us-east4", value: "us-east4" },
335
+ { name: "us-west1", value: "us-west1" },
336
+ { name: "asia-southeast1", value: "asia-southeast1" },
337
+ ];
338
+ }
339
+ }