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