index.esm2017.js 26 KB

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