No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.esm.js 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. import { _registerComponent, registerVersion, getApp, _getProvider } from '@firebase/app';
  2. import { __extends, __awaiter, __generator, __spreadArray } from 'tslib';
  3. import { FirebaseError, getModularInstance, getDefaultEmulatorHostnameAndPort } from '@firebase/util';
  4. import { Component } from '@firebase/component';
  5. /**
  6. * @license
  7. * Copyright 2017 Google LLC
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. var LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';
  22. var UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';
  23. function mapValues(
  24. // { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5
  25. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  26. o, f) {
  27. var result = {};
  28. for (var key in o) {
  29. if (o.hasOwnProperty(key)) {
  30. result[key] = f(o[key]);
  31. }
  32. }
  33. return result;
  34. }
  35. /**
  36. * Takes data and encodes it in a JSON-friendly way, such that types such as
  37. * Date are preserved.
  38. * @internal
  39. * @param data - Data to encode.
  40. */
  41. function encode(data) {
  42. if (data == null) {
  43. return null;
  44. }
  45. if (data instanceof Number) {
  46. data = data.valueOf();
  47. }
  48. if (typeof data === 'number' && isFinite(data)) {
  49. // Any number in JS is safe to put directly in JSON and parse as a double
  50. // without any loss of precision.
  51. return data;
  52. }
  53. if (data === true || data === false) {
  54. return data;
  55. }
  56. if (Object.prototype.toString.call(data) === '[object String]') {
  57. return data;
  58. }
  59. if (data instanceof Date) {
  60. return data.toISOString();
  61. }
  62. if (Array.isArray(data)) {
  63. return data.map(function (x) { return encode(x); });
  64. }
  65. if (typeof data === 'function' || typeof data === 'object') {
  66. return mapValues(data, function (x) { return encode(x); });
  67. }
  68. // If we got this far, the data is not encodable.
  69. throw new Error('Data cannot be encoded in JSON: ' + data);
  70. }
  71. /**
  72. * Takes data that's been encoded in a JSON-friendly form and returns a form
  73. * with richer datatypes, such as Dates, etc.
  74. * @internal
  75. * @param json - JSON to convert.
  76. */
  77. function decode(json) {
  78. if (json == null) {
  79. return json;
  80. }
  81. if (json['@type']) {
  82. switch (json['@type']) {
  83. case LONG_TYPE:
  84. // Fall through and handle this the same as unsigned.
  85. case UNSIGNED_LONG_TYPE: {
  86. // Technically, this could work return a valid number for malformed
  87. // data if there was a number followed by garbage. But it's just not
  88. // worth all the extra code to detect that case.
  89. var value = Number(json['value']);
  90. if (isNaN(value)) {
  91. throw new Error('Data cannot be decoded from JSON: ' + json);
  92. }
  93. return value;
  94. }
  95. default: {
  96. throw new Error('Data cannot be decoded from JSON: ' + json);
  97. }
  98. }
  99. }
  100. if (Array.isArray(json)) {
  101. return json.map(function (x) { return decode(x); });
  102. }
  103. if (typeof json === 'function' || typeof json === 'object') {
  104. return mapValues(json, function (x) { return decode(x); });
  105. }
  106. // Anything else is safe to return.
  107. return json;
  108. }
  109. /**
  110. * @license
  111. * Copyright 2020 Google LLC
  112. *
  113. * Licensed under the Apache License, Version 2.0 (the "License");
  114. * you may not use this file except in compliance with the License.
  115. * You may obtain a copy of the License at
  116. *
  117. * http://www.apache.org/licenses/LICENSE-2.0
  118. *
  119. * Unless required by applicable law or agreed to in writing, software
  120. * distributed under the License is distributed on an "AS IS" BASIS,
  121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  122. * See the License for the specific language governing permissions and
  123. * limitations under the License.
  124. */
  125. /**
  126. * Type constant for Firebase Functions.
  127. */
  128. var FUNCTIONS_TYPE = 'functions';
  129. /**
  130. * @license
  131. * Copyright 2017 Google LLC
  132. *
  133. * Licensed under the Apache License, Version 2.0 (the "License");
  134. * you may not use this file except in compliance with the License.
  135. * You may obtain a copy of the License at
  136. *
  137. * http://www.apache.org/licenses/LICENSE-2.0
  138. *
  139. * Unless required by applicable law or agreed to in writing, software
  140. * distributed under the License is distributed on an "AS IS" BASIS,
  141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  142. * See the License for the specific language governing permissions and
  143. * limitations under the License.
  144. */
  145. /**
  146. * Standard error codes for different ways a request can fail, as defined by:
  147. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  148. *
  149. * This map is used primarily to convert from a backend error code string to
  150. * a client SDK error code string, and make sure it's in the supported set.
  151. */
  152. var errorCodeMap = {
  153. OK: 'ok',
  154. CANCELLED: 'cancelled',
  155. UNKNOWN: 'unknown',
  156. INVALID_ARGUMENT: 'invalid-argument',
  157. DEADLINE_EXCEEDED: 'deadline-exceeded',
  158. NOT_FOUND: 'not-found',
  159. ALREADY_EXISTS: 'already-exists',
  160. PERMISSION_DENIED: 'permission-denied',
  161. UNAUTHENTICATED: 'unauthenticated',
  162. RESOURCE_EXHAUSTED: 'resource-exhausted',
  163. FAILED_PRECONDITION: 'failed-precondition',
  164. ABORTED: 'aborted',
  165. OUT_OF_RANGE: 'out-of-range',
  166. UNIMPLEMENTED: 'unimplemented',
  167. INTERNAL: 'internal',
  168. UNAVAILABLE: 'unavailable',
  169. DATA_LOSS: 'data-loss'
  170. };
  171. /**
  172. * An explicit error that can be thrown from a handler to send an error to the
  173. * client that called the function.
  174. */
  175. var FunctionsError = /** @class */ (function (_super) {
  176. __extends(FunctionsError, _super);
  177. function FunctionsError(
  178. /**
  179. * A standard error code that will be returned to the client. This also
  180. * determines the HTTP status code of the response, as defined in code.proto.
  181. */
  182. code, message,
  183. /**
  184. * Extra data to be converted to JSON and included in the error response.
  185. */
  186. details) {
  187. var _this = _super.call(this, "".concat(FUNCTIONS_TYPE, "/").concat(code), message || '') || this;
  188. _this.details = details;
  189. return _this;
  190. }
  191. return FunctionsError;
  192. }(FirebaseError));
  193. /**
  194. * Takes an HTTP status code and returns the corresponding ErrorCode.
  195. * This is the standard HTTP status code -> error mapping defined in:
  196. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  197. *
  198. * @param status An HTTP status code.
  199. * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.
  200. */
  201. function codeForHTTPStatus(status) {
  202. // Make sure any successful status is OK.
  203. if (status >= 200 && status < 300) {
  204. return 'ok';
  205. }
  206. switch (status) {
  207. case 0:
  208. // This can happen if the server returns 500.
  209. return 'internal';
  210. case 400:
  211. return 'invalid-argument';
  212. case 401:
  213. return 'unauthenticated';
  214. case 403:
  215. return 'permission-denied';
  216. case 404:
  217. return 'not-found';
  218. case 409:
  219. return 'aborted';
  220. case 429:
  221. return 'resource-exhausted';
  222. case 499:
  223. return 'cancelled';
  224. case 500:
  225. return 'internal';
  226. case 501:
  227. return 'unimplemented';
  228. case 503:
  229. return 'unavailable';
  230. case 504:
  231. return 'deadline-exceeded';
  232. }
  233. return 'unknown';
  234. }
  235. /**
  236. * Takes an HTTP response and returns the corresponding Error, if any.
  237. */
  238. function _errorForResponse(status, bodyJSON) {
  239. var code = codeForHTTPStatus(status);
  240. // Start with reasonable defaults from the status code.
  241. var description = code;
  242. var details = undefined;
  243. // Then look through the body for explicit details.
  244. try {
  245. var errorJSON = bodyJSON && bodyJSON.error;
  246. if (errorJSON) {
  247. var status_1 = errorJSON.status;
  248. if (typeof status_1 === 'string') {
  249. if (!errorCodeMap[status_1]) {
  250. // They must've included an unknown error code in the body.
  251. return new FunctionsError('internal', 'internal');
  252. }
  253. code = errorCodeMap[status_1];
  254. // TODO(klimt): Add better default descriptions for error enums.
  255. // The default description needs to be updated for the new code.
  256. description = status_1;
  257. }
  258. var message = errorJSON.message;
  259. if (typeof message === 'string') {
  260. description = message;
  261. }
  262. details = errorJSON.details;
  263. if (details !== undefined) {
  264. details = decode(details);
  265. }
  266. }
  267. }
  268. catch (e) {
  269. // If we couldn't parse explicit error data, that's fine.
  270. }
  271. if (code === 'ok') {
  272. // Technically, there's an edge case where a developer could explicitly
  273. // return an error code of OK, and we will treat it as success, but that
  274. // seems reasonable.
  275. return null;
  276. }
  277. return new FunctionsError(code, description, details);
  278. }
  279. /**
  280. * @license
  281. * Copyright 2017 Google LLC
  282. *
  283. * Licensed under the Apache License, Version 2.0 (the "License");
  284. * you may not use this file except in compliance with the License.
  285. * You may obtain a copy of the License at
  286. *
  287. * http://www.apache.org/licenses/LICENSE-2.0
  288. *
  289. * Unless required by applicable law or agreed to in writing, software
  290. * distributed under the License is distributed on an "AS IS" BASIS,
  291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  292. * See the License for the specific language governing permissions and
  293. * limitations under the License.
  294. */
  295. /**
  296. * Helper class to get metadata that should be included with a function call.
  297. * @internal
  298. */
  299. var ContextProvider = /** @class */ (function () {
  300. function ContextProvider(authProvider, messagingProvider, appCheckProvider) {
  301. var _this = this;
  302. this.auth = null;
  303. this.messaging = null;
  304. this.appCheck = null;
  305. this.auth = authProvider.getImmediate({ optional: true });
  306. this.messaging = messagingProvider.getImmediate({
  307. optional: true
  308. });
  309. if (!this.auth) {
  310. authProvider.get().then(function (auth) { return (_this.auth = auth); }, function () {
  311. /* get() never rejects */
  312. });
  313. }
  314. if (!this.messaging) {
  315. messagingProvider.get().then(function (messaging) { return (_this.messaging = messaging); }, function () {
  316. /* get() never rejects */
  317. });
  318. }
  319. if (!this.appCheck) {
  320. appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); }, function () {
  321. /* get() never rejects */
  322. });
  323. }
  324. }
  325. ContextProvider.prototype.getAuthToken = function () {
  326. return __awaiter(this, void 0, void 0, function () {
  327. var token;
  328. return __generator(this, function (_a) {
  329. switch (_a.label) {
  330. case 0:
  331. if (!this.auth) {
  332. return [2 /*return*/, undefined];
  333. }
  334. _a.label = 1;
  335. case 1:
  336. _a.trys.push([1, 3, , 4]);
  337. return [4 /*yield*/, this.auth.getToken()];
  338. case 2:
  339. token = _a.sent();
  340. return [2 /*return*/, token === null || token === void 0 ? void 0 : token.accessToken];
  341. case 3:
  342. _a.sent();
  343. // If there's any error when trying to get the auth token, leave it off.
  344. return [2 /*return*/, undefined];
  345. case 4: return [2 /*return*/];
  346. }
  347. });
  348. });
  349. };
  350. ContextProvider.prototype.getMessagingToken = function () {
  351. return __awaiter(this, void 0, void 0, function () {
  352. return __generator(this, function (_a) {
  353. switch (_a.label) {
  354. case 0:
  355. if (!this.messaging ||
  356. !('Notification' in self) ||
  357. Notification.permission !== 'granted') {
  358. return [2 /*return*/, undefined];
  359. }
  360. _a.label = 1;
  361. case 1:
  362. _a.trys.push([1, 3, , 4]);
  363. return [4 /*yield*/, this.messaging.getToken()];
  364. case 2: return [2 /*return*/, _a.sent()];
  365. case 3:
  366. _a.sent();
  367. // We don't warn on this, because it usually means messaging isn't set up.
  368. // console.warn('Failed to retrieve instance id token.', e);
  369. // If there's any error when trying to get the token, leave it off.
  370. return [2 /*return*/, undefined];
  371. case 4: return [2 /*return*/];
  372. }
  373. });
  374. });
  375. };
  376. ContextProvider.prototype.getAppCheckToken = function () {
  377. return __awaiter(this, void 0, void 0, function () {
  378. var result;
  379. return __generator(this, function (_a) {
  380. switch (_a.label) {
  381. case 0:
  382. if (!this.appCheck) return [3 /*break*/, 2];
  383. return [4 /*yield*/, this.appCheck.getToken()];
  384. case 1:
  385. result = _a.sent();
  386. if (result.error) {
  387. // Do not send the App Check header to the functions endpoint if
  388. // there was an error from the App Check exchange endpoint. The App
  389. // Check SDK will already have logged the error to console.
  390. return [2 /*return*/, null];
  391. }
  392. return [2 /*return*/, result.token];
  393. case 2: return [2 /*return*/, null];
  394. }
  395. });
  396. });
  397. };
  398. ContextProvider.prototype.getContext = function () {
  399. return __awaiter(this, void 0, void 0, function () {
  400. var authToken, messagingToken, appCheckToken;
  401. return __generator(this, function (_a) {
  402. switch (_a.label) {
  403. case 0: return [4 /*yield*/, this.getAuthToken()];
  404. case 1:
  405. authToken = _a.sent();
  406. return [4 /*yield*/, this.getMessagingToken()];
  407. case 2:
  408. messagingToken = _a.sent();
  409. return [4 /*yield*/, this.getAppCheckToken()];
  410. case 3:
  411. appCheckToken = _a.sent();
  412. return [2 /*return*/, { authToken: authToken, messagingToken: messagingToken, appCheckToken: appCheckToken }];
  413. }
  414. });
  415. });
  416. };
  417. return ContextProvider;
  418. }());
  419. /**
  420. * @license
  421. * Copyright 2017 Google LLC
  422. *
  423. * Licensed under the Apache License, Version 2.0 (the "License");
  424. * you may not use this file except in compliance with the License.
  425. * You may obtain a copy of the License at
  426. *
  427. * http://www.apache.org/licenses/LICENSE-2.0
  428. *
  429. * Unless required by applicable law or agreed to in writing, software
  430. * distributed under the License is distributed on an "AS IS" BASIS,
  431. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  432. * See the License for the specific language governing permissions and
  433. * limitations under the License.
  434. */
  435. var DEFAULT_REGION = 'us-central1';
  436. /**
  437. * Returns a Promise that will be rejected after the given duration.
  438. * The error will be of type FunctionsError.
  439. *
  440. * @param millis Number of milliseconds to wait before rejecting.
  441. */
  442. function failAfter(millis) {
  443. // Node timers and browser timers are fundamentally incompatible, but we
  444. // don't care about the value here
  445. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  446. var timer = null;
  447. return {
  448. promise: new Promise(function (_, reject) {
  449. timer = setTimeout(function () {
  450. reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));
  451. }, millis);
  452. }),
  453. cancel: function () {
  454. if (timer) {
  455. clearTimeout(timer);
  456. }
  457. }
  458. };
  459. }
  460. /**
  461. * The main class for the Firebase Functions SDK.
  462. * @internal
  463. */
  464. var FunctionsService = /** @class */ (function () {
  465. /**
  466. * Creates a new Functions service for the given app.
  467. * @param app - The FirebaseApp to use.
  468. */
  469. function FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl) {
  470. if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
  471. var _this = this;
  472. this.app = app;
  473. this.fetchImpl = fetchImpl;
  474. this.emulatorOrigin = null;
  475. this.contextProvider = new ContextProvider(authProvider, messagingProvider, appCheckProvider);
  476. // Cancels all ongoing requests when resolved.
  477. this.cancelAllRequests = new Promise(function (resolve) {
  478. _this.deleteService = function () {
  479. return Promise.resolve(resolve());
  480. };
  481. });
  482. // Resolve the region or custom domain overload by attempting to parse it.
  483. try {
  484. var url = new URL(regionOrCustomDomain);
  485. this.customDomain = url.origin;
  486. this.region = DEFAULT_REGION;
  487. }
  488. catch (e) {
  489. this.customDomain = null;
  490. this.region = regionOrCustomDomain;
  491. }
  492. }
  493. FunctionsService.prototype._delete = function () {
  494. return this.deleteService();
  495. };
  496. /**
  497. * Returns the URL for a callable with the given name.
  498. * @param name - The name of the callable.
  499. * @internal
  500. */
  501. FunctionsService.prototype._url = function (name) {
  502. var projectId = this.app.options.projectId;
  503. if (this.emulatorOrigin !== null) {
  504. var origin_1 = this.emulatorOrigin;
  505. return "".concat(origin_1, "/").concat(projectId, "/").concat(this.region, "/").concat(name);
  506. }
  507. if (this.customDomain !== null) {
  508. return "".concat(this.customDomain, "/").concat(name);
  509. }
  510. return "https://".concat(this.region, "-").concat(projectId, ".cloudfunctions.net/").concat(name);
  511. };
  512. return FunctionsService;
  513. }());
  514. /**
  515. * Modify this instance to communicate with the Cloud Functions emulator.
  516. *
  517. * Note: this must be called before this instance has been used to do any operations.
  518. *
  519. * @param host The emulator host (ex: localhost)
  520. * @param port The emulator port (ex: 5001)
  521. * @public
  522. */
  523. function connectFunctionsEmulator$1(functionsInstance, host, port) {
  524. functionsInstance.emulatorOrigin = "http://".concat(host, ":").concat(port);
  525. }
  526. /**
  527. * Returns a reference to the callable https trigger with the given name.
  528. * @param name - The name of the trigger.
  529. * @public
  530. */
  531. function httpsCallable$1(functionsInstance, name, options) {
  532. return (function (data) {
  533. return call(functionsInstance, name, data, options || {});
  534. });
  535. }
  536. /**
  537. * Returns a reference to the callable https trigger with the given url.
  538. * @param url - The url of the trigger.
  539. * @public
  540. */
  541. function httpsCallableFromURL$1(functionsInstance, url, options) {
  542. return (function (data) {
  543. return callAtURL(functionsInstance, url, data, options || {});
  544. });
  545. }
  546. /**
  547. * Does an HTTP POST and returns the completed response.
  548. * @param url The url to post to.
  549. * @param body The JSON body of the post.
  550. * @param headers The HTTP headers to include in the request.
  551. * @return A Promise that will succeed when the request finishes.
  552. */
  553. function postJSON(url, body, headers, fetchImpl) {
  554. return __awaiter(this, void 0, void 0, function () {
  555. var response, json;
  556. return __generator(this, function (_a) {
  557. switch (_a.label) {
  558. case 0:
  559. headers['Content-Type'] = 'application/json';
  560. _a.label = 1;
  561. case 1:
  562. _a.trys.push([1, 3, , 4]);
  563. return [4 /*yield*/, fetchImpl(url, {
  564. method: 'POST',
  565. body: JSON.stringify(body),
  566. headers: headers
  567. })];
  568. case 2:
  569. response = _a.sent();
  570. return [3 /*break*/, 4];
  571. case 3:
  572. _a.sent();
  573. // This could be an unhandled error on the backend, or it could be a
  574. // network error. There's no way to know, since an unhandled error on the
  575. // backend will fail to set the proper CORS header, and thus will be
  576. // treated as a network error by fetch.
  577. return [2 /*return*/, {
  578. status: 0,
  579. json: null
  580. }];
  581. case 4:
  582. json = null;
  583. _a.label = 5;
  584. case 5:
  585. _a.trys.push([5, 7, , 8]);
  586. return [4 /*yield*/, response.json()];
  587. case 6:
  588. json = _a.sent();
  589. return [3 /*break*/, 8];
  590. case 7:
  591. _a.sent();
  592. return [3 /*break*/, 8];
  593. case 8: return [2 /*return*/, {
  594. status: response.status,
  595. json: json
  596. }];
  597. }
  598. });
  599. });
  600. }
  601. /**
  602. * Calls a callable function asynchronously and returns the result.
  603. * @param name The name of the callable trigger.
  604. * @param data The data to pass as params to the function.s
  605. */
  606. function call(functionsInstance, name, data, options) {
  607. var url = functionsInstance._url(name);
  608. return callAtURL(functionsInstance, url, data, options);
  609. }
  610. /**
  611. * Calls a callable function asynchronously and returns the result.
  612. * @param url The url of the callable trigger.
  613. * @param data The data to pass as params to the function.s
  614. */
  615. function callAtURL(functionsInstance, url, data, options) {
  616. return __awaiter(this, void 0, void 0, function () {
  617. var body, headers, context, timeout, failAfterHandle, response, error, responseData, decodedData;
  618. return __generator(this, function (_a) {
  619. switch (_a.label) {
  620. case 0:
  621. // Encode any special types, such as dates, in the input data.
  622. data = encode(data);
  623. body = { data: data };
  624. headers = {};
  625. return [4 /*yield*/, functionsInstance.contextProvider.getContext()];
  626. case 1:
  627. context = _a.sent();
  628. if (context.authToken) {
  629. headers['Authorization'] = 'Bearer ' + context.authToken;
  630. }
  631. if (context.messagingToken) {
  632. headers['Firebase-Instance-ID-Token'] = context.messagingToken;
  633. }
  634. if (context.appCheckToken !== null) {
  635. headers['X-Firebase-AppCheck'] = context.appCheckToken;
  636. }
  637. timeout = options.timeout || 70000;
  638. failAfterHandle = failAfter(timeout);
  639. return [4 /*yield*/, Promise.race([
  640. postJSON(url, body, headers, functionsInstance.fetchImpl),
  641. failAfterHandle.promise,
  642. functionsInstance.cancelAllRequests
  643. ])];
  644. case 2:
  645. response = _a.sent();
  646. // Always clear the failAfter timeout
  647. failAfterHandle.cancel();
  648. // If service was deleted, interrupted response throws an error.
  649. if (!response) {
  650. throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');
  651. }
  652. error = _errorForResponse(response.status, response.json);
  653. if (error) {
  654. throw error;
  655. }
  656. if (!response.json) {
  657. throw new FunctionsError('internal', 'Response is not valid JSON object.');
  658. }
  659. responseData = response.json.data;
  660. // TODO(klimt): For right now, allow "result" instead of "data", for
  661. // backwards compatibility.
  662. if (typeof responseData === 'undefined') {
  663. responseData = response.json.result;
  664. }
  665. if (typeof responseData === 'undefined') {
  666. // Consider the response malformed.
  667. throw new FunctionsError('internal', 'Response is missing data field.');
  668. }
  669. decodedData = decode(responseData);
  670. return [2 /*return*/, { data: decodedData }];
  671. }
  672. });
  673. });
  674. }
  675. var name = "@firebase/functions";
  676. var version = "0.9.1";
  677. /**
  678. * @license
  679. * Copyright 2019 Google LLC
  680. *
  681. * Licensed under the Apache License, Version 2.0 (the "License");
  682. * you may not use this file except in compliance with the License.
  683. * You may obtain a copy of the License at
  684. *
  685. * http://www.apache.org/licenses/LICENSE-2.0
  686. *
  687. * Unless required by applicable law or agreed to in writing, software
  688. * distributed under the License is distributed on an "AS IS" BASIS,
  689. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  690. * See the License for the specific language governing permissions and
  691. * limitations under the License.
  692. */
  693. var AUTH_INTERNAL_NAME = 'auth-internal';
  694. var APP_CHECK_INTERNAL_NAME = 'app-check-internal';
  695. var MESSAGING_INTERNAL_NAME = 'messaging-internal';
  696. function registerFunctions(fetchImpl, variant) {
  697. var factory = function (container, _a) {
  698. var regionOrCustomDomain = _a.instanceIdentifier;
  699. // Dependencies
  700. var app = container.getProvider('app').getImmediate();
  701. var authProvider = container.getProvider(AUTH_INTERNAL_NAME);
  702. var messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);
  703. var appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);
  704. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  705. return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl);
  706. };
  707. _registerComponent(new Component(FUNCTIONS_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  708. registerVersion(name, version, variant);
  709. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  710. registerVersion(name, version, 'esm5');
  711. }
  712. /**
  713. * @license
  714. * Copyright 2020 Google LLC
  715. *
  716. * Licensed under the Apache License, Version 2.0 (the "License");
  717. * you may not use this file except in compliance with the License.
  718. * You may obtain a copy of the License at
  719. *
  720. * http://www.apache.org/licenses/LICENSE-2.0
  721. *
  722. * Unless required by applicable law or agreed to in writing, software
  723. * distributed under the License is distributed on an "AS IS" BASIS,
  724. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  725. * See the License for the specific language governing permissions and
  726. * limitations under the License.
  727. */
  728. /**
  729. * Returns a {@link Functions} instance for the given app.
  730. * @param app - The {@link @firebase/app#FirebaseApp} to use.
  731. * @param regionOrCustomDomain - one of:
  732. * a) The region the callable functions are located in (ex: us-central1)
  733. * b) A custom domain hosting the callable functions (ex: https://mydomain.com)
  734. * @public
  735. */
  736. function getFunctions(app, regionOrCustomDomain) {
  737. if (app === void 0) { app = getApp(); }
  738. if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
  739. // Dependencies
  740. var functionsProvider = _getProvider(getModularInstance(app), FUNCTIONS_TYPE);
  741. var functionsInstance = functionsProvider.getImmediate({
  742. identifier: regionOrCustomDomain
  743. });
  744. var emulator = getDefaultEmulatorHostnameAndPort('functions');
  745. if (emulator) {
  746. connectFunctionsEmulator.apply(void 0, __spreadArray([functionsInstance], emulator, false));
  747. }
  748. return functionsInstance;
  749. }
  750. /**
  751. * Modify this instance to communicate with the Cloud Functions emulator.
  752. *
  753. * Note: this must be called before this instance has been used to do any operations.
  754. *
  755. * @param host - The emulator host (ex: localhost)
  756. * @param port - The emulator port (ex: 5001)
  757. * @public
  758. */
  759. function connectFunctionsEmulator(functionsInstance, host, port) {
  760. connectFunctionsEmulator$1(getModularInstance(functionsInstance), host, port);
  761. }
  762. /**
  763. * Returns a reference to the callable HTTPS trigger with the given name.
  764. * @param name - The name of the trigger.
  765. * @public
  766. */
  767. function httpsCallable(functionsInstance, name, options) {
  768. return httpsCallable$1(getModularInstance(functionsInstance), name, options);
  769. }
  770. /**
  771. * Returns a reference to the callable HTTPS trigger with the specified url.
  772. * @param url - The url of the trigger.
  773. * @public
  774. */
  775. function httpsCallableFromURL(functionsInstance, url, options) {
  776. return httpsCallableFromURL$1(getModularInstance(functionsInstance), url, options);
  777. }
  778. /**
  779. * Cloud Functions for Firebase
  780. *
  781. * @packageDocumentation
  782. */
  783. registerFunctions(fetch.bind(self));
  784. export { connectFunctionsEmulator, getFunctions, httpsCallable, httpsCallableFromURL };
  785. //# sourceMappingURL=index.esm.js.map