Repository: firebase/firebase-tools (ts)

Issue:
firebase init fails at Firestore Setup for new project

### [REQUIRED] Environment info

<!-- What version of the Firebase CLI (`firebase-tools`) are you using? Note that your issue may already be fixed in the latest versions. The latest version can be found at https://github.com/firebase/firebase-tools/releases -->

<!-- Output of `firebase --version` -->

**firebase-tools:** 11.12.0

<!-- e.g. macOS, Windows, Ubuntu -->

**Platform:** MacOS Monterey 12.6

### [REQUIRED] Test case

Project creation from scratch

### [REQUIRED] Steps to reproduce


- Run `firebase init` in an empty folder
- Select feature: `Firestore`
- Firebase project: `Create a new project`

```
% firebase init

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  /Users/myuser/supercoolstorage

? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to confirm your choices. Firestore: Configure security rules and indexes files for Firestore

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

? Please select an option: Create a new project
i  If you want to create a project in a Google Cloud organization or folder, please use "firebase projects:create" instead, and return to this command when you've created the project.
? Please specify a unique project id (warning: cannot be modified afterward) [6-30 characters]:
 supercoolstorage
? What would you like to call your project? (defaults to your project ID) 
✔ Creating Google Cloud Platform project
✔ Adding Firebase resources to Google Cloud Platform project

🎉🎉🎉 Your Firebase project is ready! 🎉🎉🎉

Project information:
   - Project ID: supercoolstorage
   - Project Name: supercoolstorage

Firebase console is available at
https://console.firebase.google.com/project/supercoolstorage/overview
i  Using project supercoolstorage (supercoolstorage)

=== Firestore Setup

Error: It looks like you haven't used Cloud Firestore in this project before. Go to https://console.firebase.google.com/project/supercoolstorage/firestore to create your Cloud Firestore database.
```



### [REQUIRED] Expected behavior

<!-- What is the expected behavior? -->

- No error, creating the Firestore database should be part of the normal process, be it in the command line or in the web console.
- Please complete the Firebase initialization of my current folder (firebase.json, etc.) instead of crashing and letting me go to the web console to create a database, and then run `firebase init` again but this time selecting `existing project`.

### [REQUIRED] Actual behavior

<!-- Run the command with --debug flag, and include the logs below. -->

Error "you haven't used Cloud Firestore in this project before"

Of course I haven't, this is a new project to be created, per the last question.

Process exits with code 1

The current folder is not initialized, zero files were created (no firebase.json, etc.)

The new project `supercoolstorage` seems to be created server-side, though.

Pull request description:
Stop using AppEngine to check database mode
### Description
Recently, we stopped automatically creating & linking AppEngine apps to Firestore on creation (https://cloud.google.com/firestore/docs/app-engine-requirement). However, `firebase init` was still checking for the location of this app, and relying on it to check what mode the database was in. We now instead check via the firestore API (https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases#DatabaseType) and skip the default resource location check.

Fixes #5230 and #5452

### Scenarios Tested
Created a new project, and created a Firestore DB. Checked that Cloud Resource location was not set yet (via the Firebase console settings page), and then confirmed that `firebase init firestore` then `firebase deploy` run without errors.





Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 527a409d2..fcec825e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,2 +1,3 @@
-- Refactor Functions Emulator. (#5422)
-- Fix race condition when discovering functions. (#5444)
+- Refactors Functions Emulator. (#5422)
+- Fixes race condition when discovering functions. (#5444)
+- Fixes issue where `init firestore` was unecessarilly checking for default resource location. (#5230 and #5452)
diff --git a/src/firestore/checkDatabaseType.ts b/src/firestore/checkDatabaseType.ts
index 2d7c489e2..897feaf48 100644
--- a/src/firestore/checkDatabaseType.ts
+++ b/src/firestore/checkDatabaseType.ts
@@ -1,21 +1,24 @@
-import { appengineOrigin } from "../api";
+import { firestoreOrigin } from "../api";
 import { Client } from "../apiv2";
 import { logger } from "../logger";
 
 /**
  * Determine the Firestore database type for a given project. One of:
  *   - DATABASE_TYPE_UNSPECIFIED (unspecified)
- *   - CLOUD_DATASTORE (Datastore legacy)
- *   - CLOUD_FIRESTORE (Firestore native mode)
- *   - CLOUD_DATASTORE_COMPATIBILITY (Firestore datastore mode)
+ *   - DATASTORE_MODE(Datastore legacy)
+ *   - FIRESTORE_NATIVE (Firestore native mode)
  *
  * @param projectId the Firebase project ID.
  */
-export async function checkDatabaseType(projectId: string): Promise<string | undefined> {
+export async function checkDatabaseType(
+  projectId: string
+): Promise<"DATASTORE_MODE" | "FIRESTORE_NATIVE" | "DATABASE_TYPE_UNSPECIFIED" | undefined> {
   try {
-    const client = new Client({ urlPrefix: appengineOrigin, apiVersion: "v1" });
-    const resp = await client.get<{ databaseType?: string }>(`/apps/${projectId}`);
-    return resp.body.databaseType;
+    const client = new Client({ urlPrefix: firestoreOrigin, apiVersion: "v1" });
+    const resp = await client.get<{
+      type?: "DATASTORE_MODE" | "FIRESTORE_NATIVE" | "DATABASE_TYPE_UNSPECIFIED";
+    }>(`/projects/${projectId}/databases/(default)`);
+    return resp.body.type;
   } catch (err: any) {
     logger.debug("error getting database type", err);
     return undefined;
diff --git a/src/init/features/firestore/index.ts b/src/init/features/firestore/index.ts
index 050d387b2..988644a28 100644
--- a/src/init/features/firestore/index.ts
+++ b/src/init/features/firestore/index.ts
@@ -1,6 +1,5 @@
 import { logger } from "../../../logger";
 import * as apiEnabled from "../../../ensureApiEnabled";
-import { ensureLocationSet } from "../../../ensureCloudResourceLocation";
 import { requirePermissions } from "../../../requirePermissions";
 import { checkDatabaseType } from "../../../firestore/checkDatabaseType";
 import * as rules from "./rules";
@@ -36,14 +35,13 @@ async function checkProjectSetup(setup: any, config: any, options: any) {
 
   if (!dbType) {
     throw firestoreUnusedError;
-  } else if (dbType !== "CLOUD_FIRESTORE") {
+  } else if (dbType !== "FIRESTORE_NATIVE") {
     throw new FirebaseError(
       `It looks like this project is using Cloud Datastore or Cloud Firestore in Datastore mode. The Firebase CLI can only manage projects using Cloud Firestore in Native mode. For more information, visit https://cloud.google.com/datastore/docs/firestore-or-datastore`,
       { exit: 1 }
     );
   }
 
-  ensureLocationSet(setup.projectLocation, "Cloud Firestore");
   await requirePermissions({ ...options, project: setup.projectId });
 }
 


Test patch:
diff --git a/src/test/init/features/firestore.spec.ts b/src/test/init/features/firestore.spec.ts
index 012178165..38009e529 100644
--- a/src/test/init/features/firestore.spec.ts
+++ b/src/test/init/features/firestore.spec.ts
@@ -21,7 +21,7 @@ describe("firestore", () => {
 
     // By default, mock Firestore enabled in Native mode
     checkApiStub.returns(true);
-    checkDbTypeStub.returns("CLOUD_FIRESTORE");
+    checkDbTypeStub.returns("FIRESTORE_NATIVE");
   });
 
   afterEach(() => {
@@ -46,15 +46,6 @@ describe("firestore", () => {
       expect(_.get(setup, "config.firestore")).to.deep.equal({});
     });
 
-    it("should error when cloud resource location is not set", async () => {
-      const setup = { config: {}, projectId: "my-project-123" };
-
-      await expect(firestore.doSetup(setup, {}, {})).to.eventually.be.rejectedWith(
-        FirebaseError,
-        "Cloud resource location is not set"
-      );
-    });
-
     it("should error when the firestore API is not enabled", async () => {
       checkApiStub.returns(false);