index.esm.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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 (limitedUseAppCheckTokens) {
  377. return __awaiter(this, void 0, void 0, function () {
  378. var result, _a;
  379. return __generator(this, function (_b) {
  380. switch (_b.label) {
  381. case 0:
  382. if (!this.appCheck) return [3 /*break*/, 5];
  383. if (!limitedUseAppCheckTokens) return [3 /*break*/, 2];
  384. return [4 /*yield*/, this.appCheck.getLimitedUseToken()];
  385. case 1:
  386. _a = _b.sent();
  387. return [3 /*break*/, 4];
  388. case 2: return [4 /*yield*/, this.appCheck.getToken()];
  389. case 3:
  390. _a = _b.sent();
  391. _b.label = 4;
  392. case 4:
  393. result = _a;
  394. if (result.error) {
  395. // Do not send the App Check header to the functions endpoint if
  396. // there was an error from the App Check exchange endpoint. The App
  397. // Check SDK will already have logged the error to console.
  398. return [2 /*return*/, null];
  399. }
  400. return [2 /*return*/, result.token];
  401. case 5: return [2 /*return*/, null];
  402. }
  403. });
  404. });
  405. };
  406. ContextProvider.prototype.getContext = function (limitedUseAppCheckTokens) {
  407. return __awaiter(this, void 0, void 0, function () {
  408. var authToken, messagingToken, appCheckToken;
  409. return __generator(this, function (_a) {
  410. switch (_a.label) {
  411. case 0: return [4 /*yield*/, this.getAuthToken()];
  412. case 1:
  413. authToken = _a.sent();
  414. return [4 /*yield*/, this.getMessagingToken()];
  415. case 2:
  416. messagingToken = _a.sent();
  417. return [4 /*yield*/, this.getAppCheckToken(limitedUseAppCheckTokens)];
  418. case 3:
  419. appCheckToken = _a.sent();
  420. return [2 /*return*/, { authToken: authToken, messagingToken: messagingToken, appCheckToken: appCheckToken }];
  421. }
  422. });
  423. });
  424. };
  425. return ContextProvider;
  426. }());
  427. /**
  428. * @license
  429. * Copyright 2017 Google LLC
  430. *
  431. * Licensed under the Apache License, Version 2.0 (the "License");
  432. * you may not use this file except in compliance with the License.
  433. * You may obtain a copy of the License at
  434. *
  435. * http://www.apache.org/licenses/LICENSE-2.0
  436. *
  437. * Unless required by applicable law or agreed to in writing, software
  438. * distributed under the License is distributed on an "AS IS" BASIS,
  439. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  440. * See the License for the specific language governing permissions and
  441. * limitations under the License.
  442. */
  443. var DEFAULT_REGION = 'us-central1';
  444. /**
  445. * Returns a Promise that will be rejected after the given duration.
  446. * The error will be of type FunctionsError.
  447. *
  448. * @param millis Number of milliseconds to wait before rejecting.
  449. */
  450. function failAfter(millis) {
  451. // Node timers and browser timers are fundamentally incompatible, but we
  452. // don't care about the value here
  453. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  454. var timer = null;
  455. return {
  456. promise: new Promise(function (_, reject) {
  457. timer = setTimeout(function () {
  458. reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));
  459. }, millis);
  460. }),
  461. cancel: function () {
  462. if (timer) {
  463. clearTimeout(timer);
  464. }
  465. }
  466. };
  467. }
  468. /**
  469. * The main class for the Firebase Functions SDK.
  470. * @internal
  471. */
  472. var FunctionsService = /** @class */ (function () {
  473. /**
  474. * Creates a new Functions service for the given app.
  475. * @param app - The FirebaseApp to use.
  476. */
  477. function FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl) {
  478. if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
  479. var _this = this;
  480. this.app = app;
  481. this.fetchImpl = fetchImpl;
  482. this.emulatorOrigin = null;
  483. this.contextProvider = new ContextProvider(authProvider, messagingProvider, appCheckProvider);
  484. // Cancels all ongoing requests when resolved.
  485. this.cancelAllRequests = new Promise(function (resolve) {
  486. _this.deleteService = function () {
  487. return Promise.resolve(resolve());
  488. };
  489. });
  490. // Resolve the region or custom domain overload by attempting to parse it.
  491. try {
  492. var url = new URL(regionOrCustomDomain);
  493. this.customDomain = url.origin;
  494. this.region = DEFAULT_REGION;
  495. }
  496. catch (e) {
  497. this.customDomain = null;
  498. this.region = regionOrCustomDomain;
  499. }
  500. }
  501. FunctionsService.prototype._delete = function () {
  502. return this.deleteService();
  503. };
  504. /**
  505. * Returns the URL for a callable with the given name.
  506. * @param name - The name of the callable.
  507. * @internal
  508. */
  509. FunctionsService.prototype._url = function (name) {
  510. var projectId = this.app.options.projectId;
  511. if (this.emulatorOrigin !== null) {
  512. var origin_1 = this.emulatorOrigin;
  513. return "".concat(origin_1, "/").concat(projectId, "/").concat(this.region, "/").concat(name);
  514. }
  515. if (this.customDomain !== null) {
  516. return "".concat(this.customDomain, "/").concat(name);
  517. }
  518. return "https://".concat(this.region, "-").concat(projectId, ".cloudfunctions.net/").concat(name);
  519. };
  520. return FunctionsService;
  521. }());
  522. /**
  523. * Modify this instance to communicate with the Cloud Functions emulator.
  524. *
  525. * Note: this must be called before this instance has been used to do any operations.
  526. *
  527. * @param host The emulator host (ex: localhost)
  528. * @param port The emulator port (ex: 5001)
  529. * @public
  530. */
  531. function connectFunctionsEmulator$1(functionsInstance, host, port) {
  532. functionsInstance.emulatorOrigin = "http://".concat(host, ":").concat(port);
  533. }
  534. /**
  535. * Returns a reference to the callable https trigger with the given name.
  536. * @param name - The name of the trigger.
  537. * @public
  538. */
  539. function httpsCallable$1(functionsInstance, name, options) {
  540. return (function (data) {
  541. return call(functionsInstance, name, data, options || {});
  542. });
  543. }
  544. /**
  545. * Returns a reference to the callable https trigger with the given url.
  546. * @param url - The url of the trigger.
  547. * @public
  548. */
  549. function httpsCallableFromURL$1(functionsInstance, url, options) {
  550. return (function (data) {
  551. return callAtURL(functionsInstance, url, data, options || {});
  552. });
  553. }
  554. /**
  555. * Does an HTTP POST and returns the completed response.
  556. * @param url The url to post to.
  557. * @param body The JSON body of the post.
  558. * @param headers The HTTP headers to include in the request.
  559. * @return A Promise that will succeed when the request finishes.
  560. */
  561. function postJSON(url, body, headers, fetchImpl) {
  562. return __awaiter(this, void 0, void 0, function () {
  563. var response, json;
  564. return __generator(this, function (_a) {
  565. switch (_a.label) {
  566. case 0:
  567. headers['Content-Type'] = 'application/json';
  568. _a.label = 1;
  569. case 1:
  570. _a.trys.push([1, 3, , 4]);
  571. return [4 /*yield*/, fetchImpl(url, {
  572. method: 'POST',
  573. body: JSON.stringify(body),
  574. headers: headers
  575. })];
  576. case 2:
  577. response = _a.sent();
  578. return [3 /*break*/, 4];
  579. case 3:
  580. _a.sent();
  581. // This could be an unhandled error on the backend, or it could be a
  582. // network error. There's no way to know, since an unhandled error on the
  583. // backend will fail to set the proper CORS header, and thus will be
  584. // treated as a network error by fetch.
  585. return [2 /*return*/, {
  586. status: 0,
  587. json: null
  588. }];
  589. case 4:
  590. json = null;
  591. _a.label = 5;
  592. case 5:
  593. _a.trys.push([5, 7, , 8]);
  594. return [4 /*yield*/, response.json()];
  595. case 6:
  596. json = _a.sent();
  597. return [3 /*break*/, 8];
  598. case 7:
  599. _a.sent();
  600. return [3 /*break*/, 8];
  601. case 8: return [2 /*return*/, {
  602. status: response.status,
  603. json: json
  604. }];
  605. }
  606. });
  607. });
  608. }
  609. /**
  610. * Calls a callable function asynchronously and returns the result.
  611. * @param name The name of the callable trigger.
  612. * @param data The data to pass as params to the function.s
  613. */
  614. function call(functionsInstance, name, data, options) {
  615. var url = functionsInstance._url(name);
  616. return callAtURL(functionsInstance, url, data, options);
  617. }
  618. /**
  619. * Calls a callable function asynchronously and returns the result.
  620. * @param url The url of the callable trigger.
  621. * @param data The data to pass as params to the function.s
  622. */
  623. function callAtURL(functionsInstance, url, data, options) {
  624. return __awaiter(this, void 0, void 0, function () {
  625. var body, headers, context, timeout, failAfterHandle, response, error, responseData, decodedData;
  626. return __generator(this, function (_a) {
  627. switch (_a.label) {
  628. case 0:
  629. // Encode any special types, such as dates, in the input data.
  630. data = encode(data);
  631. body = { data: data };
  632. headers = {};
  633. return [4 /*yield*/, functionsInstance.contextProvider.getContext(options.limitedUseAppCheckTokens)];
  634. case 1:
  635. context = _a.sent();
  636. if (context.authToken) {
  637. headers['Authorization'] = 'Bearer ' + context.authToken;
  638. }
  639. if (context.messagingToken) {
  640. headers['Firebase-Instance-ID-Token'] = context.messagingToken;
  641. }
  642. if (context.appCheckToken !== null) {
  643. headers['X-Firebase-AppCheck'] = context.appCheckToken;
  644. }
  645. timeout = options.timeout || 70000;
  646. failAfterHandle = failAfter(timeout);
  647. return [4 /*yield*/, Promise.race([
  648. postJSON(url, body, headers, functionsInstance.fetchImpl),
  649. failAfterHandle.promise,
  650. functionsInstance.cancelAllRequests
  651. ])];
  652. case 2:
  653. response = _a.sent();
  654. // Always clear the failAfter timeout
  655. failAfterHandle.cancel();
  656. // If service was deleted, interrupted response throws an error.
  657. if (!response) {
  658. throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');
  659. }
  660. error = _errorForResponse(response.status, response.json);
  661. if (error) {
  662. throw error;
  663. }
  664. if (!response.json) {
  665. throw new FunctionsError('internal', 'Response is not valid JSON object.');
  666. }
  667. responseData = response.json.data;
  668. // TODO(klimt): For right now, allow "result" instead of "data", for
  669. // backwards compatibility.
  670. if (typeof responseData === 'undefined') {
  671. responseData = response.json.result;
  672. }
  673. if (typeof responseData === 'undefined') {
  674. // Consider the response malformed.
  675. throw new FunctionsError('internal', 'Response is missing data field.');
  676. }
  677. decodedData = decode(responseData);
  678. return [2 /*return*/, { data: decodedData }];
  679. }
  680. });
  681. });
  682. }
  683. var name = "@firebase/functions";
  684. var version = "0.10.0";
  685. /**
  686. * @license
  687. * Copyright 2019 Google LLC
  688. *
  689. * Licensed under the Apache License, Version 2.0 (the "License");
  690. * you may not use this file except in compliance with the License.
  691. * You may obtain a copy of the License at
  692. *
  693. * http://www.apache.org/licenses/LICENSE-2.0
  694. *
  695. * Unless required by applicable law or agreed to in writing, software
  696. * distributed under the License is distributed on an "AS IS" BASIS,
  697. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  698. * See the License for the specific language governing permissions and
  699. * limitations under the License.
  700. */
  701. var AUTH_INTERNAL_NAME = 'auth-internal';
  702. var APP_CHECK_INTERNAL_NAME = 'app-check-internal';
  703. var MESSAGING_INTERNAL_NAME = 'messaging-internal';
  704. function registerFunctions(fetchImpl, variant) {
  705. var factory = function (container, _a) {
  706. var regionOrCustomDomain = _a.instanceIdentifier;
  707. // Dependencies
  708. var app = container.getProvider('app').getImmediate();
  709. var authProvider = container.getProvider(AUTH_INTERNAL_NAME);
  710. var messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);
  711. var appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);
  712. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  713. return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl);
  714. };
  715. _registerComponent(new Component(FUNCTIONS_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  716. registerVersion(name, version, variant);
  717. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  718. registerVersion(name, version, 'esm5');
  719. }
  720. /**
  721. * @license
  722. * Copyright 2020 Google LLC
  723. *
  724. * Licensed under the Apache License, Version 2.0 (the "License");
  725. * you may not use this file except in compliance with the License.
  726. * You may obtain a copy of the License at
  727. *
  728. * http://www.apache.org/licenses/LICENSE-2.0
  729. *
  730. * Unless required by applicable law or agreed to in writing, software
  731. * distributed under the License is distributed on an "AS IS" BASIS,
  732. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  733. * See the License for the specific language governing permissions and
  734. * limitations under the License.
  735. */
  736. /**
  737. * Returns a {@link Functions} instance for the given app.
  738. * @param app - The {@link @firebase/app#FirebaseApp} to use.
  739. * @param regionOrCustomDomain - one of:
  740. * a) The region the callable functions are located in (ex: us-central1)
  741. * b) A custom domain hosting the callable functions (ex: https://mydomain.com)
  742. * @public
  743. */
  744. function getFunctions(app, regionOrCustomDomain) {
  745. if (app === void 0) { app = getApp(); }
  746. if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
  747. // Dependencies
  748. var functionsProvider = _getProvider(getModularInstance(app), FUNCTIONS_TYPE);
  749. var functionsInstance = functionsProvider.getImmediate({
  750. identifier: regionOrCustomDomain
  751. });
  752. var emulator = getDefaultEmulatorHostnameAndPort('functions');
  753. if (emulator) {
  754. connectFunctionsEmulator.apply(void 0, __spreadArray([functionsInstance], emulator, false));
  755. }
  756. return functionsInstance;
  757. }
  758. /**
  759. * Modify this instance to communicate with the Cloud Functions emulator.
  760. *
  761. * Note: this must be called before this instance has been used to do any operations.
  762. *
  763. * @param host - The emulator host (ex: localhost)
  764. * @param port - The emulator port (ex: 5001)
  765. * @public
  766. */
  767. function connectFunctionsEmulator(functionsInstance, host, port) {
  768. connectFunctionsEmulator$1(getModularInstance(functionsInstance), host, port);
  769. }
  770. /**
  771. * Returns a reference to the callable HTTPS trigger with the given name.
  772. * @param name - The name of the trigger.
  773. * @public
  774. */
  775. function httpsCallable(functionsInstance, name, options) {
  776. return httpsCallable$1(getModularInstance(functionsInstance), name, options);
  777. }
  778. /**
  779. * Returns a reference to the callable HTTPS trigger with the specified url.
  780. * @param url - The url of the trigger.
  781. * @public
  782. */
  783. function httpsCallableFromURL(functionsInstance, url, options) {
  784. return httpsCallableFromURL$1(getModularInstance(functionsInstance), url, options);
  785. }
  786. /**
  787. * Cloud Functions for Firebase
  788. *
  789. * @packageDocumentation
  790. */
  791. registerFunctions(fetch.bind(self));
  792. export { connectFunctionsEmulator, getFunctions, httpsCallable, httpsCallableFromURL };
  793. //# sourceMappingURL=index.esm.js.map