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.node.cjs.js 31KB

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