UNPKG

39.9 kBSource Map (JSON)View Raw
1{"version":3,"file":"firebase-functions.js","sources":["../../node_modules/tslib/tslib.es6.js","../functions/src/api/error.ts","../functions/src/context.ts","../functions/src/serializer.ts","../functions/src/api/service.ts","../functions/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HttpsError, FunctionsErrorCode } from '@firebase/functions-types';\nimport { Serializer } from '../serializer';\nimport { HttpResponseBody } from './service';\n\n/**\n * Standard error codes for different ways a request can fail, as defined by:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * This map is used primarily to convert from a backend error code string to\n * a client SDK error code string, and make sure it's in the supported set.\n */\nconst errorCodeMap: { [name: string]: FunctionsErrorCode } = {\n OK: 'ok',\n CANCELLED: 'cancelled',\n UNKNOWN: 'unknown',\n INVALID_ARGUMENT: 'invalid-argument',\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n NOT_FOUND: 'not-found',\n ALREADY_EXISTS: 'already-exists',\n PERMISSION_DENIED: 'permission-denied',\n UNAUTHENTICATED: 'unauthenticated',\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n FAILED_PRECONDITION: 'failed-precondition',\n ABORTED: 'aborted',\n OUT_OF_RANGE: 'out-of-range',\n UNIMPLEMENTED: 'unimplemented',\n INTERNAL: 'internal',\n UNAVAILABLE: 'unavailable',\n DATA_LOSS: 'data-loss'\n};\n\n/**\n * An explicit error that can be thrown from a handler to send an error to the\n * client that called the function.\n */\nexport class HttpsErrorImpl extends Error implements HttpsError {\n /**\n * A standard error code that will be returned to the client. This also\n * determines the HTTP status code of the response, as defined in code.proto.\n */\n readonly code: FunctionsErrorCode;\n\n /**\n * Extra data to be converted to JSON and included in the error response.\n */\n readonly details?: unknown;\n\n constructor(code: FunctionsErrorCode, message?: string, details?: unknown) {\n super(message);\n\n // This is a workaround for a bug in TypeScript when extending Error:\n // tslint:disable-next-line\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, HttpsErrorImpl.prototype);\n\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Takes an HTTP status code and returns the corresponding ErrorCode.\n * This is the standard HTTP status code -> error mapping defined in:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * @param status An HTTP status code.\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\n */\nfunction codeForHTTPStatus(status: number): FunctionsErrorCode {\n // Make sure any successful status is OK.\n if (status >= 200 && status < 300) {\n return 'ok';\n }\n switch (status) {\n case 0:\n // This can happen if the server returns 500.\n return 'internal';\n case 400:\n return 'invalid-argument';\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission-denied';\n case 404:\n return 'not-found';\n case 409:\n return 'aborted';\n case 429:\n return 'resource-exhausted';\n case 499:\n return 'cancelled';\n case 500:\n return 'internal';\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline-exceeded';\n default: // ignore\n }\n return 'unknown';\n}\n\n/**\n * Takes an HTTP response and returns the corresponding Error, if any.\n */\nexport function _errorForResponse(\n status: number,\n bodyJSON: HttpResponseBody | null,\n serializer: Serializer\n): Error | null {\n let code = codeForHTTPStatus(status);\n\n // Start with reasonable defaults from the status code.\n let description: string = code;\n\n let details: unknown = undefined;\n\n // Then look through the body for explicit details.\n try {\n const errorJSON = bodyJSON && bodyJSON.error;\n if (errorJSON) {\n const status = errorJSON.status;\n if (typeof status === 'string') {\n if (!errorCodeMap[status]) {\n // They must've included an unknown error code in the body.\n return new HttpsErrorImpl('internal', 'internal');\n }\n code = errorCodeMap[status];\n\n // TODO(klimt): Add better default descriptions for error enums.\n // The default description needs to be updated for the new code.\n description = status;\n }\n\n const message = errorJSON.message;\n if (typeof message === 'string') {\n description = message;\n }\n\n details = errorJSON.details;\n if (details !== undefined) {\n details = serializer.decode(details as {} | null);\n }\n }\n } catch (e) {\n // If we couldn't parse explicit error data, that's fine.\n }\n\n if (code === 'ok') {\n // Technically, there's an edge case where a developer could explicitly\n // return an error code of OK, and we will treat it as success, but that\n // seems reasonable.\n return null;\n }\n\n return new HttpsErrorImpl(code, description, details);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirebaseApp } from '@firebase/app-types';\nimport { _FirebaseApp } from '@firebase/app-types/private';\nimport { FirebaseMessaging } from '@firebase/messaging-types';\n\n/**\n * The metadata that should be supplied with function calls.\n */\nexport interface Context {\n authToken?: string;\n instanceIdToken?: string;\n}\n\n/**\n * Helper class to get metadata that should be included with a function call.\n */\nexport class ContextProvider {\n constructor(private readonly app: FirebaseApp) {}\n\n async getAuthToken(): Promise<string | undefined> {\n try {\n const token = await (this.app as _FirebaseApp).INTERNAL.getToken();\n if (!token) {\n return undefined;\n }\n return token.accessToken;\n } catch (e) {\n // If there's any error when trying to get the auth token, leave it off.\n return undefined;\n }\n }\n\n async getInstanceIdToken(): Promise<string | undefined> {\n try {\n // HACK: Until we have a separate instanceId package, this is a quick way\n // to load in the messaging instance for this app.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (!(this.app as any).messaging) {\n return undefined;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const messaging = (this.app as any).messaging() as FirebaseMessaging;\n const token = await messaging.getToken();\n if (!token) {\n return undefined;\n }\n return token;\n } catch (e) {\n // We don't warn on this, because it usually means messaging isn't set up.\n // console.warn('Failed to retrieve instance id token.', e);\n\n // If there's any error when trying to get the token, leave it off.\n return undefined;\n }\n }\n\n async getContext(): Promise<Context> {\n const authToken = await this.getAuthToken();\n const instanceIdToken = await this.getInstanceIdToken();\n return { authToken, instanceIdToken };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\nconst UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\n\nfunction mapValues(\n // { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n o: { [key: string]: any },\n f: (arg0: unknown) => unknown\n): object {\n const result: { [key: string]: unknown } = {};\n for (const key in o) {\n if (o.hasOwnProperty(key)) {\n result[key] = f(o[key]);\n }\n }\n return result;\n}\n\nexport class Serializer {\n // Takes data and encodes it in a JSON-friendly way, such that types such as\n // Date are preserved.\n encode(data: unknown): unknown {\n if (data == null) {\n return null;\n }\n if (data instanceof Number) {\n data = data.valueOf();\n }\n if (typeof data === 'number' && isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n if (data === true || data === false) {\n return data;\n }\n if (Object.prototype.toString.call(data) === '[object String]') {\n return data;\n }\n if (Array.isArray(data)) {\n return data.map(x => this.encode(x));\n }\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data as object, x => this.encode(x));\n }\n // If we got this far, the data is not encodable.\n throw new Error('Data cannot be encoded in JSON: ' + data);\n }\n\n // Takes data that's been encoded in a JSON-friendly form and returns a form\n // with richer datatypes, such as Dates, etc.\n decode(json: unknown): unknown {\n if (json == null) {\n return json;\n }\n if ((json as { [key: string]: unknown })['@type']) {\n switch ((json as { [key: string]: unknown })['@type']) {\n case LONG_TYPE:\n // Fall through and handle this the same as unsigned.\n case UNSIGNED_LONG_TYPE: {\n // Technically, this could work return a valid number for malformed\n // data if there was a number followed by garbage. But it's just not\n // worth all the extra code to detect that case.\n const value = Number((json as { [key: string]: unknown })['value']);\n if (isNaN(value)) {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n return value;\n }\n default: {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n }\n }\n if (Array.isArray(json)) {\n return json.map(x => this.decode(x));\n }\n if (typeof json === 'function' || typeof json === 'object') {\n return mapValues(json as object, x => this.decode(x as {} | null));\n }\n // Anything else is safe to return.\n return json;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n FirebaseFunctions,\n HttpsCallable,\n HttpsCallableResult,\n HttpsCallableOptions\n} from '@firebase/functions-types';\nimport { _errorForResponse, HttpsErrorImpl } from './error';\nimport { ContextProvider } from '../context';\nimport { Serializer } from '../serializer';\n\n/**\n * The response to an http request.\n */\ninterface HttpResponse {\n status: number;\n json: HttpResponseBody | null;\n}\n/**\n * Describes the shape of the HttpResponse body.\n * It makes functions that would otherwise take {} able to access the\n * possible elements in the body more easily\n */\nexport interface HttpResponseBody {\n data?: unknown;\n result?: unknown;\n error?: {\n message?: unknown;\n status?: unknown;\n details?: unknown;\n };\n}\n\n/**\n * Returns a Promise that will be rejected after the given duration.\n * The error will be of type HttpsErrorImpl.\n *\n * @param millis Number of milliseconds to wait before rejecting.\n */\nfunction failAfter(millis: number): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => {\n reject(new HttpsErrorImpl('deadline-exceeded', 'deadline-exceeded'));\n }, millis);\n });\n}\n\n/**\n * The main class for the Firebase Functions SDK.\n */\nexport class Service implements FirebaseFunctions, FirebaseService {\n private readonly contextProvider: ContextProvider;\n private readonly serializer = new Serializer();\n private emulatorOrigin: string | null = null;\n private cancelAllRequests: Promise<void>;\n private deleteService!: Function;\n\n /**\n * Creates a new Functions service for the given app and (optional) region.\n * @param app_ The FirebaseApp to use.\n * @param region_ The region to call functions in.\n */\n constructor(\n private app_: FirebaseApp,\n private region_: string = 'us-central1'\n ) {\n this.contextProvider = new ContextProvider(app_);\n // Cancels all ongoing requests when resolved.\n this.cancelAllRequests = new Promise(resolve => {\n this.deleteService = () => {\n return resolve();\n };\n });\n }\n\n get app(): FirebaseApp {\n return this.app_;\n }\n\n INTERNAL = {\n delete: (): Promise<void> => {\n return this.deleteService();\n }\n };\n\n /**\n * Returns the URL for a callable with the given name.\n * @param name The name of the callable.\n */\n _url(name: string): string {\n const projectId = this.app_.options.projectId;\n const region = this.region_;\n if (this.emulatorOrigin !== null) {\n const origin = this.emulatorOrigin;\n return `${origin}/${projectId}/${region}/${name}`;\n }\n return `https://${region}-${projectId}.cloudfunctions.net/${name}`;\n }\n\n /**\n * Changes this instance to point to a Cloud Functions emulator running\n * locally. See https://firebase.google.com/docs/functions/local-emulator\n *\n * @param origin The origin of the local emulator, such as\n * \"http://localhost:5005\".\n */\n useFunctionsEmulator(origin: string): void {\n this.emulatorOrigin = origin;\n }\n\n /**\n * Returns a reference to the callable https trigger with the given name.\n * @param name The name of the trigger.\n */\n httpsCallable(name: string, options?: HttpsCallableOptions): HttpsCallable {\n return data => {\n return this.call(name, data, options || {});\n };\n }\n\n /**\n * Does an HTTP POST and returns the completed response.\n * @param url The url to post to.\n * @param body The JSON body of the post.\n * @param headers The HTTP headers to include in the request.\n * @return A Promise that will succeed when the request finishes.\n */\n private async postJSON(\n url: string,\n body: {},\n headers: Headers\n ): Promise<HttpResponse> {\n headers.append('Content-Type', 'application/json');\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers\n });\n } catch (e) {\n // This could be an unhandled error on the backend, or it could be a\n // network error. There's no way to know, since an unhandled error on the\n // backend will fail to set the proper CORS header, and thus will be\n // treated as a network error by fetch.\n return {\n status: 0,\n json: null\n };\n }\n let json: {} | null = null;\n try {\n json = await response.json();\n } catch (e) {\n // If we fail to parse JSON, it will fail the same as an empty body.\n }\n return {\n status: response.status,\n json\n };\n }\n\n /**\n * Calls a callable function asynchronously and returns the result.\n * @param name The name of the callable trigger.\n * @param data The data to pass as params to the function.s\n */\n private async call(\n name: string,\n data: unknown,\n options: HttpsCallableOptions\n ): Promise<HttpsCallableResult> {\n const url = this._url(name);\n\n // Encode any special types, such as dates, in the input data.\n data = this.serializer.encode(data);\n const body = { data };\n\n // Add a header for the authToken.\n const headers = new Headers();\n const context = await this.contextProvider.getContext();\n if (context.authToken) {\n headers.append('Authorization', 'Bearer ' + context.authToken);\n }\n if (context.instanceIdToken) {\n headers.append('Firebase-Instance-ID-Token', context.instanceIdToken);\n }\n\n // Default timeout to 70s, but let the options override it.\n const timeout = options.timeout || 70000;\n\n const response = await Promise.race([\n this.postJSON(url, body, headers),\n failAfter(timeout),\n this.cancelAllRequests\n ]);\n\n // If service was deleted, interrupted response throws an error.\n if (!response) {\n throw new HttpsErrorImpl(\n 'cancelled',\n 'Firebase Functions instance was deleted.'\n );\n }\n\n // Check for an error status, regardless of http status.\n const error = _errorForResponse(\n response.status,\n response.json,\n this.serializer\n );\n if (error) {\n throw error;\n }\n\n if (!response.json) {\n throw new HttpsErrorImpl(\n 'internal',\n 'Response is not valid JSON object.'\n );\n }\n\n let responseData = response.json.data;\n // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\n // backwards compatibility.\n if (typeof responseData === 'undefined') {\n responseData = response.json.result;\n }\n if (typeof responseData === 'undefined') {\n // Consider the response malformed.\n throw new HttpsErrorImpl('internal', 'Response is missing data field.');\n }\n\n // Decode any special types, such as dates, in the returned data.\n const decodedData = this.serializer.decode(responseData as {} | null);\n\n return { data: decodedData };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport firebase from '@firebase/app';\nimport * as appTypes from '@firebase/app-types';\nimport {\n FirebaseServiceFactory,\n _FirebaseNamespace\n} from '@firebase/app-types/private';\nimport * as types from '@firebase/functions-types';\nimport { Service } from './src/api/service';\n\n/**\n * Type constant for Firebase Functions.\n */\nconst FUNCTIONS_TYPE = 'functions';\n\nfunction factory(\n app: appTypes.FirebaseApp,\n _unused: unknown,\n region?: string\n): Service {\n return new Service(app, region);\n}\n\nexport function registerFunctions(instance: _FirebaseNamespace): void {\n const namespaceExports = {\n // no-inline\n Functions: Service\n };\n instance.INTERNAL.registerService(\n FUNCTIONS_TYPE,\n factory as FirebaseServiceFactory,\n namespaceExports,\n // We don't need to wait on any AppHooks.\n undefined,\n // Allow multiple functions instances per app.\n true\n );\n}\n\nregisterFunctions(firebase as _FirebaseNamespace);\n\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n functions?: {\n (app?: FirebaseApp): types.FirebaseFunctions;\n Functions: typeof types.FirebaseFunctions;\n };\n }\n interface FirebaseApp {\n functions?(region?: string): types.FirebaseFunctions;\n }\n}\n"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","__generator","body","f","y","t","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","this","n","v","op","TypeError","call","pop","length","push","errorCodeMap","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","UNAUTHENTICATED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","Error","prototype","create","__","constructor","code","message","details","_super","_this","HttpsErrorImpl","_errorForResponse","status","bodyJSON","serializer","codeForHTTPStatus","description","undefined","errorJSON","error","status_1","decode","ContextProvider","app","getToken","token","_a","accessToken","messaging","getAuthToken","authToken","getInstanceIdToken","instanceIdToken","mapValues","o","key","Serializer","data","Number","valueOf","isFinite","toString","isArray","map","x","encode","json","isNaN","Service","app_","name","projectId","options","region","region_","emulatorOrigin","origin","url","headers","append","fetch","method","JSON","stringify","response","_url","Headers","contextProvider","getContext","context","timeout","race","postJSON","millis","setTimeout","failAfter","cancelAllRequests","responseData","delete","deleteService","namespaceExports","factory","_unused","Functions","firebase","registerService"],"mappings":"sRAgBA,IAAIA,EAAgB,SAASC,EAAGC,GAI5B,OAHAF,EAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAgBC,OAAS,SAAUL,EAAGC,GAAKD,EAAEI,UAAYH,IACvE,SAAUD,EAAGC,GAAK,IAAK,IAAIK,KAAKL,EAAOA,EAAEM,eAAeD,KAAIN,EAAEM,GAAKL,EAAEK,MACpDN,EAAGC,IA+CrB,SAASO,EAAUC,EAASC,EAAYC,EAAGC,GAC9C,OAAO,IAAWD,EAANA,GAAUE,SAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,IAAW,MAAOG,GAAKL,EAAOK,IACpF,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,IAAW,MAAOG,GAAKL,EAAOK,IACvF,SAASF,EAAKI,GAAUA,EAAOC,KAAOT,EAAQQ,EAAOL,OAAS,IAAIN,EAAE,SAAUG,GAAWA,EAAQQ,EAAOL,SAAWO,KAAKR,EAAWK,GACnIH,GAAMN,EAAYA,EAAUa,MAAMhB,EAASC,GAAc,KAAKS,UAI/D,SAASO,EAAYjB,EAASkB,GACjC,IAAsGC,EAAGC,EAAGC,EAAGC,EAA3GC,EAAI,CAAEC,MAAO,EAAGC,KAAM,WAAa,GAAW,EAAPJ,EAAE,GAAQ,MAAMA,EAAE,GAAI,OAAOA,EAAE,IAAOK,KAAM,GAAIC,IAAK,IA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