Initial commit
This commit is contained in:
+188
@@ -0,0 +1,188 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
/// <reference types="node" />
|
||||
import { Agent } from 'http';
|
||||
import { Credential } from './credential';
|
||||
/**
|
||||
* Available options to pass to {@link firebase-admin.app#initializeApp}.
|
||||
*/
|
||||
export interface AppOptions {
|
||||
/**
|
||||
* A {@link firebase-admin.app#Credential} object used to
|
||||
* authenticate the Admin SDK.
|
||||
*
|
||||
* See {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK}
|
||||
* for detailed documentation and code samples.
|
||||
*/
|
||||
credential?: Credential;
|
||||
/**
|
||||
* The object to use as the {@link https://firebase.google.com/docs/reference/security/database/#auth | auth}
|
||||
* variable in your Realtime Database Rules when the Admin SDK reads from or
|
||||
* writes to the Realtime Database. This allows you to downscope the Admin SDK
|
||||
* from its default full read and write privileges.
|
||||
*
|
||||
* You can pass `null` to act as an unauthenticated client.
|
||||
*
|
||||
* See
|
||||
* {@link https://firebase.google.com/docs/database/admin/start#authenticate-with-limited-privileges |
|
||||
* Authenticate with limited privileges}
|
||||
* for detailed documentation and code samples.
|
||||
*/
|
||||
databaseAuthVariableOverride?: object | null;
|
||||
/**
|
||||
* The URL of the Realtime Database from which to read and write data.
|
||||
*/
|
||||
databaseURL?: string;
|
||||
/**
|
||||
* The ID of the service account to be used for signing custom tokens. This
|
||||
* can be found in the `client_email` field of a service account JSON file.
|
||||
*/
|
||||
serviceAccountId?: string;
|
||||
/**
|
||||
* The name of the Google Cloud Storage bucket used for storing application data.
|
||||
* Use only the bucket name without any prefixes or additions (do *not* prefix
|
||||
* the name with "gs://").
|
||||
*/
|
||||
storageBucket?: string;
|
||||
/**
|
||||
* The ID of the Google Cloud project associated with the App.
|
||||
*/
|
||||
projectId?: string;
|
||||
/**
|
||||
* An {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent}
|
||||
* to be used when making outgoing HTTP calls. This Agent instance is used
|
||||
* by all services that make REST calls (e.g. `auth`, `messaging`,
|
||||
* `projectManagement`).
|
||||
*
|
||||
* Realtime Database and Firestore use other means of communicating with
|
||||
* the backend servers, so they do not use this HTTP Agent. `Credential`
|
||||
* instances also do not use this HTTP Agent, but instead support
|
||||
* specifying an HTTP Agent in the corresponding factory methods.
|
||||
*/
|
||||
httpAgent?: Agent;
|
||||
}
|
||||
/**
|
||||
* A Firebase app holds the initialization information for a collection of
|
||||
* services.
|
||||
*/
|
||||
export interface App {
|
||||
/**
|
||||
* The (read-only) name for this app.
|
||||
*
|
||||
* The default app's name is `"[DEFAULT]"`.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // The default app's name is "[DEFAULT]"
|
||||
* initializeApp(defaultAppConfig);
|
||||
* console.log(admin.app().name); // "[DEFAULT]"
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // A named app's name is what you provide to initializeApp()
|
||||
* const otherApp = initializeApp(otherAppConfig, "other");
|
||||
* console.log(otherApp.name); // "other"
|
||||
* ```
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The (read-only) configuration options for this app. These are the original
|
||||
* parameters given in {@link firebase-admin.app#initializeApp}.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const app = initializeApp(config);
|
||||
* console.log(app.options.credential === config.credential); // true
|
||||
* console.log(app.options.databaseURL === config.databaseURL); // true
|
||||
* ```
|
||||
*/
|
||||
options: AppOptions;
|
||||
}
|
||||
/**
|
||||
* `FirebaseError` is a subclass of the standard JavaScript `Error` object. In
|
||||
* addition to a message string and stack trace, it contains a string code.
|
||||
*/
|
||||
export interface FirebaseError {
|
||||
/**
|
||||
* Error codes are strings using the following format: `"service/string-code"`.
|
||||
* Some examples include `"auth/invalid-uid"` and
|
||||
* `"messaging/invalid-recipient"`.
|
||||
*
|
||||
* While the message for a given error can change, the code will remain the same
|
||||
* between backward-compatible versions of the Firebase SDK.
|
||||
*/
|
||||
code: string;
|
||||
/**
|
||||
* An explanatory message for the error that just occurred.
|
||||
*
|
||||
* This message is designed to be helpful to you, the developer. Because
|
||||
* it generally does not convey meaningful information to end users,
|
||||
* this message should not be displayed in your application.
|
||||
*/
|
||||
message: string;
|
||||
/**
|
||||
* A string value containing the execution backtrace when the error originally
|
||||
* occurred.
|
||||
*
|
||||
* This information can be useful for troubleshooting the cause of the error with
|
||||
* {@link https://firebase.google.com/support | Firebase Support}.
|
||||
*/
|
||||
stack?: string;
|
||||
/**
|
||||
* Returns a JSON-serializable object representation of this error.
|
||||
*
|
||||
* @returns A JSON-serializable representation of this object.
|
||||
*/
|
||||
toJSON(): object;
|
||||
}
|
||||
/**
|
||||
* Composite type which includes both a `FirebaseError` object and an index
|
||||
* which can be used to get the errored item.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* var registrationTokens = [token1, token2, token3];
|
||||
* admin.messaging().subscribeToTopic(registrationTokens, 'topic-name')
|
||||
* .then(function(response) {
|
||||
* if (response.failureCount > 0) {
|
||||
* console.log("Following devices unsucessfully subscribed to topic:");
|
||||
* response.errors.forEach(function(error) {
|
||||
* var invalidToken = registrationTokens[error.index];
|
||||
* console.log(invalidToken, error.error);
|
||||
* });
|
||||
* } else {
|
||||
* console.log("All devices successfully subscribed to topic:", response);
|
||||
* }
|
||||
* })
|
||||
* .catch(function(error) {
|
||||
* console.log("Error subscribing to topic:", error);
|
||||
* });
|
||||
*```
|
||||
*/
|
||||
export interface FirebaseArrayIndexError {
|
||||
/**
|
||||
* The index of the errored item within the original array passed as part of the
|
||||
* called API method.
|
||||
*/
|
||||
index: number;
|
||||
/**
|
||||
* The error object.
|
||||
*/
|
||||
error: FirebaseError;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
/// <reference types="node" />
|
||||
import { Agent } from 'http';
|
||||
import { Credential, ServiceAccount } from './credential';
|
||||
/**
|
||||
* Returns a credential created from the
|
||||
* {@link https://developers.google.com/identity/protocols/application-default-credentials |
|
||||
* Google Application Default Credentials}
|
||||
* that grants admin access to Firebase services. This credential can be used
|
||||
* in the call to {@link firebase-admin.app#initializeApp}.
|
||||
*
|
||||
* Google Application Default Credentials are available on any Google
|
||||
* infrastructure, such as Google App Engine and Google Compute Engine.
|
||||
*
|
||||
* See
|
||||
* {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK}
|
||||
* for more details.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* initializeApp({
|
||||
* credential: applicationDefault(),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent}
|
||||
* to be used when retrieving access tokens from Google token servers.
|
||||
*
|
||||
* @returns A credential authenticated via Google
|
||||
* Application Default Credentials that can be used to initialize an app.
|
||||
*/
|
||||
export declare function applicationDefault(httpAgent?: Agent): Credential;
|
||||
/**
|
||||
* Returns a credential created from the provided service account that grants
|
||||
* admin access to Firebase services. This credential can be used in the call
|
||||
* to {@link firebase-admin.app#initializeApp}.
|
||||
*
|
||||
* See
|
||||
* {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK}
|
||||
* for more details.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // Providing a path to a service account key JSON file
|
||||
* const serviceAccount = require("path/to/serviceAccountKey.json");
|
||||
* initializeApp({
|
||||
* credential: cert(serviceAccount),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // Providing a service account object inline
|
||||
* initializeApp({
|
||||
* credential: cert({
|
||||
* projectId: "<PROJECT_ID>",
|
||||
* clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com",
|
||||
* privateKey: "-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n"
|
||||
* }),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param serviceAccountPathOrObject - The path to a service
|
||||
* account key JSON file or an object representing a service account key.
|
||||
* @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent}
|
||||
* to be used when retrieving access tokens from Google token servers.
|
||||
*
|
||||
* @returns A credential authenticated via the
|
||||
* provided service account that can be used to initialize an app.
|
||||
*/
|
||||
export declare function cert(serviceAccountPathOrObject: string | ServiceAccount, httpAgent?: Agent): Credential;
|
||||
/**
|
||||
* Returns a credential created from the provided refresh token that grants
|
||||
* admin access to Firebase services. This credential can be used in the call
|
||||
* to {@link firebase-admin.app#initializeApp}.
|
||||
*
|
||||
* See
|
||||
* {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK}
|
||||
* for more details.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // Providing a path to a refresh token JSON file
|
||||
* const refreshToken = require("path/to/refreshToken.json");
|
||||
* initializeApp({
|
||||
* credential: refreshToken(refreshToken),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param refreshTokenPathOrObject - The path to a Google
|
||||
* OAuth2 refresh token JSON file or an object representing a Google OAuth2
|
||||
* refresh token.
|
||||
* @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent}
|
||||
* to be used when retrieving access tokens from Google token servers.
|
||||
*
|
||||
* @returns A credential authenticated via the
|
||||
* provided service account that can be used to initialize an app.
|
||||
*/
|
||||
export declare function refreshToken(refreshTokenPathOrObject: string | object, httpAgent?: Agent): Credential;
|
||||
/**
|
||||
* Clears the global ADC cache. Exported for testing.
|
||||
*/
|
||||
export declare function clearGlobalAppDefaultCred(): void;
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.clearGlobalAppDefaultCred = exports.refreshToken = exports.cert = exports.applicationDefault = void 0;
|
||||
var credential_internal_1 = require("./credential-internal");
|
||||
var globalAppDefaultCred;
|
||||
var globalCertCreds = {};
|
||||
var globalRefreshTokenCreds = {};
|
||||
/**
|
||||
* Returns a credential created from the
|
||||
* {@link https://developers.google.com/identity/protocols/application-default-credentials |
|
||||
* Google Application Default Credentials}
|
||||
* that grants admin access to Firebase services. This credential can be used
|
||||
* in the call to {@link firebase-admin.app#initializeApp}.
|
||||
*
|
||||
* Google Application Default Credentials are available on any Google
|
||||
* infrastructure, such as Google App Engine and Google Compute Engine.
|
||||
*
|
||||
* See
|
||||
* {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK}
|
||||
* for more details.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* initializeApp({
|
||||
* credential: applicationDefault(),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent}
|
||||
* to be used when retrieving access tokens from Google token servers.
|
||||
*
|
||||
* @returns A credential authenticated via Google
|
||||
* Application Default Credentials that can be used to initialize an app.
|
||||
*/
|
||||
function applicationDefault(httpAgent) {
|
||||
if (typeof globalAppDefaultCred === 'undefined') {
|
||||
globalAppDefaultCred = credential_internal_1.getApplicationDefault(httpAgent);
|
||||
}
|
||||
return globalAppDefaultCred;
|
||||
}
|
||||
exports.applicationDefault = applicationDefault;
|
||||
/**
|
||||
* Returns a credential created from the provided service account that grants
|
||||
* admin access to Firebase services. This credential can be used in the call
|
||||
* to {@link firebase-admin.app#initializeApp}.
|
||||
*
|
||||
* See
|
||||
* {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK}
|
||||
* for more details.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // Providing a path to a service account key JSON file
|
||||
* const serviceAccount = require("path/to/serviceAccountKey.json");
|
||||
* initializeApp({
|
||||
* credential: cert(serviceAccount),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // Providing a service account object inline
|
||||
* initializeApp({
|
||||
* credential: cert({
|
||||
* projectId: "<PROJECT_ID>",
|
||||
* clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com",
|
||||
* privateKey: "-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n"
|
||||
* }),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param serviceAccountPathOrObject - The path to a service
|
||||
* account key JSON file or an object representing a service account key.
|
||||
* @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent}
|
||||
* to be used when retrieving access tokens from Google token servers.
|
||||
*
|
||||
* @returns A credential authenticated via the
|
||||
* provided service account that can be used to initialize an app.
|
||||
*/
|
||||
function cert(serviceAccountPathOrObject, httpAgent) {
|
||||
var stringifiedServiceAccount = JSON.stringify(serviceAccountPathOrObject);
|
||||
if (!(stringifiedServiceAccount in globalCertCreds)) {
|
||||
globalCertCreds[stringifiedServiceAccount] = new credential_internal_1.ServiceAccountCredential(serviceAccountPathOrObject, httpAgent);
|
||||
}
|
||||
return globalCertCreds[stringifiedServiceAccount];
|
||||
}
|
||||
exports.cert = cert;
|
||||
/**
|
||||
* Returns a credential created from the provided refresh token that grants
|
||||
* admin access to Firebase services. This credential can be used in the call
|
||||
* to {@link firebase-admin.app#initializeApp}.
|
||||
*
|
||||
* See
|
||||
* {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK}
|
||||
* for more details.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* // Providing a path to a refresh token JSON file
|
||||
* const refreshToken = require("path/to/refreshToken.json");
|
||||
* initializeApp({
|
||||
* credential: refreshToken(refreshToken),
|
||||
* databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param refreshTokenPathOrObject - The path to a Google
|
||||
* OAuth2 refresh token JSON file or an object representing a Google OAuth2
|
||||
* refresh token.
|
||||
* @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent}
|
||||
* to be used when retrieving access tokens from Google token servers.
|
||||
*
|
||||
* @returns A credential authenticated via the
|
||||
* provided service account that can be used to initialize an app.
|
||||
*/
|
||||
function refreshToken(refreshTokenPathOrObject, httpAgent) {
|
||||
var stringifiedRefreshToken = JSON.stringify(refreshTokenPathOrObject);
|
||||
if (!(stringifiedRefreshToken in globalRefreshTokenCreds)) {
|
||||
globalRefreshTokenCreds[stringifiedRefreshToken] = new credential_internal_1.RefreshTokenCredential(refreshTokenPathOrObject, httpAgent);
|
||||
}
|
||||
return globalRefreshTokenCreds[stringifiedRefreshToken];
|
||||
}
|
||||
exports.refreshToken = refreshToken;
|
||||
/**
|
||||
* Clears the global ADC cache. Exported for testing.
|
||||
*/
|
||||
function clearGlobalAppDefaultCred() {
|
||||
globalAppDefaultCred = undefined;
|
||||
}
|
||||
exports.clearGlobalAppDefaultCred = clearGlobalAppDefaultCred;
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2020 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
/// <reference types="node" />
|
||||
import { Agent } from 'http';
|
||||
import { Credential, GoogleOAuthAccessToken } from './credential';
|
||||
/**
|
||||
* Implementation of Credential that uses a service account.
|
||||
*/
|
||||
export declare class ServiceAccountCredential implements Credential {
|
||||
private readonly httpAgent?;
|
||||
readonly implicit: boolean;
|
||||
readonly projectId: string;
|
||||
readonly privateKey: string;
|
||||
readonly clientEmail: string;
|
||||
private readonly httpClient;
|
||||
/**
|
||||
* Creates a new ServiceAccountCredential from the given parameters.
|
||||
*
|
||||
* @param serviceAccountPathOrObject - Service account json object or path to a service account json file.
|
||||
* @param httpAgent - Optional http.Agent to use when calling the remote token server.
|
||||
* @param implicit - An optinal boolean indicating whether this credential was implicitly discovered from the
|
||||
* environment, as opposed to being explicitly specified by the developer.
|
||||
*
|
||||
* @constructor
|
||||
*/
|
||||
constructor(serviceAccountPathOrObject: string | object, httpAgent?: Agent | undefined, implicit?: boolean);
|
||||
getAccessToken(): Promise<GoogleOAuthAccessToken>;
|
||||
private createAuthJwt_;
|
||||
}
|
||||
/**
|
||||
* Implementation of Credential that gets access tokens from the metadata service available
|
||||
* in the Google Cloud Platform. This authenticates the process as the default service account
|
||||
* of an App Engine instance or Google Compute Engine machine.
|
||||
*/
|
||||
export declare class ComputeEngineCredential implements Credential {
|
||||
private readonly httpClient;
|
||||
private readonly httpAgent?;
|
||||
private projectId?;
|
||||
constructor(httpAgent?: Agent);
|
||||
getAccessToken(): Promise<GoogleOAuthAccessToken>;
|
||||
getProjectId(): Promise<string>;
|
||||
private buildRequest;
|
||||
}
|
||||
/**
|
||||
* Implementation of Credential that gets access tokens from refresh tokens.
|
||||
*/
|
||||
export declare class RefreshTokenCredential implements Credential {
|
||||
private readonly httpAgent?;
|
||||
readonly implicit: boolean;
|
||||
private readonly refreshToken;
|
||||
private readonly httpClient;
|
||||
/**
|
||||
* Creates a new RefreshTokenCredential from the given parameters.
|
||||
*
|
||||
* @param refreshTokenPathOrObject - Refresh token json object or path to a refresh token
|
||||
* (user credentials) json file.
|
||||
* @param httpAgent - Optional http.Agent to use when calling the remote token server.
|
||||
* @param implicit - An optinal boolean indicating whether this credential was implicitly
|
||||
* discovered from the environment, as opposed to being explicitly specified by the developer.
|
||||
*
|
||||
* @constructor
|
||||
*/
|
||||
constructor(refreshTokenPathOrObject: string | object, httpAgent?: Agent | undefined, implicit?: boolean);
|
||||
getAccessToken(): Promise<GoogleOAuthAccessToken>;
|
||||
}
|
||||
/**
|
||||
* Checks if the given credential was loaded via the application default credentials mechanism. This
|
||||
* includes all ComputeEngineCredential instances, and the ServiceAccountCredential and RefreshTokenCredential
|
||||
* instances that were loaded from well-known files or environment variables, rather than being explicitly
|
||||
* instantiated.
|
||||
*
|
||||
* @param credential - The credential instance to check.
|
||||
*/
|
||||
export declare function isApplicationDefault(credential?: Credential): boolean;
|
||||
export declare function getApplicationDefault(httpAgent?: Agent): Credential;
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2020 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getApplicationDefault = exports.isApplicationDefault = exports.RefreshTokenCredential = exports.ComputeEngineCredential = exports.ServiceAccountCredential = void 0;
|
||||
var fs = require("fs");
|
||||
var os = require("os");
|
||||
var path = require("path");
|
||||
var error_1 = require("../utils/error");
|
||||
var api_request_1 = require("../utils/api-request");
|
||||
var util = require("../utils/validator");
|
||||
var GOOGLE_TOKEN_AUDIENCE = 'https://accounts.google.com/o/oauth2/token';
|
||||
var GOOGLE_AUTH_TOKEN_HOST = 'accounts.google.com';
|
||||
var GOOGLE_AUTH_TOKEN_PATH = '/o/oauth2/token';
|
||||
// NOTE: the Google Metadata Service uses HTTP over a vlan
|
||||
var GOOGLE_METADATA_SERVICE_HOST = 'metadata.google.internal';
|
||||
var GOOGLE_METADATA_SERVICE_TOKEN_PATH = '/computeMetadata/v1/instance/service-accounts/default/token';
|
||||
var GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH = '/computeMetadata/v1/project/project-id';
|
||||
var configDir = (function () {
|
||||
// Windows has a dedicated low-rights location for apps at ~/Application Data
|
||||
var sys = os.platform();
|
||||
if (sys && sys.length >= 3 && sys.substring(0, 3).toLowerCase() === 'win') {
|
||||
return process.env.APPDATA;
|
||||
}
|
||||
// On *nix the gcloud cli creates a . dir.
|
||||
return process.env.HOME && path.resolve(process.env.HOME, '.config');
|
||||
})();
|
||||
var GCLOUD_CREDENTIAL_SUFFIX = 'gcloud/application_default_credentials.json';
|
||||
var GCLOUD_CREDENTIAL_PATH = configDir && path.resolve(configDir, GCLOUD_CREDENTIAL_SUFFIX);
|
||||
var REFRESH_TOKEN_HOST = 'www.googleapis.com';
|
||||
var REFRESH_TOKEN_PATH = '/oauth2/v4/token';
|
||||
var ONE_HOUR_IN_SECONDS = 60 * 60;
|
||||
var JWT_ALGORITHM = 'RS256';
|
||||
/**
|
||||
* Implementation of Credential that uses a service account.
|
||||
*/
|
||||
var ServiceAccountCredential = /** @class */ (function () {
|
||||
/**
|
||||
* Creates a new ServiceAccountCredential from the given parameters.
|
||||
*
|
||||
* @param serviceAccountPathOrObject - Service account json object or path to a service account json file.
|
||||
* @param httpAgent - Optional http.Agent to use when calling the remote token server.
|
||||
* @param implicit - An optinal boolean indicating whether this credential was implicitly discovered from the
|
||||
* environment, as opposed to being explicitly specified by the developer.
|
||||
*
|
||||
* @constructor
|
||||
*/
|
||||
function ServiceAccountCredential(serviceAccountPathOrObject, httpAgent, implicit) {
|
||||
if (implicit === void 0) { implicit = false; }
|
||||
this.httpAgent = httpAgent;
|
||||
this.implicit = implicit;
|
||||
var serviceAccount = (typeof serviceAccountPathOrObject === 'string') ?
|
||||
ServiceAccount.fromPath(serviceAccountPathOrObject)
|
||||
: new ServiceAccount(serviceAccountPathOrObject);
|
||||
this.projectId = serviceAccount.projectId;
|
||||
this.privateKey = serviceAccount.privateKey;
|
||||
this.clientEmail = serviceAccount.clientEmail;
|
||||
this.httpClient = new api_request_1.HttpClient();
|
||||
}
|
||||
ServiceAccountCredential.prototype.getAccessToken = function () {
|
||||
var token = this.createAuthJwt_();
|
||||
var postData = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3A' +
|
||||
'grant-type%3Ajwt-bearer&assertion=' + token;
|
||||
var request = {
|
||||
method: 'POST',
|
||||
url: "https://" + GOOGLE_AUTH_TOKEN_HOST + GOOGLE_AUTH_TOKEN_PATH,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
data: postData,
|
||||
httpAgent: this.httpAgent,
|
||||
};
|
||||
return requestAccessToken(this.httpClient, request);
|
||||
};
|
||||
ServiceAccountCredential.prototype.createAuthJwt_ = function () {
|
||||
var claims = {
|
||||
scope: [
|
||||
'https://www.googleapis.com/auth/cloud-platform',
|
||||
'https://www.googleapis.com/auth/firebase.database',
|
||||
'https://www.googleapis.com/auth/firebase.messaging',
|
||||
'https://www.googleapis.com/auth/identitytoolkit',
|
||||
'https://www.googleapis.com/auth/userinfo.email',
|
||||
].join(' '),
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
var jwt = require('jsonwebtoken');
|
||||
// This method is actually synchronous so we can capture and return the buffer.
|
||||
return jwt.sign(claims, this.privateKey, {
|
||||
audience: GOOGLE_TOKEN_AUDIENCE,
|
||||
expiresIn: ONE_HOUR_IN_SECONDS,
|
||||
issuer: this.clientEmail,
|
||||
algorithm: JWT_ALGORITHM,
|
||||
});
|
||||
};
|
||||
return ServiceAccountCredential;
|
||||
}());
|
||||
exports.ServiceAccountCredential = ServiceAccountCredential;
|
||||
/**
|
||||
* A struct containing the properties necessary to use service account JSON credentials.
|
||||
*/
|
||||
var ServiceAccount = /** @class */ (function () {
|
||||
function ServiceAccount(json) {
|
||||
if (!util.isNonNullObject(json)) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Service account must be an object.');
|
||||
}
|
||||
copyAttr(this, json, 'projectId', 'project_id');
|
||||
copyAttr(this, json, 'privateKey', 'private_key');
|
||||
copyAttr(this, json, 'clientEmail', 'client_email');
|
||||
var errorMessage;
|
||||
if (!util.isNonEmptyString(this.projectId)) {
|
||||
errorMessage = 'Service account object must contain a string "project_id" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.privateKey)) {
|
||||
errorMessage = 'Service account object must contain a string "private_key" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.clientEmail)) {
|
||||
errorMessage = 'Service account object must contain a string "client_email" property.';
|
||||
}
|
||||
if (typeof errorMessage !== 'undefined') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
var forge = require('node-forge');
|
||||
try {
|
||||
forge.pki.privateKeyFromPem(this.privateKey);
|
||||
}
|
||||
catch (error) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse private key: ' + error);
|
||||
}
|
||||
}
|
||||
ServiceAccount.fromPath = function (filePath) {
|
||||
try {
|
||||
return new ServiceAccount(JSON.parse(fs.readFileSync(filePath, 'utf8')));
|
||||
}
|
||||
catch (error) {
|
||||
// Throw a nicely formed error message if the file contents cannot be parsed
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse service account json file: ' + error);
|
||||
}
|
||||
};
|
||||
return ServiceAccount;
|
||||
}());
|
||||
/**
|
||||
* Implementation of Credential that gets access tokens from the metadata service available
|
||||
* in the Google Cloud Platform. This authenticates the process as the default service account
|
||||
* of an App Engine instance or Google Compute Engine machine.
|
||||
*/
|
||||
var ComputeEngineCredential = /** @class */ (function () {
|
||||
function ComputeEngineCredential(httpAgent) {
|
||||
this.httpClient = new api_request_1.HttpClient();
|
||||
this.httpAgent = httpAgent;
|
||||
}
|
||||
ComputeEngineCredential.prototype.getAccessToken = function () {
|
||||
var request = this.buildRequest(GOOGLE_METADATA_SERVICE_TOKEN_PATH);
|
||||
return requestAccessToken(this.httpClient, request);
|
||||
};
|
||||
ComputeEngineCredential.prototype.getProjectId = function () {
|
||||
var _this = this;
|
||||
if (this.projectId) {
|
||||
return Promise.resolve(this.projectId);
|
||||
}
|
||||
var request = this.buildRequest(GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH);
|
||||
return this.httpClient.send(request)
|
||||
.then(function (resp) {
|
||||
_this.projectId = resp.text;
|
||||
return _this.projectId;
|
||||
})
|
||||
.catch(function (err) {
|
||||
var detail = (err instanceof api_request_1.HttpError) ? getDetailFromResponse(err.response) : err.message;
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, "Failed to determine project ID: " + detail);
|
||||
});
|
||||
};
|
||||
ComputeEngineCredential.prototype.buildRequest = function (urlPath) {
|
||||
return {
|
||||
method: 'GET',
|
||||
url: "http://" + GOOGLE_METADATA_SERVICE_HOST + urlPath,
|
||||
headers: {
|
||||
'Metadata-Flavor': 'Google',
|
||||
},
|
||||
httpAgent: this.httpAgent,
|
||||
};
|
||||
};
|
||||
return ComputeEngineCredential;
|
||||
}());
|
||||
exports.ComputeEngineCredential = ComputeEngineCredential;
|
||||
/**
|
||||
* Implementation of Credential that gets access tokens from refresh tokens.
|
||||
*/
|
||||
var RefreshTokenCredential = /** @class */ (function () {
|
||||
/**
|
||||
* Creates a new RefreshTokenCredential from the given parameters.
|
||||
*
|
||||
* @param refreshTokenPathOrObject - Refresh token json object or path to a refresh token
|
||||
* (user credentials) json file.
|
||||
* @param httpAgent - Optional http.Agent to use when calling the remote token server.
|
||||
* @param implicit - An optinal boolean indicating whether this credential was implicitly
|
||||
* discovered from the environment, as opposed to being explicitly specified by the developer.
|
||||
*
|
||||
* @constructor
|
||||
*/
|
||||
function RefreshTokenCredential(refreshTokenPathOrObject, httpAgent, implicit) {
|
||||
if (implicit === void 0) { implicit = false; }
|
||||
this.httpAgent = httpAgent;
|
||||
this.implicit = implicit;
|
||||
this.refreshToken = (typeof refreshTokenPathOrObject === 'string') ?
|
||||
RefreshToken.fromPath(refreshTokenPathOrObject)
|
||||
: new RefreshToken(refreshTokenPathOrObject);
|
||||
this.httpClient = new api_request_1.HttpClient();
|
||||
}
|
||||
RefreshTokenCredential.prototype.getAccessToken = function () {
|
||||
var postData = 'client_id=' + this.refreshToken.clientId + '&' +
|
||||
'client_secret=' + this.refreshToken.clientSecret + '&' +
|
||||
'refresh_token=' + this.refreshToken.refreshToken + '&' +
|
||||
'grant_type=refresh_token';
|
||||
var request = {
|
||||
method: 'POST',
|
||||
url: "https://" + REFRESH_TOKEN_HOST + REFRESH_TOKEN_PATH,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
data: postData,
|
||||
httpAgent: this.httpAgent,
|
||||
};
|
||||
return requestAccessToken(this.httpClient, request);
|
||||
};
|
||||
return RefreshTokenCredential;
|
||||
}());
|
||||
exports.RefreshTokenCredential = RefreshTokenCredential;
|
||||
var RefreshToken = /** @class */ (function () {
|
||||
function RefreshToken(json) {
|
||||
copyAttr(this, json, 'clientId', 'client_id');
|
||||
copyAttr(this, json, 'clientSecret', 'client_secret');
|
||||
copyAttr(this, json, 'refreshToken', 'refresh_token');
|
||||
copyAttr(this, json, 'type', 'type');
|
||||
var errorMessage;
|
||||
if (!util.isNonEmptyString(this.clientId)) {
|
||||
errorMessage = 'Refresh token must contain a "client_id" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.clientSecret)) {
|
||||
errorMessage = 'Refresh token must contain a "client_secret" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.refreshToken)) {
|
||||
errorMessage = 'Refresh token must contain a "refresh_token" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.type)) {
|
||||
errorMessage = 'Refresh token must contain a "type" property.';
|
||||
}
|
||||
if (typeof errorMessage !== 'undefined') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Tries to load a RefreshToken from a path. Throws if the path doesn't exist or the
|
||||
* data at the path is invalid.
|
||||
*/
|
||||
RefreshToken.fromPath = function (filePath) {
|
||||
try {
|
||||
return new RefreshToken(JSON.parse(fs.readFileSync(filePath, 'utf8')));
|
||||
}
|
||||
catch (error) {
|
||||
// Throw a nicely formed error message if the file contents cannot be parsed
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse refresh token file: ' + error);
|
||||
}
|
||||
};
|
||||
return RefreshToken;
|
||||
}());
|
||||
/**
|
||||
* Checks if the given credential was loaded via the application default credentials mechanism. This
|
||||
* includes all ComputeEngineCredential instances, and the ServiceAccountCredential and RefreshTokenCredential
|
||||
* instances that were loaded from well-known files or environment variables, rather than being explicitly
|
||||
* instantiated.
|
||||
*
|
||||
* @param credential - The credential instance to check.
|
||||
*/
|
||||
function isApplicationDefault(credential) {
|
||||
return credential instanceof ComputeEngineCredential ||
|
||||
(credential instanceof ServiceAccountCredential && credential.implicit) ||
|
||||
(credential instanceof RefreshTokenCredential && credential.implicit);
|
||||
}
|
||||
exports.isApplicationDefault = isApplicationDefault;
|
||||
function getApplicationDefault(httpAgent) {
|
||||
if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
|
||||
return credentialFromFile(process.env.GOOGLE_APPLICATION_CREDENTIALS, httpAgent);
|
||||
}
|
||||
// It is OK to not have this file. If it is present, it must be valid.
|
||||
if (GCLOUD_CREDENTIAL_PATH) {
|
||||
var refreshToken = readCredentialFile(GCLOUD_CREDENTIAL_PATH, true);
|
||||
if (refreshToken) {
|
||||
return new RefreshTokenCredential(refreshToken, httpAgent, true);
|
||||
}
|
||||
}
|
||||
return new ComputeEngineCredential(httpAgent);
|
||||
}
|
||||
exports.getApplicationDefault = getApplicationDefault;
|
||||
/**
|
||||
* Copies the specified property from one object to another.
|
||||
*
|
||||
* If no property exists by the given "key", looks for a property identified by "alt", and copies it instead.
|
||||
* This can be used to implement behaviors such as "copy property myKey or my_key".
|
||||
*
|
||||
* @param to - Target object to copy the property into.
|
||||
* @param from - Source object to copy the property from.
|
||||
* @param key - Name of the property to copy.
|
||||
* @param alt - Alternative name of the property to copy.
|
||||
*/
|
||||
function copyAttr(to, from, key, alt) {
|
||||
var tmp = from[key] || from[alt];
|
||||
if (typeof tmp !== 'undefined') {
|
||||
to[key] = tmp;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Obtain a new OAuth2 token by making a remote service call.
|
||||
*/
|
||||
function requestAccessToken(client, request) {
|
||||
return client.send(request).then(function (resp) {
|
||||
var json = resp.data;
|
||||
if (!json.access_token || !json.expires_in) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, "Unexpected response while fetching access token: " + JSON.stringify(json));
|
||||
}
|
||||
return json;
|
||||
}).catch(function (err) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, getErrorMessage(err));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Constructs a human-readable error message from the given Error.
|
||||
*/
|
||||
function getErrorMessage(err) {
|
||||
var detail = (err instanceof api_request_1.HttpError) ? getDetailFromResponse(err.response) : err.message;
|
||||
return "Error fetching access token: " + detail;
|
||||
}
|
||||
/**
|
||||
* Extracts details from the given HTTP error response, and returns a human-readable description. If
|
||||
* the response is JSON-formatted, looks up the error and error_description fields sent by the
|
||||
* Google Auth servers. Otherwise returns the entire response payload as the error detail.
|
||||
*/
|
||||
function getDetailFromResponse(response) {
|
||||
if (response.isJson() && response.data.error) {
|
||||
var json = response.data;
|
||||
var detail = json.error;
|
||||
if (json.error_description) {
|
||||
detail += ' (' + json.error_description + ')';
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
return response.text || 'Missing error payload';
|
||||
}
|
||||
function credentialFromFile(filePath, httpAgent) {
|
||||
var credentialsFile = readCredentialFile(filePath);
|
||||
if (typeof credentialsFile !== 'object' || credentialsFile === null) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse contents of the credentials file as an object');
|
||||
}
|
||||
if (credentialsFile.type === 'service_account') {
|
||||
return new ServiceAccountCredential(credentialsFile, httpAgent, true);
|
||||
}
|
||||
if (credentialsFile.type === 'authorized_user') {
|
||||
return new RefreshTokenCredential(credentialsFile, httpAgent, true);
|
||||
}
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Invalid contents in the credentials file');
|
||||
}
|
||||
function readCredentialFile(filePath, ignoreMissing) {
|
||||
var fileText;
|
||||
try {
|
||||
fileText = fs.readFileSync(filePath, 'utf8');
|
||||
}
|
||||
catch (error) {
|
||||
if (ignoreMissing) {
|
||||
return null;
|
||||
}
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, "Failed to read credentials from file " + filePath + ": " + error);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(fileText);
|
||||
}
|
||||
catch (error) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse contents of the credentials file as an object: ' + error);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
export interface ServiceAccount {
|
||||
projectId?: string;
|
||||
clientEmail?: string;
|
||||
privateKey?: string;
|
||||
}
|
||||
/**
|
||||
* Interface for Google OAuth 2.0 access tokens.
|
||||
*/
|
||||
export interface GoogleOAuthAccessToken {
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
}
|
||||
/**
|
||||
* Interface that provides Google OAuth2 access tokens used to authenticate
|
||||
* with Firebase services.
|
||||
*
|
||||
* In most cases, you will not need to implement this yourself and can instead
|
||||
* use the default implementations provided by the `firebase-admin/app` module.
|
||||
*/
|
||||
export interface Credential {
|
||||
/**
|
||||
* Returns a Google OAuth2 access token object used to authenticate with
|
||||
* Firebase services.
|
||||
*
|
||||
* @returns A Google OAuth2 access token object.
|
||||
*/
|
||||
getAccessToken(): Promise<GoogleOAuthAccessToken>;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { Credential } from './credential';
|
||||
/**
|
||||
* Type representing a Firebase OAuth access token (derived from a Google OAuth2 access token) which
|
||||
* can be used to authenticate to Firebase services such as the Realtime Database and Auth.
|
||||
*/
|
||||
export interface FirebaseAccessToken {
|
||||
accessToken: string;
|
||||
expirationTime: number;
|
||||
}
|
||||
/**
|
||||
* Internals of a FirebaseApp instance.
|
||||
*/
|
||||
export declare class FirebaseAppInternals {
|
||||
private credential_;
|
||||
private cachedToken_;
|
||||
private tokenListeners_;
|
||||
constructor(credential_: Credential);
|
||||
getToken(forceRefresh?: boolean): Promise<FirebaseAccessToken>;
|
||||
getCachedToken(): FirebaseAccessToken | null;
|
||||
private refreshToken;
|
||||
private shouldRefresh;
|
||||
/**
|
||||
* Adds a listener that is called each time a token changes.
|
||||
*
|
||||
* @param listener - The listener that will be called with each new token.
|
||||
*/
|
||||
addAuthTokenListener(listener: (token: string) => void): void;
|
||||
/**
|
||||
* Removes a token listener.
|
||||
*
|
||||
* @param listener - The listener to remove.
|
||||
*/
|
||||
removeAuthTokenListener(listener: (token: string) => void): void;
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FirebaseApp = exports.FirebaseAppInternals = void 0;
|
||||
var credential_internal_1 = require("./credential-internal");
|
||||
var validator = require("../utils/validator");
|
||||
var deep_copy_1 = require("../utils/deep-copy");
|
||||
var error_1 = require("../utils/error");
|
||||
var TOKEN_EXPIRY_THRESHOLD_MILLIS = 5 * 60 * 1000;
|
||||
/**
|
||||
* Internals of a FirebaseApp instance.
|
||||
*/
|
||||
var FirebaseAppInternals = /** @class */ (function () {
|
||||
function FirebaseAppInternals(credential_) {
|
||||
this.credential_ = credential_;
|
||||
this.tokenListeners_ = [];
|
||||
}
|
||||
FirebaseAppInternals.prototype.getToken = function (forceRefresh) {
|
||||
if (forceRefresh === void 0) { forceRefresh = false; }
|
||||
if (forceRefresh || this.shouldRefresh()) {
|
||||
return this.refreshToken();
|
||||
}
|
||||
return Promise.resolve(this.cachedToken_);
|
||||
};
|
||||
FirebaseAppInternals.prototype.getCachedToken = function () {
|
||||
return this.cachedToken_ || null;
|
||||
};
|
||||
FirebaseAppInternals.prototype.refreshToken = function () {
|
||||
var _this = this;
|
||||
return Promise.resolve(this.credential_.getAccessToken())
|
||||
.then(function (result) {
|
||||
// Since the developer can provide the credential implementation, we want to weakly verify
|
||||
// the return type until the type is properly exported.
|
||||
if (!validator.isNonNullObject(result) ||
|
||||
typeof result.expires_in !== 'number' ||
|
||||
typeof result.access_token !== 'string') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, "Invalid access token generated: \"" + JSON.stringify(result) + "\". Valid access " +
|
||||
'tokens must be an object with the "expires_in" (number) and "access_token" ' +
|
||||
'(string) properties.');
|
||||
}
|
||||
var token = {
|
||||
accessToken: result.access_token,
|
||||
expirationTime: Date.now() + (result.expires_in * 1000),
|
||||
};
|
||||
if (!_this.cachedToken_
|
||||
|| _this.cachedToken_.accessToken !== token.accessToken
|
||||
|| _this.cachedToken_.expirationTime !== token.expirationTime) {
|
||||
// Update the cache before firing listeners. Listeners may directly query the
|
||||
// cached token state.
|
||||
_this.cachedToken_ = token;
|
||||
_this.tokenListeners_.forEach(function (listener) {
|
||||
listener(token.accessToken);
|
||||
});
|
||||
}
|
||||
return token;
|
||||
})
|
||||
.catch(function (error) {
|
||||
var errorMessage = (typeof error === 'string') ? error : error.message;
|
||||
errorMessage = 'Credential implementation provided to initializeApp() via the ' +
|
||||
'"credential" property failed to fetch a valid Google OAuth2 access token with the ' +
|
||||
("following error: \"" + errorMessage + "\".");
|
||||
if (errorMessage.indexOf('invalid_grant') !== -1) {
|
||||
errorMessage += ' There are two likely causes: (1) your server time is not properly ' +
|
||||
'synced or (2) your certificate key file has been revoked. To solve (1), re-sync the ' +
|
||||
'time on your server. To solve (2), make sure the key ID for your key file is still ' +
|
||||
'present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If ' +
|
||||
'not, generate a new key file at ' +
|
||||
'https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.';
|
||||
}
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
|
||||
});
|
||||
};
|
||||
FirebaseAppInternals.prototype.shouldRefresh = function () {
|
||||
return !this.cachedToken_ || (this.cachedToken_.expirationTime - Date.now()) <= TOKEN_EXPIRY_THRESHOLD_MILLIS;
|
||||
};
|
||||
/**
|
||||
* Adds a listener that is called each time a token changes.
|
||||
*
|
||||
* @param listener - The listener that will be called with each new token.
|
||||
*/
|
||||
FirebaseAppInternals.prototype.addAuthTokenListener = function (listener) {
|
||||
this.tokenListeners_.push(listener);
|
||||
if (this.cachedToken_) {
|
||||
listener(this.cachedToken_.accessToken);
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Removes a token listener.
|
||||
*
|
||||
* @param listener - The listener to remove.
|
||||
*/
|
||||
FirebaseAppInternals.prototype.removeAuthTokenListener = function (listener) {
|
||||
this.tokenListeners_ = this.tokenListeners_.filter(function (other) { return other !== listener; });
|
||||
};
|
||||
return FirebaseAppInternals;
|
||||
}());
|
||||
exports.FirebaseAppInternals = FirebaseAppInternals;
|
||||
/**
|
||||
* Global context object for a collection of services using a shared authentication state.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
var FirebaseApp = /** @class */ (function () {
|
||||
function FirebaseApp(options, name, appStore) {
|
||||
this.appStore = appStore;
|
||||
this.services_ = {};
|
||||
this.isDeleted_ = false;
|
||||
this.name_ = name;
|
||||
this.options_ = deep_copy_1.deepCopy(options);
|
||||
if (!validator.isNonNullObject(this.options_)) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Invalid Firebase app options passed as the first argument to initializeApp() for the ' +
|
||||
("app named \"" + this.name_ + "\". Options must be a non-null object."));
|
||||
}
|
||||
var hasCredential = ('credential' in this.options_);
|
||||
if (!hasCredential) {
|
||||
this.options_.credential = credential_internal_1.getApplicationDefault(this.options_.httpAgent);
|
||||
}
|
||||
var credential = this.options_.credential;
|
||||
if (typeof credential !== 'object' || credential === null || typeof credential.getAccessToken !== 'function') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Invalid Firebase app options passed as the first argument to initializeApp() for the ' +
|
||||
("app named \"" + this.name_ + "\". The \"credential\" property must be an object which implements ") +
|
||||
'the Credential interface.');
|
||||
}
|
||||
this.INTERNAL = new FirebaseAppInternals(credential);
|
||||
}
|
||||
Object.defineProperty(FirebaseApp.prototype, "name", {
|
||||
/**
|
||||
* Returns the name of the FirebaseApp instance.
|
||||
*
|
||||
* @returns The name of the FirebaseApp instance.
|
||||
*/
|
||||
get: function () {
|
||||
this.checkDestroyed_();
|
||||
return this.name_;
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseApp.prototype, "options", {
|
||||
/**
|
||||
* Returns the options for the FirebaseApp instance.
|
||||
*
|
||||
* @returns The options for the FirebaseApp instance.
|
||||
*/
|
||||
get: function () {
|
||||
this.checkDestroyed_();
|
||||
return deep_copy_1.deepCopy(this.options_);
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
FirebaseApp.prototype.getOrInitService = function (name, init) {
|
||||
var _this = this;
|
||||
return this.ensureService_(name, function () { return init(_this); });
|
||||
};
|
||||
/**
|
||||
* Deletes the FirebaseApp instance.
|
||||
*
|
||||
* @returns An empty Promise fulfilled once the FirebaseApp instance is deleted.
|
||||
*/
|
||||
FirebaseApp.prototype.delete = function () {
|
||||
var _this = this;
|
||||
var _a;
|
||||
this.checkDestroyed_();
|
||||
// Also remove the instance from the AppStore. This is needed to support the existing
|
||||
// app.delete() use case. In the future we can remove this API, and deleteApp() will
|
||||
// become the only way to tear down an App.
|
||||
(_a = this.appStore) === null || _a === void 0 ? void 0 : _a.removeApp(this.name);
|
||||
return Promise.all(Object.keys(this.services_).map(function (serviceName) {
|
||||
var service = _this.services_[serviceName];
|
||||
if (isStateful(service)) {
|
||||
return service.delete();
|
||||
}
|
||||
return Promise.resolve();
|
||||
})).then(function () {
|
||||
_this.services_ = {};
|
||||
_this.isDeleted_ = true;
|
||||
});
|
||||
};
|
||||
FirebaseApp.prototype.ensureService_ = function (serviceName, initializer) {
|
||||
this.checkDestroyed_();
|
||||
if (!(serviceName in this.services_)) {
|
||||
this.services_[serviceName] = initializer();
|
||||
}
|
||||
return this.services_[serviceName];
|
||||
};
|
||||
/**
|
||||
* Throws an Error if the FirebaseApp instance has already been deleted.
|
||||
*/
|
||||
FirebaseApp.prototype.checkDestroyed_ = function () {
|
||||
if (this.isDeleted_) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.APP_DELETED, "Firebase app named \"" + this.name_ + "\" has already been deleted.");
|
||||
}
|
||||
};
|
||||
return FirebaseApp;
|
||||
}());
|
||||
exports.FirebaseApp = FirebaseApp;
|
||||
function isStateful(service) {
|
||||
return typeof service.delete === 'function';
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { AppStore } from './lifecycle';
|
||||
import { app, appCheck, auth, messaging, machineLearning, storage, firestore, database, instanceId, installations, projectManagement, securityRules, remoteConfig, AppOptions } from '../firebase-namespace-api';
|
||||
import { cert, refreshToken, applicationDefault } from './credential-factory';
|
||||
import App = app.App;
|
||||
import AppCheck = appCheck.AppCheck;
|
||||
import Auth = auth.Auth;
|
||||
import Database = database.Database;
|
||||
import Firestore = firestore.Firestore;
|
||||
import Installations = installations.Installations;
|
||||
import InstanceId = instanceId.InstanceId;
|
||||
import MachineLearning = machineLearning.MachineLearning;
|
||||
import Messaging = messaging.Messaging;
|
||||
import ProjectManagement = projectManagement.ProjectManagement;
|
||||
import RemoteConfig = remoteConfig.RemoteConfig;
|
||||
import SecurityRules = securityRules.SecurityRules;
|
||||
import Storage = storage.Storage;
|
||||
export interface FirebaseServiceNamespace<T> {
|
||||
(app?: App): T;
|
||||
[key: string]: any;
|
||||
}
|
||||
/**
|
||||
* Internals of a FirebaseNamespace instance.
|
||||
*/
|
||||
export declare class FirebaseNamespaceInternals {
|
||||
private readonly appStore;
|
||||
constructor(appStore: AppStore);
|
||||
/**
|
||||
* Initializes the App instance.
|
||||
*
|
||||
* @param options - Optional options for the App instance. If none present will try to initialize
|
||||
* from the FIREBASE_CONFIG environment variable. If the environment variable contains a string
|
||||
* that starts with '{' it will be parsed as JSON, otherwise it will be assumed to be pointing
|
||||
* to a file.
|
||||
* @param appName - Optional name of the FirebaseApp instance.
|
||||
*
|
||||
* @returns A new App instance.
|
||||
*/
|
||||
initializeApp(options?: AppOptions, appName?: string): App;
|
||||
/**
|
||||
* Returns the App instance with the provided name (or the default App instance
|
||||
* if no name is provided).
|
||||
*
|
||||
* @param appName - Optional name of the FirebaseApp instance to return.
|
||||
* @returns The App instance which has the provided name.
|
||||
*/
|
||||
app(appName?: string): App;
|
||||
get apps(): App[];
|
||||
}
|
||||
/**
|
||||
* Global Firebase context object.
|
||||
*/
|
||||
export declare class FirebaseNamespace {
|
||||
__esModule: boolean;
|
||||
credential: {
|
||||
cert: typeof cert;
|
||||
refreshToken: typeof refreshToken;
|
||||
applicationDefault: typeof applicationDefault;
|
||||
};
|
||||
SDK_VERSION: string;
|
||||
INTERNAL: FirebaseNamespaceInternals;
|
||||
Promise: any;
|
||||
constructor(appStore?: AppStore);
|
||||
/**
|
||||
* Gets the `Auth` service namespace. The returned namespace can be used to get the
|
||||
* `Auth` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get auth(): FirebaseServiceNamespace<Auth>;
|
||||
/**
|
||||
* Gets the `Database` service namespace. The returned namespace can be used to get the
|
||||
* `Database` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get database(): FirebaseServiceNamespace<Database>;
|
||||
/**
|
||||
* Gets the `Messaging` service namespace. The returned namespace can be used to get the
|
||||
* `Messaging` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get messaging(): FirebaseServiceNamespace<Messaging>;
|
||||
/**
|
||||
* Gets the `Storage` service namespace. The returned namespace can be used to get the
|
||||
* `Storage` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get storage(): FirebaseServiceNamespace<Storage>;
|
||||
/**
|
||||
* Gets the `Firestore` service namespace. The returned namespace can be used to get the
|
||||
* `Firestore` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get firestore(): FirebaseServiceNamespace<Firestore>;
|
||||
/**
|
||||
* Gets the `MachineLearning` service namespace. The returned namespace can be
|
||||
* used to get the `MachineLearning` service for the default app or an
|
||||
* explicityly specified app.
|
||||
*/
|
||||
get machineLearning(): FirebaseServiceNamespace<MachineLearning>;
|
||||
/**
|
||||
* Gets the `Installations` service namespace. The returned namespace can be used to get the
|
||||
* `Installations` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get installations(): FirebaseServiceNamespace<Installations>;
|
||||
/**
|
||||
* Gets the `InstanceId` service namespace. The returned namespace can be used to get the
|
||||
* `Instance` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get instanceId(): FirebaseServiceNamespace<InstanceId>;
|
||||
/**
|
||||
* Gets the `ProjectManagement` service namespace. The returned namespace can be used to get the
|
||||
* `ProjectManagement` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get projectManagement(): FirebaseServiceNamespace<ProjectManagement>;
|
||||
/**
|
||||
* Gets the `SecurityRules` service namespace. The returned namespace can be used to get the
|
||||
* `SecurityRules` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get securityRules(): FirebaseServiceNamespace<SecurityRules>;
|
||||
/**
|
||||
* Gets the `RemoteConfig` service namespace. The returned namespace can be used to get the
|
||||
* `RemoteConfig` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get remoteConfig(): FirebaseServiceNamespace<RemoteConfig>;
|
||||
/**
|
||||
* Gets the `AppCheck` service namespace. The returned namespace can be used to get the
|
||||
* `AppCheck` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get appCheck(): FirebaseServiceNamespace<AppCheck>;
|
||||
/**
|
||||
* Initializes the FirebaseApp instance.
|
||||
*
|
||||
* @param options - Optional options for the FirebaseApp instance.
|
||||
* If none present will try to initialize from the FIREBASE_CONFIG environment variable.
|
||||
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
|
||||
* otherwise it will be assumed to be pointing to a file.
|
||||
* @param appName - Optional name of the FirebaseApp instance.
|
||||
*
|
||||
* @returns A new FirebaseApp instance.
|
||||
*/
|
||||
initializeApp(options?: AppOptions, appName?: string): App;
|
||||
/**
|
||||
* Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance
|
||||
* if no name is provided).
|
||||
*
|
||||
* @param appName - Optional name of the FirebaseApp instance to return.
|
||||
* @returns The FirebaseApp instance which has the provided name.
|
||||
*/
|
||||
app(appName?: string): App;
|
||||
get apps(): App[];
|
||||
private ensureApp;
|
||||
}
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.defaultNamespace = exports.FirebaseNamespace = exports.FirebaseNamespaceInternals = void 0;
|
||||
var lifecycle_1 = require("./lifecycle");
|
||||
var credential_factory_1 = require("./credential-factory");
|
||||
var index_1 = require("../utils/index");
|
||||
/**
|
||||
* Internals of a FirebaseNamespace instance.
|
||||
*/
|
||||
var FirebaseNamespaceInternals = /** @class */ (function () {
|
||||
function FirebaseNamespaceInternals(appStore) {
|
||||
this.appStore = appStore;
|
||||
}
|
||||
/**
|
||||
* Initializes the App instance.
|
||||
*
|
||||
* @param options - Optional options for the App instance. If none present will try to initialize
|
||||
* from the FIREBASE_CONFIG environment variable. If the environment variable contains a string
|
||||
* that starts with '{' it will be parsed as JSON, otherwise it will be assumed to be pointing
|
||||
* to a file.
|
||||
* @param appName - Optional name of the FirebaseApp instance.
|
||||
*
|
||||
* @returns A new App instance.
|
||||
*/
|
||||
FirebaseNamespaceInternals.prototype.initializeApp = function (options, appName) {
|
||||
var app = this.appStore.initializeApp(options, appName);
|
||||
return extendApp(app);
|
||||
};
|
||||
/**
|
||||
* Returns the App instance with the provided name (or the default App instance
|
||||
* if no name is provided).
|
||||
*
|
||||
* @param appName - Optional name of the FirebaseApp instance to return.
|
||||
* @returns The App instance which has the provided name.
|
||||
*/
|
||||
FirebaseNamespaceInternals.prototype.app = function (appName) {
|
||||
var app = this.appStore.getApp(appName);
|
||||
return extendApp(app);
|
||||
};
|
||||
Object.defineProperty(FirebaseNamespaceInternals.prototype, "apps", {
|
||||
/*
|
||||
* Returns an array of all the non-deleted App instances.
|
||||
*/
|
||||
get: function () {
|
||||
return this.appStore.getApps().map(function (app) { return extendApp(app); });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
return FirebaseNamespaceInternals;
|
||||
}());
|
||||
exports.FirebaseNamespaceInternals = FirebaseNamespaceInternals;
|
||||
var firebaseCredential = {
|
||||
cert: credential_factory_1.cert, refreshToken: credential_factory_1.refreshToken, applicationDefault: credential_factory_1.applicationDefault
|
||||
};
|
||||
/**
|
||||
* Global Firebase context object.
|
||||
*/
|
||||
var FirebaseNamespace = /** @class */ (function () {
|
||||
/* tslint:enable */
|
||||
function FirebaseNamespace(appStore) {
|
||||
// Hack to prevent Babel from modifying the object returned as the default admin namespace.
|
||||
/* tslint:disable:variable-name */
|
||||
this.__esModule = true;
|
||||
/* tslint:enable:variable-name */
|
||||
this.credential = firebaseCredential;
|
||||
this.SDK_VERSION = index_1.getSdkVersion();
|
||||
/* tslint:disable */
|
||||
// TODO(jwenger): Database is the only consumer of firebase.Promise. We should update it to use
|
||||
// use the native Promise and then remove this.
|
||||
this.Promise = Promise;
|
||||
this.INTERNAL = new FirebaseNamespaceInternals(appStore !== null && appStore !== void 0 ? appStore : new lifecycle_1.AppStore());
|
||||
}
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "auth", {
|
||||
/**
|
||||
* Gets the `Auth` service namespace. The returned namespace can be used to get the
|
||||
* `Auth` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).auth();
|
||||
};
|
||||
var auth = require('../auth/auth').Auth;
|
||||
return Object.assign(fn, { Auth: auth });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "database", {
|
||||
/**
|
||||
* Gets the `Database` service namespace. The returned namespace can be used to get the
|
||||
* `Database` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).database();
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return Object.assign(fn, require('@firebase/database-compat/standalone'));
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "messaging", {
|
||||
/**
|
||||
* Gets the `Messaging` service namespace. The returned namespace can be used to get the
|
||||
* `Messaging` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).messaging();
|
||||
};
|
||||
var messaging = require('../messaging/messaging').Messaging;
|
||||
return Object.assign(fn, { Messaging: messaging });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "storage", {
|
||||
/**
|
||||
* Gets the `Storage` service namespace. The returned namespace can be used to get the
|
||||
* `Storage` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).storage();
|
||||
};
|
||||
var storage = require('../storage/storage').Storage;
|
||||
return Object.assign(fn, { Storage: storage });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "firestore", {
|
||||
/**
|
||||
* Gets the `Firestore` service namespace. The returned namespace can be used to get the
|
||||
* `Firestore` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).firestore();
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
var firestore = require('@google-cloud/firestore');
|
||||
fn = Object.assign(fn, firestore.Firestore);
|
||||
// `v1beta1` and `v1` are lazy-loaded in the Firestore SDK. We use the same trick here
|
||||
// to avoid triggering this lazy-loading upon initialization.
|
||||
Object.defineProperty(fn, 'v1beta1', {
|
||||
get: function () {
|
||||
return firestore.v1beta1;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(fn, 'v1', {
|
||||
get: function () {
|
||||
return firestore.v1;
|
||||
},
|
||||
});
|
||||
return fn;
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "machineLearning", {
|
||||
/**
|
||||
* Gets the `MachineLearning` service namespace. The returned namespace can be
|
||||
* used to get the `MachineLearning` service for the default app or an
|
||||
* explicityly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).machineLearning();
|
||||
};
|
||||
var machineLearning = require('../machine-learning/machine-learning').MachineLearning;
|
||||
return Object.assign(fn, { MachineLearning: machineLearning });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "installations", {
|
||||
/**
|
||||
* Gets the `Installations` service namespace. The returned namespace can be used to get the
|
||||
* `Installations` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).installations();
|
||||
};
|
||||
var installations = require('../installations/installations').Installations;
|
||||
return Object.assign(fn, { Installations: installations });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "instanceId", {
|
||||
/**
|
||||
* Gets the `InstanceId` service namespace. The returned namespace can be used to get the
|
||||
* `Instance` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).instanceId();
|
||||
};
|
||||
var instanceId = require('../instance-id/instance-id').InstanceId;
|
||||
return Object.assign(fn, { InstanceId: instanceId });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "projectManagement", {
|
||||
/**
|
||||
* Gets the `ProjectManagement` service namespace. The returned namespace can be used to get the
|
||||
* `ProjectManagement` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).projectManagement();
|
||||
};
|
||||
var projectManagement = require('../project-management/project-management').ProjectManagement;
|
||||
return Object.assign(fn, { ProjectManagement: projectManagement });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "securityRules", {
|
||||
/**
|
||||
* Gets the `SecurityRules` service namespace. The returned namespace can be used to get the
|
||||
* `SecurityRules` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).securityRules();
|
||||
};
|
||||
var securityRules = require('../security-rules/security-rules').SecurityRules;
|
||||
return Object.assign(fn, { SecurityRules: securityRules });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "remoteConfig", {
|
||||
/**
|
||||
* Gets the `RemoteConfig` service namespace. The returned namespace can be used to get the
|
||||
* `RemoteConfig` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).remoteConfig();
|
||||
};
|
||||
var remoteConfig = require('../remote-config/remote-config').RemoteConfig;
|
||||
return Object.assign(fn, { RemoteConfig: remoteConfig });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "appCheck", {
|
||||
/**
|
||||
* Gets the `AppCheck` service namespace. The returned namespace can be used to get the
|
||||
* `AppCheck` service for the default app or an explicitly specified app.
|
||||
*/
|
||||
get: function () {
|
||||
var _this = this;
|
||||
var fn = function (app) {
|
||||
return _this.ensureApp(app).appCheck();
|
||||
};
|
||||
var appCheck = require('../app-check/app-check').AppCheck;
|
||||
return Object.assign(fn, { AppCheck: appCheck });
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
// TODO: Change the return types to app.App in the following methods.
|
||||
/**
|
||||
* Initializes the FirebaseApp instance.
|
||||
*
|
||||
* @param options - Optional options for the FirebaseApp instance.
|
||||
* If none present will try to initialize from the FIREBASE_CONFIG environment variable.
|
||||
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
|
||||
* otherwise it will be assumed to be pointing to a file.
|
||||
* @param appName - Optional name of the FirebaseApp instance.
|
||||
*
|
||||
* @returns A new FirebaseApp instance.
|
||||
*/
|
||||
FirebaseNamespace.prototype.initializeApp = function (options, appName) {
|
||||
return this.INTERNAL.initializeApp(options, appName);
|
||||
};
|
||||
/**
|
||||
* Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance
|
||||
* if no name is provided).
|
||||
*
|
||||
* @param appName - Optional name of the FirebaseApp instance to return.
|
||||
* @returns The FirebaseApp instance which has the provided name.
|
||||
*/
|
||||
FirebaseNamespace.prototype.app = function (appName) {
|
||||
return this.INTERNAL.app(appName);
|
||||
};
|
||||
Object.defineProperty(FirebaseNamespace.prototype, "apps", {
|
||||
/*
|
||||
* Returns an array of all the non-deleted FirebaseApp instances.
|
||||
*/
|
||||
get: function () {
|
||||
return this.INTERNAL.apps;
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
FirebaseNamespace.prototype.ensureApp = function (app) {
|
||||
if (typeof app === 'undefined') {
|
||||
app = this.app();
|
||||
}
|
||||
return app;
|
||||
};
|
||||
return FirebaseNamespace;
|
||||
}());
|
||||
exports.FirebaseNamespace = FirebaseNamespace;
|
||||
/**
|
||||
* In order to maintain backward compatibility, we instantiate a default namespace instance in
|
||||
* this module, and delegate all app lifecycle operations to it. In a future implementation where
|
||||
* the old admin namespace is no longer supported, we should remove this.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
exports.defaultNamespace = new FirebaseNamespace(lifecycle_1.defaultAppStore);
|
||||
function extendApp(app) {
|
||||
var result = app;
|
||||
if (result.__extended) {
|
||||
return result;
|
||||
}
|
||||
result.auth = function () {
|
||||
var fn = require('../auth/index').getAuth;
|
||||
return fn(app);
|
||||
};
|
||||
result.appCheck = function () {
|
||||
var fn = require('../app-check/index').getAppCheck;
|
||||
return fn(app);
|
||||
};
|
||||
result.database = function (url) {
|
||||
var fn = require('../database/index').getDatabaseWithUrl;
|
||||
return fn(url, app);
|
||||
};
|
||||
result.messaging = function () {
|
||||
var fn = require('../messaging/index').getMessaging;
|
||||
return fn(app);
|
||||
};
|
||||
result.storage = function () {
|
||||
var fn = require('../storage/index').getStorage;
|
||||
return fn(app);
|
||||
};
|
||||
result.firestore = function () {
|
||||
var fn = require('../firestore/index').getFirestore;
|
||||
return fn(app);
|
||||
};
|
||||
result.instanceId = function () {
|
||||
var fn = require('../instance-id/index').getInstanceId;
|
||||
return fn(app);
|
||||
};
|
||||
result.installations = function () {
|
||||
var fn = require('../installations/index').getInstallations;
|
||||
return fn(app);
|
||||
};
|
||||
result.machineLearning = function () {
|
||||
var fn = require('../machine-learning/index').getMachineLearning;
|
||||
return fn(app);
|
||||
};
|
||||
result.projectManagement = function () {
|
||||
var fn = require('../project-management/index').getProjectManagement;
|
||||
return fn(app);
|
||||
};
|
||||
result.securityRules = function () {
|
||||
var fn = require('../security-rules/index').getSecurityRules;
|
||||
return fn(app);
|
||||
};
|
||||
result.remoteConfig = function () {
|
||||
var fn = require('../remote-config/index').getRemoteConfig;
|
||||
return fn(app);
|
||||
};
|
||||
result.__extended = true;
|
||||
return result;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
/**
|
||||
* Firebase App and SDK initialization.
|
||||
*
|
||||
* @packageDocumentation
|
||||
*/
|
||||
export { App, AppOptions, FirebaseArrayIndexError, FirebaseError } from './core';
|
||||
export { initializeApp, getApp, getApps, deleteApp } from './lifecycle';
|
||||
export { Credential, ServiceAccount, GoogleOAuthAccessToken } from './credential';
|
||||
export { applicationDefault, cert, refreshToken } from './credential-factory';
|
||||
export declare const SDK_VERSION: string;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SDK_VERSION = void 0;
|
||||
var utils_1 = require("../utils");
|
||||
var lifecycle_1 = require("./lifecycle");
|
||||
Object.defineProperty(exports, "initializeApp", { enumerable: true, get: function () { return lifecycle_1.initializeApp; } });
|
||||
Object.defineProperty(exports, "getApp", { enumerable: true, get: function () { return lifecycle_1.getApp; } });
|
||||
Object.defineProperty(exports, "getApps", { enumerable: true, get: function () { return lifecycle_1.getApps; } });
|
||||
Object.defineProperty(exports, "deleteApp", { enumerable: true, get: function () { return lifecycle_1.deleteApp; } });
|
||||
var credential_factory_1 = require("./credential-factory");
|
||||
Object.defineProperty(exports, "applicationDefault", { enumerable: true, get: function () { return credential_factory_1.applicationDefault; } });
|
||||
Object.defineProperty(exports, "cert", { enumerable: true, get: function () { return credential_factory_1.cert; } });
|
||||
Object.defineProperty(exports, "refreshToken", { enumerable: true, get: function () { return credential_factory_1.refreshToken; } });
|
||||
exports.SDK_VERSION = utils_1.getSdkVersion();
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { App, AppOptions } from './core';
|
||||
export declare class AppStore {
|
||||
private readonly appStore;
|
||||
initializeApp(options?: AppOptions, appName?: string): App;
|
||||
getApp(appName?: string): App;
|
||||
getApps(): App[];
|
||||
deleteApp(app: App): Promise<void>;
|
||||
clearAllApps(): Promise<void>;
|
||||
/**
|
||||
* Removes the specified App instance from the store. This is currently called by the
|
||||
* {@link FirebaseApp.delete} method. Can be removed once the app deletion is handled
|
||||
* entirely by the {@link deleteApp} top-level function.
|
||||
*/
|
||||
removeApp(appName: string): void;
|
||||
}
|
||||
export declare const defaultAppStore: AppStore;
|
||||
export declare function initializeApp(options?: AppOptions, appName?: string): App;
|
||||
export declare function getApp(appName?: string): App;
|
||||
export declare function getApps(): App[];
|
||||
/**
|
||||
* Renders this given `App` unusable and frees the resources of
|
||||
* all associated services (though it does *not* clean up any backend
|
||||
* resources). When running the SDK locally, this method
|
||||
* must be called to ensure graceful termination of the process.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* deleteApp(app)
|
||||
* .then(function() {
|
||||
* console.log("App deleted successfully");
|
||||
* })
|
||||
* .catch(function(error) {
|
||||
* console.log("Error deleting app:", error);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export declare function deleteApp(app: App): Promise<void>;
|
||||
/**
|
||||
* Constant holding the environment variable name with the default config.
|
||||
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
|
||||
* otherwise it will be assumed to be pointing to a file.
|
||||
*/
|
||||
export declare const FIREBASE_CONFIG_VAR = "FIREBASE_CONFIG";
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
/*! firebase-admin v10.0.1 */
|
||||
"use strict";
|
||||
/*!
|
||||
* @license
|
||||
* Copyright 2021 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FIREBASE_CONFIG_VAR = exports.deleteApp = exports.getApps = exports.getApp = exports.initializeApp = exports.defaultAppStore = exports.AppStore = void 0;
|
||||
var fs = require("fs");
|
||||
var validator = require("../utils/validator");
|
||||
var error_1 = require("../utils/error");
|
||||
var credential_internal_1 = require("./credential-internal");
|
||||
var firebase_app_1 = require("./firebase-app");
|
||||
var DEFAULT_APP_NAME = '[DEFAULT]';
|
||||
var AppStore = /** @class */ (function () {
|
||||
function AppStore() {
|
||||
this.appStore = new Map();
|
||||
}
|
||||
AppStore.prototype.initializeApp = function (options, appName) {
|
||||
if (appName === void 0) { appName = DEFAULT_APP_NAME; }
|
||||
if (typeof options === 'undefined') {
|
||||
options = loadOptionsFromEnvVar();
|
||||
options.credential = credential_internal_1.getApplicationDefault();
|
||||
}
|
||||
if (typeof appName !== 'string' || appName === '') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_NAME, "Invalid Firebase app name \"" + appName + "\" provided. App name must be a non-empty string.");
|
||||
}
|
||||
else if (this.appStore.has(appName)) {
|
||||
if (appName === DEFAULT_APP_NAME) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.DUPLICATE_APP, 'The default Firebase app already exists. This means you called initializeApp() ' +
|
||||
'more than once without providing an app name as the second argument. In most cases ' +
|
||||
'you only need to call initializeApp() once. But if you do want to initialize ' +
|
||||
'multiple apps, pass a second argument to initializeApp() to give each app a unique ' +
|
||||
'name.');
|
||||
}
|
||||
else {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.DUPLICATE_APP, "Firebase app named \"" + appName + "\" already exists. This means you called initializeApp() " +
|
||||
'more than once with the same app name as the second argument. Make sure you provide a ' +
|
||||
'unique name every time you call initializeApp().');
|
||||
}
|
||||
}
|
||||
var app = new firebase_app_1.FirebaseApp(options, appName, this);
|
||||
this.appStore.set(app.name, app);
|
||||
return app;
|
||||
};
|
||||
AppStore.prototype.getApp = function (appName) {
|
||||
if (appName === void 0) { appName = DEFAULT_APP_NAME; }
|
||||
if (typeof appName !== 'string' || appName === '') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_NAME, "Invalid Firebase app name \"" + appName + "\" provided. App name must be a non-empty string.");
|
||||
}
|
||||
else if (!this.appStore.has(appName)) {
|
||||
var errorMessage = (appName === DEFAULT_APP_NAME)
|
||||
? 'The default Firebase app does not exist. ' : "Firebase app named \"" + appName + "\" does not exist. ";
|
||||
errorMessage += 'Make sure you call initializeApp() before using any of the Firebase services.';
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NO_APP, errorMessage);
|
||||
}
|
||||
return this.appStore.get(appName);
|
||||
};
|
||||
AppStore.prototype.getApps = function () {
|
||||
// Return a copy so the caller cannot mutate the array
|
||||
return Array.from(this.appStore.values());
|
||||
};
|
||||
AppStore.prototype.deleteApp = function (app) {
|
||||
if (typeof app !== 'object' || app === null || !('options' in app)) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'Invalid app argument.');
|
||||
}
|
||||
// Make sure the given app already exists.
|
||||
var existingApp = getApp(app.name);
|
||||
// Delegate delete operation to the App instance itself. That will also remove the App
|
||||
// instance from the AppStore.
|
||||
return existingApp.delete();
|
||||
};
|
||||
AppStore.prototype.clearAllApps = function () {
|
||||
var _this = this;
|
||||
var promises = [];
|
||||
this.getApps().forEach(function (app) {
|
||||
promises.push(_this.deleteApp(app));
|
||||
});
|
||||
return Promise.all(promises).then();
|
||||
};
|
||||
/**
|
||||
* Removes the specified App instance from the store. This is currently called by the
|
||||
* {@link FirebaseApp.delete} method. Can be removed once the app deletion is handled
|
||||
* entirely by the {@link deleteApp} top-level function.
|
||||
*/
|
||||
AppStore.prototype.removeApp = function (appName) {
|
||||
this.appStore.delete(appName);
|
||||
};
|
||||
return AppStore;
|
||||
}());
|
||||
exports.AppStore = AppStore;
|
||||
exports.defaultAppStore = new AppStore();
|
||||
function initializeApp(options, appName) {
|
||||
if (appName === void 0) { appName = DEFAULT_APP_NAME; }
|
||||
return exports.defaultAppStore.initializeApp(options, appName);
|
||||
}
|
||||
exports.initializeApp = initializeApp;
|
||||
function getApp(appName) {
|
||||
if (appName === void 0) { appName = DEFAULT_APP_NAME; }
|
||||
return exports.defaultAppStore.getApp(appName);
|
||||
}
|
||||
exports.getApp = getApp;
|
||||
function getApps() {
|
||||
return exports.defaultAppStore.getApps();
|
||||
}
|
||||
exports.getApps = getApps;
|
||||
/**
|
||||
* Renders this given `App` unusable and frees the resources of
|
||||
* all associated services (though it does *not* clean up any backend
|
||||
* resources). When running the SDK locally, this method
|
||||
* must be called to ensure graceful termination of the process.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* deleteApp(app)
|
||||
* .then(function() {
|
||||
* console.log("App deleted successfully");
|
||||
* })
|
||||
* .catch(function(error) {
|
||||
* console.log("Error deleting app:", error);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
function deleteApp(app) {
|
||||
return exports.defaultAppStore.deleteApp(app);
|
||||
}
|
||||
exports.deleteApp = deleteApp;
|
||||
/**
|
||||
* Constant holding the environment variable name with the default config.
|
||||
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
|
||||
* otherwise it will be assumed to be pointing to a file.
|
||||
*/
|
||||
exports.FIREBASE_CONFIG_VAR = 'FIREBASE_CONFIG';
|
||||
/**
|
||||
* Parse the file pointed to by the FIREBASE_CONFIG_VAR, if it exists.
|
||||
* Or if the FIREBASE_CONFIG_ENV contains a valid JSON object, parse it directly.
|
||||
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
|
||||
* otherwise it will be assumed to be pointing to a file.
|
||||
*/
|
||||
function loadOptionsFromEnvVar() {
|
||||
var config = process.env[exports.FIREBASE_CONFIG_VAR];
|
||||
if (!validator.isNonEmptyString(config)) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
var contents = config.startsWith('{') ? config : fs.readFileSync(config, 'utf8');
|
||||
return JSON.parse(contents);
|
||||
}
|
||||
catch (error) {
|
||||
// Throw a nicely formed error message if the file contents cannot be parsed
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Failed to parse app options file: ' + error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user