@depup/firebase__functions 0.13.2-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,970 @@
1
+ import { _isFirebaseServerApp, _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';
2
+ import { FirebaseError, isCloudWorkstation, pingServer, updateEmulatorBanner, getModularInstance, getDefaultEmulatorHostnameAndPort } from '@firebase/util';
3
+ import { Component } from '@firebase/component';
4
+
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
+ const LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';
22
+ const 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
+ const result = {};
28
+ for (const 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(x => encode(x));
64
+ }
65
+ if (typeof data === 'function' || typeof data === 'object') {
66
+ return mapValues(data, x => 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
+ const 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(x => decode(x));
102
+ }
103
+ if (typeof json === 'function' || typeof json === 'object') {
104
+ return mapValues(json, x => decode(x));
105
+ }
106
+ // Anything else is safe to return.
107
+ return json;
108
+ }
109
+
110
+ /**
111
+ * @license
112
+ * Copyright 2020 Google LLC
113
+ *
114
+ * Licensed under the Apache License, Version 2.0 (the "License");
115
+ * you may not use this file except in compliance with the License.
116
+ * You may obtain a copy of the License at
117
+ *
118
+ * http://www.apache.org/licenses/LICENSE-2.0
119
+ *
120
+ * Unless required by applicable law or agreed to in writing, software
121
+ * distributed under the License is distributed on an "AS IS" BASIS,
122
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
123
+ * See the License for the specific language governing permissions and
124
+ * limitations under the License.
125
+ */
126
+ /**
127
+ * Type constant for Firebase Functions.
128
+ */
129
+ const FUNCTIONS_TYPE = 'functions';
130
+
131
+ /**
132
+ * @license
133
+ * Copyright 2017 Google LLC
134
+ *
135
+ * Licensed under the Apache License, Version 2.0 (the "License");
136
+ * you may not use this file except in compliance with the License.
137
+ * You may obtain a copy of the License at
138
+ *
139
+ * http://www.apache.org/licenses/LICENSE-2.0
140
+ *
141
+ * Unless required by applicable law or agreed to in writing, software
142
+ * distributed under the License is distributed on an "AS IS" BASIS,
143
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
144
+ * See the License for the specific language governing permissions and
145
+ * limitations under the License.
146
+ */
147
+ /**
148
+ * Standard error codes for different ways a request can fail, as defined by:
149
+ * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
150
+ *
151
+ * This map is used primarily to convert from a backend error code string to
152
+ * a client SDK error code string, and make sure it's in the supported set.
153
+ */
154
+ const errorCodeMap = {
155
+ OK: 'ok',
156
+ CANCELLED: 'cancelled',
157
+ UNKNOWN: 'unknown',
158
+ INVALID_ARGUMENT: 'invalid-argument',
159
+ DEADLINE_EXCEEDED: 'deadline-exceeded',
160
+ NOT_FOUND: 'not-found',
161
+ ALREADY_EXISTS: 'already-exists',
162
+ PERMISSION_DENIED: 'permission-denied',
163
+ UNAUTHENTICATED: 'unauthenticated',
164
+ RESOURCE_EXHAUSTED: 'resource-exhausted',
165
+ FAILED_PRECONDITION: 'failed-precondition',
166
+ ABORTED: 'aborted',
167
+ OUT_OF_RANGE: 'out-of-range',
168
+ UNIMPLEMENTED: 'unimplemented',
169
+ INTERNAL: 'internal',
170
+ UNAVAILABLE: 'unavailable',
171
+ DATA_LOSS: 'data-loss'
172
+ };
173
+ /**
174
+ * An error returned by the Firebase Functions client SDK.
175
+ *
176
+ * See {@link FunctionsErrorCode} for full documentation of codes.
177
+ *
178
+ * @public
179
+ */
180
+ class FunctionsError extends FirebaseError {
181
+ /**
182
+ * Constructs a new instance of the `FunctionsError` class.
183
+ */
184
+ constructor(
185
+ /**
186
+ * A standard error code that will be returned to the client. This also
187
+ * determines the HTTP status code of the response, as defined in code.proto.
188
+ */
189
+ code, message,
190
+ /**
191
+ * Additional details to be converted to JSON and included in the error response.
192
+ */
193
+ details) {
194
+ super(`${FUNCTIONS_TYPE}/${code}`, message || '');
195
+ this.details = details;
196
+ // Since the FirebaseError constructor sets the prototype of `this` to FirebaseError.prototype,
197
+ // we also have to do it in all subclasses to allow for correct `instanceof` checks.
198
+ Object.setPrototypeOf(this, FunctionsError.prototype);
199
+ }
200
+ }
201
+ /**
202
+ * Takes an HTTP status code and returns the corresponding ErrorCode.
203
+ * This is the standard HTTP status code -> error mapping defined in:
204
+ * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
205
+ *
206
+ * @param status An HTTP status code.
207
+ * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.
208
+ */
209
+ function codeForHTTPStatus(status) {
210
+ // Make sure any successful status is OK.
211
+ if (status >= 200 && status < 300) {
212
+ return 'ok';
213
+ }
214
+ switch (status) {
215
+ case 0:
216
+ // This can happen if the server returns 500.
217
+ return 'internal';
218
+ case 400:
219
+ return 'invalid-argument';
220
+ case 401:
221
+ return 'unauthenticated';
222
+ case 403:
223
+ return 'permission-denied';
224
+ case 404:
225
+ return 'not-found';
226
+ case 409:
227
+ return 'aborted';
228
+ case 429:
229
+ return 'resource-exhausted';
230
+ case 499:
231
+ return 'cancelled';
232
+ case 500:
233
+ return 'internal';
234
+ case 501:
235
+ return 'unimplemented';
236
+ case 503:
237
+ return 'unavailable';
238
+ case 504:
239
+ return 'deadline-exceeded';
240
+ }
241
+ return 'unknown';
242
+ }
243
+ /**
244
+ * Takes an HTTP response and returns the corresponding Error, if any.
245
+ */
246
+ function _errorForResponse(status, bodyJSON) {
247
+ let code = codeForHTTPStatus(status);
248
+ // Start with reasonable defaults from the status code.
249
+ let description = code;
250
+ let details = undefined;
251
+ // Then look through the body for explicit details.
252
+ try {
253
+ const errorJSON = bodyJSON && bodyJSON.error;
254
+ if (errorJSON) {
255
+ const status = errorJSON.status;
256
+ if (typeof status === 'string') {
257
+ if (!errorCodeMap[status]) {
258
+ // They must've included an unknown error code in the body.
259
+ return new FunctionsError('internal', 'internal');
260
+ }
261
+ code = errorCodeMap[status];
262
+ // TODO(klimt): Add better default descriptions for error enums.
263
+ // The default description needs to be updated for the new code.
264
+ description = status;
265
+ }
266
+ const message = errorJSON.message;
267
+ if (typeof message === 'string') {
268
+ description = message;
269
+ }
270
+ details = errorJSON.details;
271
+ if (details !== undefined) {
272
+ details = decode(details);
273
+ }
274
+ }
275
+ }
276
+ catch (e) {
277
+ // If we couldn't parse explicit error data, that's fine.
278
+ }
279
+ if (code === 'ok') {
280
+ // Technically, there's an edge case where a developer could explicitly
281
+ // return an error code of OK, and we will treat it as success, but that
282
+ // seems reasonable.
283
+ return null;
284
+ }
285
+ return new FunctionsError(code, description, details);
286
+ }
287
+
288
+ /**
289
+ * @license
290
+ * Copyright 2017 Google LLC
291
+ *
292
+ * Licensed under the Apache License, Version 2.0 (the "License");
293
+ * you may not use this file except in compliance with the License.
294
+ * You may obtain a copy of the License at
295
+ *
296
+ * http://www.apache.org/licenses/LICENSE-2.0
297
+ *
298
+ * Unless required by applicable law or agreed to in writing, software
299
+ * distributed under the License is distributed on an "AS IS" BASIS,
300
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
301
+ * See the License for the specific language governing permissions and
302
+ * limitations under the License.
303
+ */
304
+ /**
305
+ * Helper class to get metadata that should be included with a function call.
306
+ * @internal
307
+ */
308
+ class ContextProvider {
309
+ constructor(app, authProvider, messagingProvider, appCheckProvider) {
310
+ this.app = app;
311
+ this.auth = null;
312
+ this.messaging = null;
313
+ this.appCheck = null;
314
+ this.serverAppAppCheckToken = null;
315
+ if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {
316
+ this.serverAppAppCheckToken = app.settings.appCheckToken;
317
+ }
318
+ this.auth = authProvider.getImmediate({ optional: true });
319
+ this.messaging = messagingProvider.getImmediate({
320
+ optional: true
321
+ });
322
+ if (!this.auth) {
323
+ authProvider.get().then(auth => (this.auth = auth), () => {
324
+ /* get() never rejects */
325
+ });
326
+ }
327
+ if (!this.messaging) {
328
+ messagingProvider.get().then(messaging => (this.messaging = messaging), () => {
329
+ /* get() never rejects */
330
+ });
331
+ }
332
+ if (!this.appCheck) {
333
+ appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck), () => {
334
+ /* get() never rejects */
335
+ });
336
+ }
337
+ }
338
+ async getAuthToken() {
339
+ if (!this.auth) {
340
+ return undefined;
341
+ }
342
+ try {
343
+ const token = await this.auth.getToken();
344
+ return token?.accessToken;
345
+ }
346
+ catch (e) {
347
+ // If there's any error when trying to get the auth token, leave it off.
348
+ return undefined;
349
+ }
350
+ }
351
+ async getMessagingToken() {
352
+ if (!this.messaging ||
353
+ !('Notification' in self) ||
354
+ Notification.permission !== 'granted') {
355
+ return undefined;
356
+ }
357
+ try {
358
+ return await this.messaging.getToken();
359
+ }
360
+ catch (e) {
361
+ // We don't warn on this, because it usually means messaging isn't set up.
362
+ // console.warn('Failed to retrieve instance id token.', e);
363
+ // If there's any error when trying to get the token, leave it off.
364
+ return undefined;
365
+ }
366
+ }
367
+ async getAppCheckToken(limitedUseAppCheckTokens) {
368
+ if (this.serverAppAppCheckToken) {
369
+ return this.serverAppAppCheckToken;
370
+ }
371
+ if (this.appCheck) {
372
+ const result = limitedUseAppCheckTokens
373
+ ? await this.appCheck.getLimitedUseToken()
374
+ : await this.appCheck.getToken();
375
+ if (result.error) {
376
+ // Do not send the App Check header to the functions endpoint if
377
+ // there was an error from the App Check exchange endpoint. The App
378
+ // Check SDK will already have logged the error to console.
379
+ return null;
380
+ }
381
+ return result.token;
382
+ }
383
+ return null;
384
+ }
385
+ async getContext(limitedUseAppCheckTokens) {
386
+ const authToken = await this.getAuthToken();
387
+ const messagingToken = await this.getMessagingToken();
388
+ const appCheckToken = await this.getAppCheckToken(limitedUseAppCheckTokens);
389
+ return { authToken, messagingToken, appCheckToken };
390
+ }
391
+ }
392
+
393
+ /**
394
+ * @license
395
+ * Copyright 2017 Google LLC
396
+ *
397
+ * Licensed under the Apache License, Version 2.0 (the "License");
398
+ * you may not use this file except in compliance with the License.
399
+ * You may obtain a copy of the License at
400
+ *
401
+ * http://www.apache.org/licenses/LICENSE-2.0
402
+ *
403
+ * Unless required by applicable law or agreed to in writing, software
404
+ * distributed under the License is distributed on an "AS IS" BASIS,
405
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
406
+ * See the License for the specific language governing permissions and
407
+ * limitations under the License.
408
+ */
409
+ const DEFAULT_REGION = 'us-central1';
410
+ const responseLineRE = /^data: (.*?)(?:\n|$)/;
411
+ /**
412
+ * Returns a Promise that will be rejected after the given duration.
413
+ * The error will be of type FunctionsError.
414
+ *
415
+ * @param millis Number of milliseconds to wait before rejecting.
416
+ */
417
+ function failAfter(millis) {
418
+ // Node timers and browser timers are fundamentally incompatible, but we
419
+ // don't care about the value here
420
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
421
+ let timer = null;
422
+ return {
423
+ promise: new Promise((_, reject) => {
424
+ timer = setTimeout(() => {
425
+ reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));
426
+ }, millis);
427
+ }),
428
+ cancel: () => {
429
+ if (timer) {
430
+ clearTimeout(timer);
431
+ }
432
+ }
433
+ };
434
+ }
435
+ /**
436
+ * The main class for the Firebase Functions SDK.
437
+ * @internal
438
+ */
439
+ class FunctionsService {
440
+ /**
441
+ * Creates a new Functions service for the given app.
442
+ * @param app - The FirebaseApp to use.
443
+ */
444
+ constructor(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain = DEFAULT_REGION, fetchImpl = (...args) => fetch(...args)) {
445
+ this.app = app;
446
+ this.fetchImpl = fetchImpl;
447
+ this.emulatorOrigin = null;
448
+ this.contextProvider = new ContextProvider(app, authProvider, messagingProvider, appCheckProvider);
449
+ // Cancels all ongoing requests when resolved.
450
+ this.cancelAllRequests = new Promise(resolve => {
451
+ this.deleteService = () => {
452
+ return Promise.resolve(resolve());
453
+ };
454
+ });
455
+ // Resolve the region or custom domain overload by attempting to parse it.
456
+ try {
457
+ const url = new URL(regionOrCustomDomain);
458
+ this.customDomain =
459
+ url.origin + (url.pathname === '/' ? '' : url.pathname);
460
+ this.region = DEFAULT_REGION;
461
+ }
462
+ catch (e) {
463
+ this.customDomain = null;
464
+ this.region = regionOrCustomDomain;
465
+ }
466
+ }
467
+ _delete() {
468
+ return this.deleteService();
469
+ }
470
+ /**
471
+ * Returns the URL for a callable with the given name.
472
+ * @param name - The name of the callable.
473
+ * @internal
474
+ */
475
+ _url(name) {
476
+ const projectId = this.app.options.projectId;
477
+ if (this.emulatorOrigin !== null) {
478
+ const origin = this.emulatorOrigin;
479
+ return `${origin}/${projectId}/${this.region}/${name}`;
480
+ }
481
+ if (this.customDomain !== null) {
482
+ return `${this.customDomain}/${name}`;
483
+ }
484
+ return `https://${this.region}-${projectId}.cloudfunctions.net/${name}`;
485
+ }
486
+ }
487
+ /**
488
+ * Modify this instance to communicate with the Cloud Functions emulator.
489
+ *
490
+ * Note: this must be called before this instance has been used to do any operations.
491
+ *
492
+ * @param host The emulator host (ex: localhost)
493
+ * @param port The emulator port (ex: 5001)
494
+ * @public
495
+ */
496
+ function connectFunctionsEmulator$1(functionsInstance, host, port) {
497
+ const useSsl = isCloudWorkstation(host);
498
+ functionsInstance.emulatorOrigin = `http${useSsl ? 's' : ''}://${host}:${port}`;
499
+ // Workaround to get cookies in Firebase Studio
500
+ if (useSsl) {
501
+ void pingServer(functionsInstance.emulatorOrigin + '/backends');
502
+ updateEmulatorBanner('Functions', true);
503
+ }
504
+ }
505
+ /**
506
+ * Returns a reference to the callable https trigger with the given name.
507
+ * @param name - The name of the trigger.
508
+ * @public
509
+ */
510
+ function httpsCallable$1(functionsInstance, name, options) {
511
+ const callable = (data) => {
512
+ return call(functionsInstance, name, data, options || {});
513
+ };
514
+ callable.stream = (data, options) => {
515
+ return stream(functionsInstance, name, data, options);
516
+ };
517
+ return callable;
518
+ }
519
+ /**
520
+ * Returns a reference to the callable https trigger with the given url.
521
+ * @param url - The url of the trigger.
522
+ * @public
523
+ */
524
+ function httpsCallableFromURL$1(functionsInstance, url, options) {
525
+ const callable = (data) => {
526
+ return callAtURL(functionsInstance, url, data, options || {});
527
+ };
528
+ callable.stream = (data, options) => {
529
+ return streamAtURL(functionsInstance, url, data, options || {});
530
+ };
531
+ return callable;
532
+ }
533
+ function getCredentials(functionsInstance) {
534
+ return functionsInstance.emulatorOrigin &&
535
+ isCloudWorkstation(functionsInstance.emulatorOrigin)
536
+ ? 'include'
537
+ : undefined;
538
+ }
539
+ /**
540
+ * Does an HTTP POST and returns the completed response.
541
+ * @param url The url to post to.
542
+ * @param body The JSON body of the post.
543
+ * @param headers The HTTP headers to include in the request.
544
+ * @param functionsInstance functions instance that is calling postJSON
545
+ * @return A Promise that will succeed when the request finishes.
546
+ */
547
+ async function postJSON(url, body, headers, fetchImpl, functionsInstance) {
548
+ headers['Content-Type'] = 'application/json';
549
+ let response;
550
+ try {
551
+ response = await fetchImpl(url, {
552
+ method: 'POST',
553
+ body: JSON.stringify(body),
554
+ headers,
555
+ credentials: getCredentials(functionsInstance)
556
+ });
557
+ }
558
+ catch (e) {
559
+ // This could be an unhandled error on the backend, or it could be a
560
+ // network error. There's no way to know, since an unhandled error on the
561
+ // backend will fail to set the proper CORS header, and thus will be
562
+ // treated as a network error by fetch.
563
+ return {
564
+ status: 0,
565
+ json: null
566
+ };
567
+ }
568
+ let json = null;
569
+ try {
570
+ json = await response.json();
571
+ }
572
+ catch (e) {
573
+ // If we fail to parse JSON, it will fail the same as an empty body.
574
+ }
575
+ return {
576
+ status: response.status,
577
+ json
578
+ };
579
+ }
580
+ /**
581
+ * Creates authorization headers for Firebase Functions requests.
582
+ * @param functionsInstance The Firebase Functions service instance.
583
+ * @param options Options for the callable function, including AppCheck token settings.
584
+ * @return A Promise that resolves a headers map to include in outgoing fetch request.
585
+ */
586
+ async function makeAuthHeaders(functionsInstance, options) {
587
+ const headers = {};
588
+ const context = await functionsInstance.contextProvider.getContext(options.limitedUseAppCheckTokens);
589
+ if (context.authToken) {
590
+ headers['Authorization'] = 'Bearer ' + context.authToken;
591
+ }
592
+ if (context.messagingToken) {
593
+ headers['Firebase-Instance-ID-Token'] = context.messagingToken;
594
+ }
595
+ if (context.appCheckToken !== null) {
596
+ headers['X-Firebase-AppCheck'] = context.appCheckToken;
597
+ }
598
+ return headers;
599
+ }
600
+ /**
601
+ * Calls a callable function asynchronously and returns the result.
602
+ * @param name The name of the callable trigger.
603
+ * @param data The data to pass as params to the function.
604
+ */
605
+ function call(functionsInstance, name, data, options) {
606
+ const url = functionsInstance._url(name);
607
+ return callAtURL(functionsInstance, url, data, options);
608
+ }
609
+ /**
610
+ * Calls a callable function asynchronously and returns the result.
611
+ * @param url The url of the callable trigger.
612
+ * @param data The data to pass as params to the function.
613
+ */
614
+ async function callAtURL(functionsInstance, url, data, options) {
615
+ // Encode any special types, such as dates, in the input data.
616
+ data = encode(data);
617
+ const body = { data };
618
+ // Add a header for the authToken.
619
+ const headers = await makeAuthHeaders(functionsInstance, options);
620
+ // Default timeout to 70s, but let the options override it.
621
+ const timeout = options.timeout || 70000;
622
+ const failAfterHandle = failAfter(timeout);
623
+ const response = await Promise.race([
624
+ postJSON(url, body, headers, functionsInstance.fetchImpl, functionsInstance),
625
+ failAfterHandle.promise,
626
+ functionsInstance.cancelAllRequests
627
+ ]);
628
+ // Always clear the failAfter timeout
629
+ failAfterHandle.cancel();
630
+ // If service was deleted, interrupted response throws an error.
631
+ if (!response) {
632
+ throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');
633
+ }
634
+ // Check for an error status, regardless of http status.
635
+ const error = _errorForResponse(response.status, response.json);
636
+ if (error) {
637
+ throw error;
638
+ }
639
+ if (!response.json) {
640
+ throw new FunctionsError('internal', 'Response is not valid JSON object.');
641
+ }
642
+ let responseData = response.json.data;
643
+ // TODO(klimt): For right now, allow "result" instead of "data", for
644
+ // backwards compatibility.
645
+ if (typeof responseData === 'undefined') {
646
+ responseData = response.json.result;
647
+ }
648
+ if (typeof responseData === 'undefined') {
649
+ // Consider the response malformed.
650
+ throw new FunctionsError('internal', 'Response is missing data field.');
651
+ }
652
+ // Decode any special types, such as dates, in the returned data.
653
+ const decodedData = decode(responseData);
654
+ return { data: decodedData };
655
+ }
656
+ /**
657
+ * Calls a callable function asynchronously and returns a streaming result.
658
+ * @param name The name of the callable trigger.
659
+ * @param data The data to pass as params to the function.
660
+ * @param options Streaming request options.
661
+ */
662
+ function stream(functionsInstance, name, data, options) {
663
+ const url = functionsInstance._url(name);
664
+ return streamAtURL(functionsInstance, url, data, options || {});
665
+ }
666
+ /**
667
+ * Calls a callable function asynchronously and return a streaming result.
668
+ * @param url The url of the callable trigger.
669
+ * @param data The data to pass as params to the function.
670
+ * @param options Streaming request options.
671
+ */
672
+ async function streamAtURL(functionsInstance, url, data, options) {
673
+ // Encode any special types, such as dates, in the input data.
674
+ data = encode(data);
675
+ const body = { data };
676
+ //
677
+ // Add a header for the authToken.
678
+ const headers = await makeAuthHeaders(functionsInstance, options);
679
+ headers['Content-Type'] = 'application/json';
680
+ headers['Accept'] = 'text/event-stream';
681
+ let response;
682
+ try {
683
+ response = await functionsInstance.fetchImpl(url, {
684
+ method: 'POST',
685
+ body: JSON.stringify(body),
686
+ headers,
687
+ signal: options?.signal,
688
+ credentials: getCredentials(functionsInstance)
689
+ });
690
+ }
691
+ catch (e) {
692
+ if (e instanceof Error && e.name === 'AbortError') {
693
+ const error = new FunctionsError('cancelled', 'Request was cancelled.');
694
+ return {
695
+ data: Promise.reject(error),
696
+ stream: {
697
+ [Symbol.asyncIterator]() {
698
+ return {
699
+ next() {
700
+ return Promise.reject(error);
701
+ }
702
+ };
703
+ }
704
+ }
705
+ };
706
+ }
707
+ // This could be an unhandled error on the backend, or it could be a
708
+ // network error. There's no way to know, since an unhandled error on the
709
+ // backend will fail to set the proper CORS header, and thus will be
710
+ // treated as a network error by fetch.
711
+ const error = _errorForResponse(0, null);
712
+ return {
713
+ data: Promise.reject(error),
714
+ // Return an empty async iterator
715
+ stream: {
716
+ [Symbol.asyncIterator]() {
717
+ return {
718
+ next() {
719
+ return Promise.reject(error);
720
+ }
721
+ };
722
+ }
723
+ }
724
+ };
725
+ }
726
+ let resultResolver;
727
+ let resultRejecter;
728
+ const resultPromise = new Promise((resolve, reject) => {
729
+ resultResolver = resolve;
730
+ resultRejecter = reject;
731
+ });
732
+ options?.signal?.addEventListener('abort', () => {
733
+ const error = new FunctionsError('cancelled', 'Request was cancelled.');
734
+ resultRejecter(error);
735
+ });
736
+ const reader = response.body.getReader();
737
+ const rstream = createResponseStream(reader, resultResolver, resultRejecter, options?.signal);
738
+ return {
739
+ stream: {
740
+ [Symbol.asyncIterator]() {
741
+ const rreader = rstream.getReader();
742
+ return {
743
+ async next() {
744
+ const { value, done } = await rreader.read();
745
+ return { value: value, done };
746
+ },
747
+ async return() {
748
+ await rreader.cancel();
749
+ return { done: true, value: undefined };
750
+ }
751
+ };
752
+ }
753
+ },
754
+ data: resultPromise
755
+ };
756
+ }
757
+ /**
758
+ * Creates a ReadableStream that processes a streaming response from a streaming
759
+ * callable function that returns data in server-sent event format.
760
+ *
761
+ * @param reader The underlying reader providing raw response data
762
+ * @param resultResolver Callback to resolve the final result when received
763
+ * @param resultRejecter Callback to reject with an error if encountered
764
+ * @param signal Optional AbortSignal to cancel the stream processing
765
+ * @returns A ReadableStream that emits decoded messages from the response
766
+ *
767
+ * The returned ReadableStream:
768
+ * 1. Emits individual messages when "message" data is received
769
+ * 2. Resolves with the final result when a "result" message is received
770
+ * 3. Rejects with an error if an "error" message is received
771
+ */
772
+ function createResponseStream(reader, resultResolver, resultRejecter, signal) {
773
+ const processLine = (line, controller) => {
774
+ const match = line.match(responseLineRE);
775
+ // ignore all other lines (newline, comments, etc.)
776
+ if (!match) {
777
+ return;
778
+ }
779
+ const data = match[1];
780
+ try {
781
+ const jsonData = JSON.parse(data);
782
+ if ('result' in jsonData) {
783
+ resultResolver(decode(jsonData.result));
784
+ return;
785
+ }
786
+ if ('message' in jsonData) {
787
+ controller.enqueue(decode(jsonData.message));
788
+ return;
789
+ }
790
+ if ('error' in jsonData) {
791
+ const error = _errorForResponse(0, jsonData);
792
+ controller.error(error);
793
+ resultRejecter(error);
794
+ return;
795
+ }
796
+ }
797
+ catch (error) {
798
+ if (error instanceof FunctionsError) {
799
+ controller.error(error);
800
+ resultRejecter(error);
801
+ return;
802
+ }
803
+ // ignore other parsing errors
804
+ }
805
+ };
806
+ const decoder = new TextDecoder();
807
+ return new ReadableStream({
808
+ start(controller) {
809
+ let currentText = '';
810
+ return pump();
811
+ async function pump() {
812
+ if (signal?.aborted) {
813
+ const error = new FunctionsError('cancelled', 'Request was cancelled');
814
+ controller.error(error);
815
+ resultRejecter(error);
816
+ return Promise.resolve();
817
+ }
818
+ try {
819
+ const { value, done } = await reader.read();
820
+ if (done) {
821
+ if (currentText.trim()) {
822
+ processLine(currentText.trim(), controller);
823
+ }
824
+ controller.close();
825
+ return;
826
+ }
827
+ if (signal?.aborted) {
828
+ const error = new FunctionsError('cancelled', 'Request was cancelled');
829
+ controller.error(error);
830
+ resultRejecter(error);
831
+ await reader.cancel();
832
+ return;
833
+ }
834
+ currentText += decoder.decode(value, { stream: true });
835
+ const lines = currentText.split('\n');
836
+ currentText = lines.pop() || '';
837
+ for (const line of lines) {
838
+ if (line.trim()) {
839
+ processLine(line.trim(), controller);
840
+ }
841
+ }
842
+ return pump();
843
+ }
844
+ catch (error) {
845
+ const functionsError = error instanceof FunctionsError
846
+ ? error
847
+ : _errorForResponse(0, null);
848
+ controller.error(functionsError);
849
+ resultRejecter(functionsError);
850
+ }
851
+ }
852
+ },
853
+ cancel() {
854
+ return reader.cancel();
855
+ }
856
+ });
857
+ }
858
+
859
+ const name = "@firebase/functions";
860
+ const version = "0.13.2";
861
+
862
+ /**
863
+ * @license
864
+ * Copyright 2019 Google LLC
865
+ *
866
+ * Licensed under the Apache License, Version 2.0 (the "License");
867
+ * you may not use this file except in compliance with the License.
868
+ * You may obtain a copy of the License at
869
+ *
870
+ * http://www.apache.org/licenses/LICENSE-2.0
871
+ *
872
+ * Unless required by applicable law or agreed to in writing, software
873
+ * distributed under the License is distributed on an "AS IS" BASIS,
874
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
875
+ * See the License for the specific language governing permissions and
876
+ * limitations under the License.
877
+ */
878
+ const AUTH_INTERNAL_NAME = 'auth-internal';
879
+ const APP_CHECK_INTERNAL_NAME = 'app-check-internal';
880
+ const MESSAGING_INTERNAL_NAME = 'messaging-internal';
881
+ function registerFunctions(variant) {
882
+ const factory = (container, { instanceIdentifier: regionOrCustomDomain }) => {
883
+ // Dependencies
884
+ const app = container.getProvider('app').getImmediate();
885
+ const authProvider = container.getProvider(AUTH_INTERNAL_NAME);
886
+ const messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);
887
+ const appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);
888
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
889
+ return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain);
890
+ };
891
+ _registerComponent(new Component(FUNCTIONS_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
892
+ registerVersion(name, version, variant);
893
+ // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
894
+ registerVersion(name, version, 'esm2020');
895
+ }
896
+
897
+ /**
898
+ * @license
899
+ * Copyright 2020 Google LLC
900
+ *
901
+ * Licensed under the Apache License, Version 2.0 (the "License");
902
+ * you may not use this file except in compliance with the License.
903
+ * You may obtain a copy of the License at
904
+ *
905
+ * http://www.apache.org/licenses/LICENSE-2.0
906
+ *
907
+ * Unless required by applicable law or agreed to in writing, software
908
+ * distributed under the License is distributed on an "AS IS" BASIS,
909
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
910
+ * See the License for the specific language governing permissions and
911
+ * limitations under the License.
912
+ */
913
+ /**
914
+ * Returns a {@link Functions} instance for the given app.
915
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
916
+ * @param regionOrCustomDomain - one of:
917
+ * a) The region the callable functions are located in (ex: us-central1)
918
+ * b) A custom domain hosting the callable functions (ex: https://mydomain.com)
919
+ * @public
920
+ */
921
+ function getFunctions(app = getApp(), regionOrCustomDomain = DEFAULT_REGION) {
922
+ // Dependencies
923
+ const functionsProvider = _getProvider(getModularInstance(app), FUNCTIONS_TYPE);
924
+ const functionsInstance = functionsProvider.getImmediate({
925
+ identifier: regionOrCustomDomain
926
+ });
927
+ const emulator = getDefaultEmulatorHostnameAndPort('functions');
928
+ if (emulator) {
929
+ connectFunctionsEmulator(functionsInstance, ...emulator);
930
+ }
931
+ return functionsInstance;
932
+ }
933
+ /**
934
+ * Modify this instance to communicate with the Cloud Functions emulator.
935
+ *
936
+ * Note: this must be called before this instance has been used to do any operations.
937
+ *
938
+ * @param host - The emulator host (ex: localhost)
939
+ * @param port - The emulator port (ex: 5001)
940
+ * @public
941
+ */
942
+ function connectFunctionsEmulator(functionsInstance, host, port) {
943
+ connectFunctionsEmulator$1(getModularInstance(functionsInstance), host, port);
944
+ }
945
+ /**
946
+ * Returns a reference to the callable HTTPS trigger with the given name.
947
+ * @param name - The name of the trigger.
948
+ * @public
949
+ */
950
+ function httpsCallable(functionsInstance, name, options) {
951
+ return httpsCallable$1(getModularInstance(functionsInstance), name, options);
952
+ }
953
+ /**
954
+ * Returns a reference to the callable HTTPS trigger with the specified url.
955
+ * @param url - The url of the trigger.
956
+ * @public
957
+ */
958
+ function httpsCallableFromURL(functionsInstance, url, options) {
959
+ return httpsCallableFromURL$1(getModularInstance(functionsInstance), url, options);
960
+ }
961
+
962
+ /**
963
+ * Cloud Functions for Firebase
964
+ *
965
+ * @packageDocumentation
966
+ */
967
+ registerFunctions();
968
+
969
+ export { FunctionsError, connectFunctionsEmulator, getFunctions, httpsCallable, httpsCallableFromURL };
970
+ //# sourceMappingURL=index.esm.js.map